visionclaw 0.1.220-beta.2 → 0.1.220-beta.21
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/README.md +2 -2
- package/dist/agent/activity-tracker.d.ts +8 -17
- package/dist/agent/activity-tracker.d.ts.map +1 -1
- package/dist/agent/activity-tracker.js +11 -25
- package/dist/agent/activity-tracker.js.map +1 -1
- package/dist/agent/command-handlers.js +1 -1
- package/dist/agent/command-handlers.js.map +1 -1
- package/dist/agent/context.d.ts +0 -22
- package/dist/agent/context.d.ts.map +1 -1
- package/dist/agent/context.js +0 -79
- package/dist/agent/context.js.map +1 -1
- package/dist/agent/engine-switch-handler.d.ts +2 -2
- package/dist/agent/engine-switch-handler.js +3 -3
- package/dist/agent/engine-switch-handler.js.map +1 -1
- package/dist/agent/engine-switch-target.d.ts.map +1 -1
- package/dist/agent/engine-switch-target.js +5 -1
- package/dist/agent/engine-switch-target.js.map +1 -1
- package/dist/agent/engine-switch.d.ts +4 -4
- package/dist/agent/engine-switch.d.ts.map +1 -1
- package/dist/agent/engine-switch.js +9 -3
- package/dist/agent/engine-switch.js.map +1 -1
- package/dist/agent/engines/claude/session.d.ts +2 -1
- package/dist/agent/engines/claude/session.d.ts.map +1 -1
- package/dist/agent/engines/claude/session.js +5 -4
- package/dist/agent/engines/claude/session.js.map +1 -1
- package/dist/agent/engines/pi/tools.d.ts.map +1 -1
- package/dist/agent/engines/pi/tools.js +3 -1
- package/dist/agent/engines/pi/tools.js.map +1 -1
- package/dist/agent/engines/pi-coding/mcp-config.d.ts +10 -1
- package/dist/agent/engines/pi-coding/mcp-config.d.ts.map +1 -1
- package/dist/agent/engines/pi-coding/mcp-config.js +4 -7
- package/dist/agent/engines/pi-coding/mcp-config.js.map +1 -1
- package/dist/agent/engines/pi-coding/session.d.ts +1 -1
- package/dist/agent/engines/pi-coding/session.d.ts.map +1 -1
- package/dist/agent/engines/pi-coding/session.js +17 -22
- package/dist/agent/engines/pi-coding/session.js.map +1 -1
- package/dist/agent/engines/session-types.d.ts +2 -0
- package/dist/agent/engines/session-types.d.ts.map +1 -1
- package/dist/agent/fast-response-eligibility.d.ts +2 -2
- package/dist/agent/fast-response-eligibility.d.ts.map +1 -1
- package/dist/agent/fast-response-eligibility.js +10 -2
- package/dist/agent/fast-response-eligibility.js.map +1 -1
- package/dist/agent/interrupt-handler.d.ts +2 -2
- package/dist/agent/interrupt-handler.js +4 -4
- package/dist/agent/interrupt-handler.js.map +1 -1
- package/dist/agent/llm-engine-capabilities.d.ts.map +1 -1
- package/dist/agent/llm-engine-capabilities.js +4 -1
- package/dist/agent/llm-engine-capabilities.js.map +1 -1
- package/dist/agent/loop.d.ts +0 -2
- package/dist/agent/loop.d.ts.map +1 -1
- package/dist/agent/loop.js +12 -4
- package/dist/agent/loop.js.map +1 -1
- package/dist/agent/model-provider.d.ts +1 -7
- package/dist/agent/model-provider.d.ts.map +1 -1
- package/dist/agent/model-provider.js +2 -10
- package/dist/agent/model-provider.js.map +1 -1
- package/dist/agent/owner-initiated-eligibility.d.ts +2 -0
- package/dist/agent/owner-initiated-eligibility.d.ts.map +1 -1
- package/dist/agent/owner-initiated-eligibility.js +5 -15
- package/dist/agent/owner-initiated-eligibility.js.map +1 -1
- package/dist/agent/reply-watchdog.d.ts +1 -1
- package/dist/agent/reply-watchdog.js +2 -2
- package/dist/agent/reply-watchdog.js.map +1 -1
- package/dist/agent/runtime-surface.d.ts +2 -0
- package/dist/agent/runtime-surface.d.ts.map +1 -1
- package/dist/agent/runtime-surface.js +12 -2
- package/dist/agent/runtime-surface.js.map +1 -1
- package/dist/agent/status.js +1 -1
- package/dist/agent/status.js.map +1 -1
- package/dist/agent/stream-handler.d.ts.map +1 -1
- package/dist/agent/stream-handler.js +48 -22
- package/dist/agent/stream-handler.js.map +1 -1
- package/dist/agent/system-prompt.d.ts.map +1 -1
- package/dist/agent/system-prompt.js +10 -4
- package/dist/agent/system-prompt.js.map +1 -1
- package/dist/agent/wake-cycle-runner.d.ts +1 -1
- package/dist/agent/wake-cycle-runner.d.ts.map +1 -1
- package/dist/agent/wake-cycle-runner.js +2 -3
- package/dist/agent/wake-cycle-runner.js.map +1 -1
- package/dist/builtin-skills/rethinka-fund/SKILL.md +287 -28
- package/dist/builtin-skills/rethinka-fund/core-contract.md +30 -14
- package/dist/channels/interface.d.ts +0 -34
- package/dist/channels/interface.d.ts.map +1 -1
- package/dist/channels/manager.d.ts.map +1 -1
- package/dist/channels/manager.js +4 -0
- package/dist/channels/manager.js.map +1 -1
- package/dist/channels/qq.js +1 -1
- package/dist/channels/qq.js.map +1 -1
- package/dist/channels/rethinka-fund.d.ts +16 -3
- package/dist/channels/rethinka-fund.d.ts.map +1 -1
- package/dist/channels/rethinka-fund.js +180 -16
- package/dist/channels/rethinka-fund.js.map +1 -1
- package/dist/channels/telegram.js +1 -1
- package/dist/channels/telegram.js.map +1 -1
- package/dist/channels/tui-commands.js +1 -1
- package/dist/channels/tui-commands.js.map +1 -1
- package/dist/config/types.d.ts +4 -2
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/obs/mini-app/status.d.ts.map +1 -1
- package/dist/obs/mini-app/status.js +63 -0
- package/dist/obs/mini-app/status.js.map +1 -1
- package/dist/obs/mini-app/telegram-auth.d.ts +23 -0
- package/dist/obs/mini-app/telegram-auth.d.ts.map +1 -0
- package/dist/obs/mini-app/telegram-auth.js +55 -0
- package/dist/obs/mini-app/telegram-auth.js.map +1 -0
- package/dist/obs/rdp/linux-x11-backend.d.ts +9 -0
- package/dist/obs/rdp/linux-x11-backend.d.ts.map +1 -1
- package/dist/obs/rdp/linux-x11-backend.js +69 -33
- package/dist/obs/rdp/linux-x11-backend.js.map +1 -1
- package/dist/obs/server.d.ts.map +1 -1
- package/dist/obs/server.js +29 -0
- package/dist/obs/server.js.map +1 -1
- package/dist/reconfigure.d.ts.map +1 -1
- package/dist/reconfigure.js +7 -1
- package/dist/reconfigure.js.map +1 -1
- package/dist/rethinka-fund/hyperliquid-signing.d.ts +56 -0
- package/dist/rethinka-fund/hyperliquid-signing.d.ts.map +1 -0
- package/dist/rethinka-fund/hyperliquid-signing.js +159 -0
- package/dist/rethinka-fund/hyperliquid-signing.js.map +1 -0
- package/dist/rethinka-fund/hyperliquid-trading.d.ts +154 -0
- package/dist/rethinka-fund/hyperliquid-trading.d.ts.map +1 -0
- package/dist/rethinka-fund/hyperliquid-trading.js +673 -0
- package/dist/rethinka-fund/hyperliquid-trading.js.map +1 -0
- package/dist/rethinka-fund/ibkr-flex.d.ts +49 -0
- package/dist/rethinka-fund/ibkr-flex.d.ts.map +1 -0
- package/dist/rethinka-fund/ibkr-flex.js +182 -0
- package/dist/rethinka-fund/ibkr-flex.js.map +1 -0
- package/dist/rethinka-fund/ibkr-mcp.d.ts +119 -0
- package/dist/rethinka-fund/ibkr-mcp.d.ts.map +1 -0
- package/dist/rethinka-fund/ibkr-mcp.js +418 -0
- package/dist/rethinka-fund/ibkr-mcp.js.map +1 -0
- package/dist/rethinka-fund/ibkr-sync.d.ts +30 -17
- package/dist/rethinka-fund/ibkr-sync.d.ts.map +1 -1
- package/dist/rethinka-fund/ibkr-sync.js +66 -31
- package/dist/rethinka-fund/ibkr-sync.js.map +1 -1
- package/dist/rethinka-fund/ibkr-trading.d.ts +102 -0
- package/dist/rethinka-fund/ibkr-trading.d.ts.map +1 -0
- package/dist/rethinka-fund/ibkr-trading.js +594 -0
- package/dist/rethinka-fund/ibkr-trading.js.map +1 -0
- package/dist/rethinka-fund/order-refresh.d.ts +66 -0
- package/dist/rethinka-fund/order-refresh.d.ts.map +1 -0
- package/dist/rethinka-fund/order-refresh.js +195 -0
- package/dist/rethinka-fund/order-refresh.js.map +1 -0
- package/dist/rethinka-fund/polymarket-redeem.d.ts +82 -0
- package/dist/rethinka-fund/polymarket-redeem.d.ts.map +1 -0
- package/dist/rethinka-fund/polymarket-redeem.js +353 -0
- package/dist/rethinka-fund/polymarket-redeem.js.map +1 -0
- package/dist/rethinka-fund/polymarket-trading.d.ts +61 -30
- package/dist/rethinka-fund/polymarket-trading.d.ts.map +1 -1
- package/dist/rethinka-fund/polymarket-trading.js +183 -71
- package/dist/rethinka-fund/polymarket-trading.js.map +1 -1
- package/dist/rethinka-fund/trading-common.d.ts +157 -0
- package/dist/rethinka-fund/trading-common.d.ts.map +1 -0
- package/dist/rethinka-fund/trading-common.js +237 -0
- package/dist/rethinka-fund/trading-common.js.map +1 -0
- package/dist/rethinka-fund-credentials.d.ts +2 -0
- package/dist/rethinka-fund-credentials.d.ts.map +1 -1
- package/dist/rethinka-fund-credentials.js +2 -0
- package/dist/rethinka-fund-credentials.js.map +1 -1
- package/dist/sites/manager.d.ts +50 -0
- package/dist/sites/manager.d.ts.map +1 -0
- package/dist/sites/manager.js +353 -0
- package/dist/sites/manager.js.map +1 -0
- package/dist/sites/pm2-injected-env.d.ts +49 -0
- package/dist/sites/pm2-injected-env.d.ts.map +1 -0
- package/dist/sites/pm2-injected-env.js +160 -0
- package/dist/sites/pm2-injected-env.js.map +1 -0
- package/dist/sites/process.d.ts +20 -0
- package/dist/sites/process.d.ts.map +1 -0
- package/dist/sites/process.js +122 -0
- package/dist/sites/process.js.map +1 -0
- package/dist/sites/registry.d.ts +79 -0
- package/dist/sites/registry.d.ts.map +1 -0
- package/dist/sites/registry.js +147 -0
- package/dist/sites/registry.js.map +1 -0
- package/dist/threads/execution-snapshot.d.ts +1 -0
- package/dist/threads/execution-snapshot.d.ts.map +1 -1
- package/dist/threads/foreground-task.d.ts +16 -3
- package/dist/threads/foreground-task.d.ts.map +1 -1
- package/dist/threads/foreground-task.js +57 -7
- package/dist/threads/foreground-task.js.map +1 -1
- package/dist/threads/foreman-execution.d.ts +14 -2
- package/dist/threads/foreman-execution.d.ts.map +1 -1
- package/dist/threads/foreman-execution.js +15 -3
- package/dist/threads/foreman-execution.js.map +1 -1
- package/dist/threads/foreman-host.d.ts +1 -0
- package/dist/threads/foreman-host.d.ts.map +1 -1
- package/dist/threads/foreman-host.js +27 -5
- package/dist/threads/foreman-host.js.map +1 -1
- package/dist/threads/foreman-protocol.d.ts +1 -0
- package/dist/threads/foreman-protocol.d.ts.map +1 -1
- package/dist/threads/foreman-protocol.js +2 -2
- package/dist/threads/foreman-protocol.js.map +1 -1
- package/dist/threads/foreman-write-contract.d.ts +1 -1
- package/dist/threads/foreman-write-contract.d.ts.map +1 -1
- package/dist/threads/foreman-write-contract.js +1 -1
- package/dist/threads/foreman-write-contract.js.map +1 -1
- package/dist/threads/supervisor.d.ts +2 -1
- package/dist/threads/supervisor.d.ts.map +1 -1
- package/dist/threads/supervisor.js +4 -1
- package/dist/threads/supervisor.js.map +1 -1
- package/dist/threads/thread-meta.d.ts +1 -0
- package/dist/threads/thread-meta.d.ts.map +1 -1
- package/dist/tools/delegation.d.ts.map +1 -1
- package/dist/tools/delegation.js +4 -1
- package/dist/tools/delegation.js.map +1 -1
- package/dist/tools/email.d.ts +1 -1
- package/dist/tools/event-trigger.d.ts +2 -2
- package/dist/tools/finish.d.ts.map +1 -1
- package/dist/tools/finish.js +5 -1
- package/dist/tools/finish.js.map +1 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +4 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/rethinka-fund-trading.d.ts +137 -1
- package/dist/tools/rethinka-fund-trading.d.ts.map +1 -1
- package/dist/tools/rethinka-fund-trading.js +102 -5
- package/dist/tools/rethinka-fund-trading.js.map +1 -1
- package/dist/tools/sites.d.ts +24 -0
- package/dist/tools/sites.d.ts.map +1 -0
- package/dist/tools/sites.js +61 -0
- package/dist/tools/sites.js.map +1 -0
- package/dist/tui/index.js +1 -1
- package/dist-agent/bundle.cjs +2 -2
- package/dist-agent/image-resize-worker.js +1 -0
- package/dist-agent/image-resize-worker.mjs +375 -0
- package/dist-agent/mcp-script-worker.mjs +6 -2
- package/package.json +8 -8
- package/dist/agent/fast-responder.d.ts +0 -52
- package/dist/agent/fast-responder.d.ts.map +0 -1
- package/dist/agent/fast-responder.js +0 -213
- package/dist/agent/fast-responder.js.map +0 -1
- package/dist/rethinka-fund/ibkr-collect.d.ts +0 -70
- package/dist/rethinka-fund/ibkr-collect.d.ts.map +0 -1
- package/dist/rethinka-fund/ibkr-collect.js +0 -180
- package/dist/rethinka-fund/ibkr-collect.js.map +0 -1
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hyperliquid order placement for the Rethinka Fund agent.
|
|
3
|
+
*
|
|
4
|
+
* Deterministic code that ships with the agent, on the same pattern as the
|
|
5
|
+
* Polymarket tool (./polymarket-trading.ts): the model names a decision, and
|
|
6
|
+
* everything that matters is taken from that decision or checked against it.
|
|
7
|
+
*
|
|
8
|
+
* 1. The decision is read from the Rethinka Fund server, which says whether
|
|
9
|
+
* an order may be placed under it now. No decision, no order.
|
|
10
|
+
* 2. Instrument, side and reduce-only come from the decision. The price may
|
|
11
|
+
* not be worse than its limit, and the order must fit in what is left of
|
|
12
|
+
* its size.
|
|
13
|
+
* 3. For an order that can open or add to a perp position, the mandate's
|
|
14
|
+
* instrument switches and leverage cap are checked against the account's
|
|
15
|
+
* current leverage for that coin.
|
|
16
|
+
* 4. The order is recorded on the server, then signed on this host with the
|
|
17
|
+
* key from a local settings file and sent straight to Hyperliquid. There
|
|
18
|
+
* is no relay in between: the exchange is reachable from the agent's
|
|
19
|
+
* host, and a relay would hold no key and stop nothing.
|
|
20
|
+
* 5. The outcome is reported back. Every order carries a client order id
|
|
21
|
+
* and a short expiry, so when the answer is lost the tool asks the
|
|
22
|
+
* exchange what became of it instead of guessing.
|
|
23
|
+
*
|
|
24
|
+
* The settings file is written by the owner on this host, not through chat.
|
|
25
|
+
*/
|
|
26
|
+
import { randomUUID } from "node:crypto";
|
|
27
|
+
import path from "node:path";
|
|
28
|
+
import { z } from "zod";
|
|
29
|
+
import { getSharedProfileDir } from "../config/index.js";
|
|
30
|
+
import { createL1Signer, floatToWire } from "./hyperliquid-signing.js";
|
|
31
|
+
import { errorText, fundCall, readDecision, readKeyFile, refreshDecisionOrders, reportOrder } from "./trading-common.js";
|
|
32
|
+
export const HYPERLIQUID_SETTINGS_FILE = "rethinka-fund-hyperliquid.json";
|
|
33
|
+
const API_URL = "https://api.hyperliquid.xyz";
|
|
34
|
+
/** How long the exchange may still accept a submitted order. Short, so a lost answer can be settled. */
|
|
35
|
+
const ORDER_EXPIRY_MS = 15_000;
|
|
36
|
+
const MIN_ORDER_USD = 10;
|
|
37
|
+
export const HyperliquidSettingsSchema = z.object({
|
|
38
|
+
/** The signing key: the dedicated wallet's own key, or the key of an API wallet that wallet approved. Read by this module only. */
|
|
39
|
+
privateKey: z.string().trim().regex(/^0x[0-9a-fA-F]{64}$/),
|
|
40
|
+
/** The account that holds the funds and positions: the address added in the console. */
|
|
41
|
+
account: z.string().trim().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
42
|
+
}).strict();
|
|
43
|
+
export function hyperliquidSettingsPath() {
|
|
44
|
+
return path.join(getSharedProfileDir(), HYPERLIQUID_SETTINGS_FILE);
|
|
45
|
+
}
|
|
46
|
+
export function readHyperliquidSettings(file = hyperliquidSettingsPath()) {
|
|
47
|
+
return readKeyFile(file, HyperliquidSettingsSchema);
|
|
48
|
+
}
|
|
49
|
+
function record(value) {
|
|
50
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
51
|
+
}
|
|
52
|
+
function list(value) {
|
|
53
|
+
return Array.isArray(value) ? value : [];
|
|
54
|
+
}
|
|
55
|
+
function settingsOrReason(deps) {
|
|
56
|
+
const read = readHyperliquidSettings(deps.settingsFile);
|
|
57
|
+
if (read.status === "absent")
|
|
58
|
+
return { reason: `Hyperliquid trading is not set up on this agent: the owner has not created ${deps.settingsFile ?? hyperliquidSettingsPath()} on this host yet.` };
|
|
59
|
+
if (read.status === "invalid")
|
|
60
|
+
return { reason: `Hyperliquid trading settings are not usable: ${read.reason}` };
|
|
61
|
+
return { settings: read.settings };
|
|
62
|
+
}
|
|
63
|
+
/** A read from the public info endpoint, with the exchange's clock as the reply carried it. */
|
|
64
|
+
async function info(deps, body) {
|
|
65
|
+
const reply = await (deps.http ?? fetch)(`${API_URL}/info`, {
|
|
66
|
+
method: "POST",
|
|
67
|
+
headers: { "content-type": "application/json" },
|
|
68
|
+
body: JSON.stringify(body),
|
|
69
|
+
signal: AbortSignal.timeout(15_000),
|
|
70
|
+
});
|
|
71
|
+
if (!reply.ok)
|
|
72
|
+
throw new Error(`Hyperliquid info ${String(body.type)} returned HTTP ${reply.status}`);
|
|
73
|
+
const date = Date.parse(reply.headers.get("date") ?? "");
|
|
74
|
+
return { data: (await reply.json()), serverTime: Number.isFinite(date) ? date : null };
|
|
75
|
+
}
|
|
76
|
+
let universe = null;
|
|
77
|
+
let builderUniverse = null;
|
|
78
|
+
let perpDexList = null;
|
|
79
|
+
const UNIVERSE_TTL_MS = 5 * 60_000;
|
|
80
|
+
function addPerpUniverse(assets, data, dex, dexIndex) {
|
|
81
|
+
list(record(data).universe).forEach((entry, index) => {
|
|
82
|
+
const perp = record(entry);
|
|
83
|
+
if (typeof perp.name !== "string" || typeof perp.szDecimals !== "number" || perp.isDelisted === true)
|
|
84
|
+
return;
|
|
85
|
+
const asset = dex === "" ? index : 100_000 + dexIndex * 10_000 + index;
|
|
86
|
+
assets.set(perp.name, {
|
|
87
|
+
asset,
|
|
88
|
+
coin: perp.name,
|
|
89
|
+
kind: "perp",
|
|
90
|
+
dex,
|
|
91
|
+
szDecimals: perp.szDecimals,
|
|
92
|
+
maxLeverage: typeof perp.maxLeverage === "number" ? perp.maxLeverage : null,
|
|
93
|
+
onlyIsolated: perp.onlyIsolated === true || perp.marginMode === "strictIsolated" || perp.marginMode === "noCross",
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
async function loadUniverse(deps) {
|
|
98
|
+
const now = (deps.now ?? Date.now)();
|
|
99
|
+
if (universe && now - universe.at < UNIVERSE_TTL_MS)
|
|
100
|
+
return universe.assets;
|
|
101
|
+
const [meta, spotMeta] = await Promise.all([info(deps, { type: "meta" }), info(deps, { type: "spotMeta" })]);
|
|
102
|
+
const assets = new Map();
|
|
103
|
+
addPerpUniverse(assets, meta.data, "", 0);
|
|
104
|
+
const tokens = new Map();
|
|
105
|
+
for (const entry of list(record(spotMeta.data).tokens)) {
|
|
106
|
+
const token = record(entry);
|
|
107
|
+
if (typeof token.index === "number" && typeof token.name === "string" && typeof token.szDecimals === "number")
|
|
108
|
+
tokens.set(token.index, { name: token.name, szDecimals: token.szDecimals });
|
|
109
|
+
}
|
|
110
|
+
for (const entry of list(record(spotMeta.data).universe)) {
|
|
111
|
+
const pair = record(entry);
|
|
112
|
+
const [baseIndex, quoteIndex] = list(pair.tokens);
|
|
113
|
+
const base = typeof baseIndex === "number" ? tokens.get(baseIndex) : undefined;
|
|
114
|
+
const quote = typeof quoteIndex === "number" ? tokens.get(quoteIndex) : undefined;
|
|
115
|
+
if (!base || !quote || typeof pair.name !== "string" || typeof pair.index !== "number")
|
|
116
|
+
continue;
|
|
117
|
+
const asset = { asset: 10_000 + pair.index, coin: pair.name, kind: "spot", dex: "", szDecimals: base.szDecimals, maxLeverage: null, onlyIsolated: false };
|
|
118
|
+
// Reachable by the exchange's own pair name and by BASE/QUOTE. The first pair listed for a BASE/QUOTE wins.
|
|
119
|
+
assets.set(pair.name, asset);
|
|
120
|
+
const spelled = `${base.name}/${quote.name}`;
|
|
121
|
+
if (!assets.has(spelled))
|
|
122
|
+
assets.set(spelled, asset);
|
|
123
|
+
}
|
|
124
|
+
universe = { at: now, assets };
|
|
125
|
+
return assets;
|
|
126
|
+
}
|
|
127
|
+
async function loadBuilderUniverse(deps) {
|
|
128
|
+
const now = (deps.now ?? Date.now)();
|
|
129
|
+
if (builderUniverse && now - builderUniverse.at < UNIVERSE_TTL_MS)
|
|
130
|
+
return builderUniverse.assets;
|
|
131
|
+
const entries = await loadPerpDexList(deps);
|
|
132
|
+
const assets = new Map();
|
|
133
|
+
await Promise.all(entries.map(async ({ name, index }) => {
|
|
134
|
+
if (!name)
|
|
135
|
+
return;
|
|
136
|
+
const meta = await info(deps, { type: "meta", dex: name });
|
|
137
|
+
addPerpUniverse(assets, meta.data, name, index);
|
|
138
|
+
}));
|
|
139
|
+
builderUniverse = { at: now, assets };
|
|
140
|
+
return assets;
|
|
141
|
+
}
|
|
142
|
+
async function loadPerpDexList(deps) {
|
|
143
|
+
const now = (deps.now ?? Date.now)();
|
|
144
|
+
if (perpDexList && now - perpDexList.at < UNIVERSE_TTL_MS)
|
|
145
|
+
return perpDexList.entries;
|
|
146
|
+
const dexes = await info(deps, { type: "perpDexs" });
|
|
147
|
+
const entries = [{ name: "", index: 0 }];
|
|
148
|
+
list(dexes.data).forEach((entry, index) => {
|
|
149
|
+
const dex = record(entry);
|
|
150
|
+
if (index > 0 && typeof dex.name === "string" && dex.name)
|
|
151
|
+
entries.push({ name: dex.name, index });
|
|
152
|
+
});
|
|
153
|
+
perpDexList = { at: now, entries };
|
|
154
|
+
return entries;
|
|
155
|
+
}
|
|
156
|
+
async function resolveAsset(deps, symbol) {
|
|
157
|
+
const found = (await loadUniverse(deps)).get(symbol)
|
|
158
|
+
?? (symbol.includes(":") ? (await loadBuilderUniverse(deps)).get(symbol) : undefined);
|
|
159
|
+
if (found)
|
|
160
|
+
return found;
|
|
161
|
+
return {
|
|
162
|
+
reason: `Hyperliquid lists no instrument "${symbol}". Use the perp's coin exactly as listed (e.g. "BTC" or "xyz:TSLA") or the spot pair (e.g. "PURR/USDC").`,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* A price the exchange accepts: at most 5 significant figures and at most
|
|
167
|
+
* (6 for perps, 8 for spot) minus szDecimals decimal places; whole numbers
|
|
168
|
+
* always pass. Rounded toward the cheaper side for the order, so the result
|
|
169
|
+
* is never worse than the price asked for: down for a buy, up for a sell.
|
|
170
|
+
*/
|
|
171
|
+
export function roundPrice(price, asset, isBuy) {
|
|
172
|
+
const maxDecimals = Math.max(0, (asset.kind === "spot" ? 8 : 6) - asset.szDecimals);
|
|
173
|
+
const magnitude = Math.floor(Math.log10(price)) + 1;
|
|
174
|
+
const decimals = Math.min(maxDecimals, Math.max(0, 5 - magnitude));
|
|
175
|
+
const factor = 10 ** decimals;
|
|
176
|
+
// Absorb binary noise (0.1 + 0.2) before choosing a direction.
|
|
177
|
+
const scaled = Number((price * factor).toFixed(6));
|
|
178
|
+
return Number(((isBuy ? Math.floor(scaled) : Math.ceil(scaled)) / factor).toFixed(decimals));
|
|
179
|
+
}
|
|
180
|
+
/** A size the exchange accepts: szDecimals places, rounded down so an order is never larger than asked. */
|
|
181
|
+
export function roundSize(size, szDecimals) {
|
|
182
|
+
const factor = 10 ** szDecimals;
|
|
183
|
+
return Number((Math.floor(Number((size * factor).toFixed(6))) / factor).toFixed(szDecimals));
|
|
184
|
+
}
|
|
185
|
+
const signers = new Map();
|
|
186
|
+
const lastNonce = new Map();
|
|
187
|
+
function signerFor(settings) {
|
|
188
|
+
let signer = signers.get(settings.privateKey);
|
|
189
|
+
if (!signer) {
|
|
190
|
+
signer = createL1Signer(settings.privateKey);
|
|
191
|
+
signers.set(settings.privateKey, signer);
|
|
192
|
+
signer.catch(() => signers.delete(settings.privateKey));
|
|
193
|
+
}
|
|
194
|
+
return signer;
|
|
195
|
+
}
|
|
196
|
+
/** Strictly increasing per signing key, as the exchange requires, and close to the clock. */
|
|
197
|
+
function nextNonce(signer, now) {
|
|
198
|
+
const nonce = Math.max(now, (lastNonce.get(signer.address) ?? 0) + 1);
|
|
199
|
+
lastNonce.set(signer.address, nonce);
|
|
200
|
+
return nonce;
|
|
201
|
+
}
|
|
202
|
+
async function exchange(deps, settings, action, expiresAfter) {
|
|
203
|
+
const signer = await signerFor(settings);
|
|
204
|
+
const nonce = nextNonce(signer, (deps.now ?? Date.now)());
|
|
205
|
+
const signature = signer.sign({ action, nonce, expiresAfter });
|
|
206
|
+
let reply;
|
|
207
|
+
try {
|
|
208
|
+
reply = await (deps.http ?? fetch)(`${API_URL}/exchange`, {
|
|
209
|
+
method: "POST",
|
|
210
|
+
headers: { "content-type": "application/json" },
|
|
211
|
+
body: JSON.stringify({ action, nonce, signature, vaultAddress: null, ...(expiresAfter === null ? {} : { expiresAfter }) }),
|
|
212
|
+
signal: AbortSignal.timeout(20_000),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
catch (err) {
|
|
216
|
+
return { answered: false, why: errorText(err) };
|
|
217
|
+
}
|
|
218
|
+
const text = await reply.text().catch(() => "");
|
|
219
|
+
let body;
|
|
220
|
+
try {
|
|
221
|
+
body = JSON.parse(text);
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
return { answered: false, why: `HTTP ${reply.status}: ${text.slice(0, 200) || "no body"}` };
|
|
225
|
+
}
|
|
226
|
+
const parsed = record(body);
|
|
227
|
+
// Only the exchange's own two verdicts count as an answer.
|
|
228
|
+
if (parsed.status === "ok" || parsed.status === "err")
|
|
229
|
+
return { answered: true, body: parsed };
|
|
230
|
+
return { answered: false, why: `HTTP ${reply.status}: ${text.slice(0, 200)}` };
|
|
231
|
+
}
|
|
232
|
+
/** What the exchange's reply to an order action says became of the one order in it. */
|
|
233
|
+
export function readOrderReply(body) {
|
|
234
|
+
if (body.status === "err")
|
|
235
|
+
return { status: "rejected", detail: typeof body.response === "string" ? body.response : JSON.stringify(body.response ?? "").slice(0, 300), orderId: null };
|
|
236
|
+
const statuses = list(record(record(body.response).data).statuses);
|
|
237
|
+
const first = statuses[0];
|
|
238
|
+
if (typeof first === "string")
|
|
239
|
+
return { status: "submitted", detail: first, orderId: null };
|
|
240
|
+
const status = record(first);
|
|
241
|
+
if (typeof status.error === "string")
|
|
242
|
+
return { status: "rejected", detail: status.error, orderId: null };
|
|
243
|
+
const resting = record(status.resting);
|
|
244
|
+
if (typeof resting.oid === "number")
|
|
245
|
+
return { status: "submitted", detail: "resting", orderId: String(resting.oid) };
|
|
246
|
+
const filled = record(status.filled);
|
|
247
|
+
if (typeof filled.oid === "number") {
|
|
248
|
+
return { status: "submitted", detail: `filled ${String(filled.totalSz)} @ ${String(filled.avgPx)}`, orderId: String(filled.oid), filled: { size: String(filled.totalSz), averagePrice: String(filled.avgPx) } };
|
|
249
|
+
}
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
/** What `orderStatus` says about an order looked up by its client order id. */
|
|
253
|
+
export function readOrderStatus(data) {
|
|
254
|
+
const body = record(data);
|
|
255
|
+
if (body.status === "unknownOid")
|
|
256
|
+
return "not_found";
|
|
257
|
+
if (body.status !== "order")
|
|
258
|
+
return null;
|
|
259
|
+
const wrapper = record(body.order);
|
|
260
|
+
const state = typeof wrapper.status === "string" ? wrapper.status : "";
|
|
261
|
+
const oid = record(wrapper.order).oid;
|
|
262
|
+
const orderId = typeof oid === "number" ? String(oid) : null;
|
|
263
|
+
if (!state)
|
|
264
|
+
return null;
|
|
265
|
+
// "rejected" and the "...Rejected" family never rested and never filled.
|
|
266
|
+
if (/rejected$/i.test(state))
|
|
267
|
+
return { status: "rejected", detail: state, orderId };
|
|
268
|
+
return { status: "submitted", detail: state, orderId };
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Settle an order whose submission got no readable answer. The order carried
|
|
272
|
+
* an expiry, so once the exchange's own clock is past it, an order the
|
|
273
|
+
* exchange has no record of can no longer arrive: it was not placed.
|
|
274
|
+
*/
|
|
275
|
+
async function settleLostOrder(deps, settings, cloid, expiresAfter, why) {
|
|
276
|
+
const now = deps.now ?? Date.now;
|
|
277
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
278
|
+
let lastProblem = why;
|
|
279
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
280
|
+
const wait = expiresAfter + 3_000 - now();
|
|
281
|
+
if (wait > 0)
|
|
282
|
+
await sleep(wait);
|
|
283
|
+
else if (attempt > 0)
|
|
284
|
+
await sleep(3_000);
|
|
285
|
+
try {
|
|
286
|
+
const lookup = await info(deps, { type: "orderStatus", user: settings.account, oid: cloid });
|
|
287
|
+
const read = readOrderStatus(lookup.data);
|
|
288
|
+
if (read === "not_found") {
|
|
289
|
+
// Judged by the exchange's clock, not this host's.
|
|
290
|
+
if (lookup.serverTime !== null && lookup.serverTime > expiresAfter + 2_000) {
|
|
291
|
+
return { status: "rejected", detail: `not placed: the exchange has no record of it and its expiry has passed (${why})`, orderId: null };
|
|
292
|
+
}
|
|
293
|
+
lastProblem = `${why}; the exchange has no record of the order yet`;
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
if (read)
|
|
297
|
+
return { ...read, detail: `${read.detail} (answer to the submission was lost: ${why})` };
|
|
298
|
+
lastProblem = `${why}; order status could not be read`;
|
|
299
|
+
}
|
|
300
|
+
catch (err) {
|
|
301
|
+
lastProblem = `${why}; order status lookup failed: ${errorText(err)}`;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return { status: "unknown", detail: lastProblem, orderId: null };
|
|
305
|
+
}
|
|
306
|
+
/** The exchange's client order id for one of this tool's order ids. A UUID is exactly the 128 bits it holds. */
|
|
307
|
+
function cloidOf(clientId) {
|
|
308
|
+
return `0x${clientId.replace(/-/g, "").padStart(32, "0").slice(0, 32).toLowerCase()}`;
|
|
309
|
+
}
|
|
310
|
+
async function readMandate(deps) {
|
|
311
|
+
const reply = await fundCall(deps, "GET", "/agent/mandate");
|
|
312
|
+
if (reply.status !== 200)
|
|
313
|
+
throw new Error(`the Rethinka Fund server answered HTTP ${reply.status}`);
|
|
314
|
+
const market = record(record(reply.body.markets).hyperliquid);
|
|
315
|
+
const instruments = record(reply.body.instruments);
|
|
316
|
+
return {
|
|
317
|
+
trading_paused: reply.body.trading_paused === true,
|
|
318
|
+
maxLeverage: typeof market.max_leverage === "number" ? market.max_leverage : null,
|
|
319
|
+
perpsAllowed: instruments.perps !== false,
|
|
320
|
+
shortSellingAllowed: instruments.short_selling !== false,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
async function currentLeverage(deps, settings, coin) {
|
|
324
|
+
const { data } = await info(deps, { type: "activeAssetData", user: settings.account, coin });
|
|
325
|
+
const value = record(record(data).leverage).value;
|
|
326
|
+
if (typeof value !== "number")
|
|
327
|
+
throw new Error("the exchange did not report the account's leverage for this coin");
|
|
328
|
+
return value;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Place one order under a recorded decision. Never throws: every outcome is a
|
|
332
|
+
* result the model can read, with the reason when nothing was placed.
|
|
333
|
+
*/
|
|
334
|
+
export async function placeHyperliquidOrder(input, deps) {
|
|
335
|
+
const configured = settingsOrReason(deps);
|
|
336
|
+
if ("reason" in configured)
|
|
337
|
+
return { ok: false, reason: configured.reason };
|
|
338
|
+
const { settings } = configured;
|
|
339
|
+
const trade = input.trade ?? 1;
|
|
340
|
+
const read = await readDecision(deps, input.decisionId, "hyperliquid", trade);
|
|
341
|
+
if ("reason" in read)
|
|
342
|
+
return { ok: false, reason: read.reason, ...read.extra };
|
|
343
|
+
const { permission } = read;
|
|
344
|
+
const { decision } = permission;
|
|
345
|
+
const isBuy = decision.action !== "sell";
|
|
346
|
+
const reduceOnly = decision.reduce_only === true;
|
|
347
|
+
const limit = Number(decision.limit_price);
|
|
348
|
+
if (!Number.isFinite(limit) || limit <= 0)
|
|
349
|
+
return { ok: false, reason: `Decision #${decision.id} has no limit price.` };
|
|
350
|
+
let asset;
|
|
351
|
+
try {
|
|
352
|
+
const resolved = await resolveAsset(deps, decision.symbol);
|
|
353
|
+
if ("reason" in resolved)
|
|
354
|
+
return { ok: false, reason: resolved.reason };
|
|
355
|
+
asset = resolved;
|
|
356
|
+
}
|
|
357
|
+
catch (err) {
|
|
358
|
+
return { ok: false, reason: `Hyperliquid's instrument list could not be read, and nothing was placed: ${errorText(err)}` };
|
|
359
|
+
}
|
|
360
|
+
if (reduceOnly && asset.kind === "spot")
|
|
361
|
+
return { ok: false, reason: `Decision #${decision.id} is reduce-only, but ${asset.coin} is a spot pair: spot has no positions to reduce. Record a plain sell decision instead.` };
|
|
362
|
+
const trigger = input.kind === "stop_loss" || input.kind === "take_profit";
|
|
363
|
+
if (trigger && !(input.triggerPrice !== undefined && input.triggerPrice > 0))
|
|
364
|
+
return { ok: false, reason: `A ${input.kind} order needs a trigger price.` };
|
|
365
|
+
if (!trigger && input.triggerPrice !== undefined)
|
|
366
|
+
return { ok: false, reason: `A ${input.kind} order takes no trigger price.` };
|
|
367
|
+
if (input.kind === "limit" && input.price === undefined)
|
|
368
|
+
return { ok: false, reason: "A limit order needs a price." };
|
|
369
|
+
if (input.price !== undefined && !(input.price > 0))
|
|
370
|
+
return { ok: false, reason: "The price must be positive." };
|
|
371
|
+
if (!(input.size > 0))
|
|
372
|
+
return { ok: false, reason: "The size must be a positive amount of the base asset." };
|
|
373
|
+
// Without a price of its own, an order may fill up to the decision's limit and no further.
|
|
374
|
+
const asked = input.price ?? limit;
|
|
375
|
+
if (isBuy ? asked > limit : asked < limit) {
|
|
376
|
+
return { ok: false, reason: `Price ${asked} is worse than the decision's limit of ${limit} for a ${decision.action}. Record a new decision if the plan changed.` };
|
|
377
|
+
}
|
|
378
|
+
const price = roundPrice(asked, asset, isBuy);
|
|
379
|
+
const size = roundSize(input.size, asset.szDecimals);
|
|
380
|
+
if (!(price > 0))
|
|
381
|
+
return { ok: false, reason: `Price ${asked} rounds to zero at ${asset.coin}'s price precision.` };
|
|
382
|
+
if (!(size > 0))
|
|
383
|
+
return { ok: false, reason: `Size ${input.size} is below ${asset.coin}'s smallest unit (${asset.szDecimals} decimal places).` };
|
|
384
|
+
const triggerPrice = trigger ? roundPrice(input.triggerPrice ?? 0, asset, isBuy) : null;
|
|
385
|
+
const notional = Number((price * size).toFixed(6));
|
|
386
|
+
if (!reduceOnly && notional < MIN_ORDER_USD)
|
|
387
|
+
return { ok: false, reason: `This order is $${notional}; Hyperliquid's minimum order value is $${MIN_ORDER_USD}.` };
|
|
388
|
+
if (notional > permission.remaining_usd + 1e-9) {
|
|
389
|
+
return { ok: false, reason: `This order is $${notional}, but only $${permission.remaining_usd} of decision #${decision.id}'s size is left.` };
|
|
390
|
+
}
|
|
391
|
+
// An order that can open or add to a perp position is held to the mandate.
|
|
392
|
+
if (asset.kind === "perp" && !reduceOnly) {
|
|
393
|
+
try {
|
|
394
|
+
const mandate = await readMandate(deps);
|
|
395
|
+
if (!mandate.perpsAllowed)
|
|
396
|
+
return { ok: false, reason: "The owner's mandate does not allow perps. Only reduce-only decisions can be traded on a perp." };
|
|
397
|
+
if (!isBuy && !mandate.shortSellingAllowed)
|
|
398
|
+
return { ok: false, reason: "The owner's mandate does not allow short selling. A sell on a perp must come from a reduce-only decision, which can only close a long." };
|
|
399
|
+
if (mandate.maxLeverage !== null) {
|
|
400
|
+
const leverage = await currentLeverage(deps, settings, asset.coin);
|
|
401
|
+
if (leverage > mandate.maxLeverage) {
|
|
402
|
+
return { ok: false, reason: `The account's leverage for ${asset.coin} is ${leverage}x, above the mandate's limit of ${mandate.maxLeverage}x for Hyperliquid. Lower it with rkf_hyperliquid_set_leverage first.`, leverage, max_leverage: mandate.maxLeverage };
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
catch (err) {
|
|
407
|
+
return { ok: false, reason: `The mandate's limits could not be checked, so nothing was placed: ${errorText(err)}` };
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
let wire;
|
|
411
|
+
try {
|
|
412
|
+
const type = trigger
|
|
413
|
+
? { trigger: { isMarket: input.triggerIsMarket !== false, triggerPx: floatToWire(triggerPrice ?? 0), tpsl: input.kind === "stop_loss" ? "sl" : "tp" } }
|
|
414
|
+
: { limit: { tif: input.kind === "market" ? "Ioc" : input.timeInForce ?? "Gtc" } };
|
|
415
|
+
wire = { a: asset.asset, b: isBuy, p: floatToWire(price), s: floatToWire(size), r: reduceOnly, t: type };
|
|
416
|
+
await signerFor(settings);
|
|
417
|
+
}
|
|
418
|
+
catch (err) {
|
|
419
|
+
return { ok: false, reason: `The order could not be built, and nothing was placed: ${errorText(err)}` };
|
|
420
|
+
}
|
|
421
|
+
const clientId = (deps.newId ?? randomUUID)();
|
|
422
|
+
const cloid = cloidOf(clientId);
|
|
423
|
+
if (!/^0x[0-9a-f]{32}$/.test(cloid))
|
|
424
|
+
return { ok: false, reason: "Could not make a client order id, and nothing was placed." };
|
|
425
|
+
const report = (status, detail, venueOrderId, fill) => reportOrder(deps, decision.id, {
|
|
426
|
+
client_id: clientId,
|
|
427
|
+
venue_order_id: venueOrderId,
|
|
428
|
+
side: isBuy ? "buy" : "sell",
|
|
429
|
+
price,
|
|
430
|
+
size,
|
|
431
|
+
notional_usd: notional,
|
|
432
|
+
...(fill ? { filled_size: fill.size, filled_notional_usd: fill.notional_usd } : {}),
|
|
433
|
+
status,
|
|
434
|
+
detail,
|
|
435
|
+
}, trade);
|
|
436
|
+
// Recorded before anything is sent: the server takes it only while an order
|
|
437
|
+
// may be placed and it fits, and an order lost mid-flight still counts.
|
|
438
|
+
const described = `${input.kind}${trigger ? ` trigger ${triggerPrice ?? ""}` : ""}${reduceOnly ? " reduce-only" : ""}`;
|
|
439
|
+
const preReport = await report("unknown", `submitting ${described}`, null);
|
|
440
|
+
if (preReport !== null)
|
|
441
|
+
return { ok: false, reason: `The Rethinka Fund server did not take this order (${preReport}), so it was not placed.` };
|
|
442
|
+
const expiresAfter = (deps.now ?? Date.now)() + ORDER_EXPIRY_MS;
|
|
443
|
+
// HIP-3 currently rejects orders carrying a client order id. Keep the local
|
|
444
|
+
// id for Fund reconciliation, but omit it from the signed wire on builder DEXs.
|
|
445
|
+
const action = { type: "order", orders: [{ ...wire, ...(asset.dex === "" ? { c: cloid } : {}) }], grouping: "na" };
|
|
446
|
+
const reply = await exchange(deps, settings, action, expiresAfter);
|
|
447
|
+
const outcome = (reply.answered ? readOrderReply(reply.body) : null)
|
|
448
|
+
?? (asset.dex === ""
|
|
449
|
+
? await settleLostOrder(deps, settings, cloid, expiresAfter, reply.answered ? "the exchange's answer was not understood" : reply.why)
|
|
450
|
+
: { status: "unknown", detail: reply.answered ? "the exchange's answer was not understood" : `${reply.why}; HIP-3 orders do not support client order ids, so check the numeric order id, open orders and fills before retrying`, orderId: null });
|
|
451
|
+
// A trigger order is acknowledged without its order id; the client order id finds it.
|
|
452
|
+
if (outcome.status === "submitted" && outcome.orderId === null) {
|
|
453
|
+
const found = await info(deps, { type: "orderStatus", user: settings.account, oid: cloid }).then((r) => readOrderStatus(r.data)).catch(() => null);
|
|
454
|
+
if (found && found !== "not_found" && found.orderId)
|
|
455
|
+
outcome.orderId = found.orderId;
|
|
456
|
+
}
|
|
457
|
+
const reportedFill = outcome.filled ? { size: Number(outcome.filled.size), notional_usd: Number(outcome.filled.size) * Number(outcome.filled.averagePrice) } : undefined;
|
|
458
|
+
const hasValidFill = reportedFill !== undefined && Number.isFinite(reportedFill.size) && reportedFill.size > 0 && Number.isFinite(reportedFill.notional_usd) && reportedFill.notional_usd > 0;
|
|
459
|
+
const reportStatus = hasValidFill
|
|
460
|
+
? reportedFill.size >= size - 1e-9 ? "filled" : "partially_filled"
|
|
461
|
+
: outcome.status;
|
|
462
|
+
const reportError = await report(reportStatus, `${described}: ${outcome.detail}`, outcome.orderId, hasValidFill ? reportedFill : undefined);
|
|
463
|
+
const common = { decision_id: decision.id, trade, coin: asset.coin, side: decision.action, reduce_only: reduceOnly, kind: input.kind, price, size, notional_usd: notional, client_order_id: cloid };
|
|
464
|
+
if (outcome.status === "rejected")
|
|
465
|
+
return { ok: false, reason: `Hyperliquid did not take the order, and nothing was placed: ${outcome.detail}`, ...common };
|
|
466
|
+
if (outcome.status === "unknown") {
|
|
467
|
+
return { ok: false, unknown: true, reason: `The order's fate is unknown: ${outcome.detail}. It may or may not be live. Check it with rkf_hyperliquid_order_status using client_order_id before doing anything else; do not simply retry.`, ...common };
|
|
468
|
+
}
|
|
469
|
+
return {
|
|
470
|
+
ok: true,
|
|
471
|
+
...common,
|
|
472
|
+
order_id: outcome.orderId,
|
|
473
|
+
venue_status: outcome.detail,
|
|
474
|
+
...(outcome.filled ? { filled_size: outcome.filled.size, average_price: outcome.filled.averagePrice } : {}),
|
|
475
|
+
...(price !== asked || size !== input.size ? { rounded: `price ${asked} -> ${price}, size ${input.size} -> ${size}, to the exchange's precision` } : {}),
|
|
476
|
+
note: "The order is placed. It can rest unfilled or fill only in part, and an immediate-or-cancel order can cancel without filling: read the fills and open orders before assuming a position. Later, bring this decision's record up to date with rkf_hyperliquid_refresh_orders, and when you are done with the decision, say so with rk_update_decision_outcome."
|
|
477
|
+
+ (reportError ? ` The result could not be written back to the Rethinka Fund server (${reportError}); tell the owner.` : ""),
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
export async function cancelHyperliquidOrder(input, deps) {
|
|
481
|
+
const configured = settingsOrReason(deps);
|
|
482
|
+
if ("reason" in configured)
|
|
483
|
+
return { ok: false, reason: configured.reason };
|
|
484
|
+
try {
|
|
485
|
+
const asset = await resolveAsset(deps, input.symbol);
|
|
486
|
+
if ("reason" in asset)
|
|
487
|
+
return { ok: false, reason: asset.reason };
|
|
488
|
+
const reply = await exchange(deps, configured.settings, { type: "cancel", cancels: [{ a: asset.asset, o: input.orderId }] }, null);
|
|
489
|
+
if (!reply.answered)
|
|
490
|
+
return { ok: false, reason: `The cancel got no answer (${reply.why}). The order may still be live; check open orders.` };
|
|
491
|
+
if (reply.body.status === "err")
|
|
492
|
+
return { ok: false, reason: `Hyperliquid refused the cancel: ${String(reply.body.response).replace(/\.$/, "")}. The order may still be live.` };
|
|
493
|
+
const first = list(record(record(reply.body.response).data).statuses)[0];
|
|
494
|
+
if (first === "success")
|
|
495
|
+
return { ok: true, cancelled: input.orderId, coin: asset.coin };
|
|
496
|
+
return { ok: false, reason: `The order was not cancelled: ${typeof record(first).error === "string" ? String(record(first).error) : JSON.stringify(first ?? null)}` };
|
|
497
|
+
}
|
|
498
|
+
catch (err) {
|
|
499
|
+
return { ok: false, reason: `The cancel did not go through: ${errorText(err)}. The order may still be live.` };
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
export async function listHyperliquidOpenOrders(deps) {
|
|
503
|
+
const configured = settingsOrReason(deps);
|
|
504
|
+
if ("reason" in configured)
|
|
505
|
+
return { ok: false, reason: configured.reason };
|
|
506
|
+
try {
|
|
507
|
+
// The default DEX also contains spot orders. HIP-3 DEXs need one query each.
|
|
508
|
+
// Older/private API deployments may not expose perpDexs, so retain the default query in that case.
|
|
509
|
+
const dexes = await loadPerpDexList(deps).catch(() => [{ name: "", index: 0 }]);
|
|
510
|
+
const orders = (await Promise.all(dexes.map(async ({ name }) => {
|
|
511
|
+
const request = { type: "frontendOpenOrders", user: configured.settings.account };
|
|
512
|
+
if (name)
|
|
513
|
+
request.dex = name;
|
|
514
|
+
const { data } = await info(deps, request);
|
|
515
|
+
return list(data).map((order) => name ? { ...record(order), dex: name } : order);
|
|
516
|
+
}))).flat();
|
|
517
|
+
return { ok: true, account: configured.settings.account, orders };
|
|
518
|
+
}
|
|
519
|
+
catch (err) {
|
|
520
|
+
return { ok: false, reason: `Open orders could not be read: ${errorText(err)}` };
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
/** Look one order up by the exchange's order id or by the client order id a placement returned. */
|
|
524
|
+
export async function getHyperliquidOrderStatus(input, deps) {
|
|
525
|
+
const configured = settingsOrReason(deps);
|
|
526
|
+
if ("reason" in configured)
|
|
527
|
+
return { ok: false, reason: configured.reason };
|
|
528
|
+
const oid = /^0x[0-9a-fA-F]{32}$/.test(input.order) ? input.order.toLowerCase() : /^\d{1,18}$/.test(input.order) ? Number(input.order) : null;
|
|
529
|
+
if (oid === null)
|
|
530
|
+
return { ok: false, reason: "Give the exchange's numeric order id, or the client_order_id (0x and 32 hex digits) a placement returned." };
|
|
531
|
+
try {
|
|
532
|
+
const { data } = await info(deps, { type: "orderStatus", user: configured.settings.account, oid });
|
|
533
|
+
if (record(data).status === "unknownOid")
|
|
534
|
+
return { ok: true, found: false, note: "The exchange has no record of this order. If it was submitted more than a minute ago, it was not placed." };
|
|
535
|
+
return { ok: true, found: true, order: record(data).order };
|
|
536
|
+
}
|
|
537
|
+
catch (err) {
|
|
538
|
+
return { ok: false, reason: `The order's status could not be read: ${errorText(err)}` };
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
/** Where an order stands, from the state `orderStatus` gives it. Null when the state says nothing usable. */
|
|
542
|
+
export function readOrderProgress(data) {
|
|
543
|
+
const body = record(data);
|
|
544
|
+
if (body.status === "unknownOid")
|
|
545
|
+
return "not_found";
|
|
546
|
+
if (body.status !== "order")
|
|
547
|
+
return null;
|
|
548
|
+
const wrapper = record(body.order);
|
|
549
|
+
const venueState = typeof wrapper.status === "string" ? wrapper.status : "";
|
|
550
|
+
if (!venueState)
|
|
551
|
+
return null;
|
|
552
|
+
const inner = record(wrapper.order);
|
|
553
|
+
const number = (value) => {
|
|
554
|
+
const n = typeof value === "string" || typeof value === "number" ? Number(value) : Number.NaN;
|
|
555
|
+
return Number.isFinite(n) && n >= 0 ? n : null;
|
|
556
|
+
};
|
|
557
|
+
// "canceled", "marginCanceled", "siblingFilledCanceled" and the rest of that family all ended without (further) fills.
|
|
558
|
+
const state = venueState === "filled" ? "filled" : /rejected$/i.test(venueState) ? "rejected" : /cancel/i.test(venueState) || /expired$/i.test(venueState) ? "cancelled" : "open";
|
|
559
|
+
return { state, venueState, orderId: typeof inner.oid === "number" ? String(inner.oid) : null, originalSize: number(inner.origSz), remainingSize: number(inner.sz) };
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Bring the orders under one decision up to date with the exchange: what each
|
|
563
|
+
* has filled and whether it is still live. The fills themselves give the
|
|
564
|
+
* amounts where the exchange still lists them; an order's own record gives
|
|
565
|
+
* the size otherwise, valued at the order's limit price.
|
|
566
|
+
*/
|
|
567
|
+
export async function refreshHyperliquidOrders(input, deps) {
|
|
568
|
+
const configured = settingsOrReason(deps);
|
|
569
|
+
if ("reason" in configured)
|
|
570
|
+
return { ok: false, reason: configured.reason };
|
|
571
|
+
const { settings } = configured;
|
|
572
|
+
let fills = null;
|
|
573
|
+
const recentFills = () => fills ??= info(deps, { type: "userFills", user: settings.account }).then((r) => list(r.data).map(record)).catch(() => []);
|
|
574
|
+
return await refreshDecisionOrders(deps, input.decisionId, "hyperliquid", Date.now, async (order) => {
|
|
575
|
+
const oid = order.venue_order_id !== null && /^\d{1,18}$/.test(order.venue_order_id) ? Number(order.venue_order_id) : cloidOf(order.client_id);
|
|
576
|
+
const reply = await info(deps, { type: "orderStatus", user: settings.account, oid });
|
|
577
|
+
const progress = readOrderProgress(reply.data);
|
|
578
|
+
if (progress === null)
|
|
579
|
+
return { skipped: "the exchange's answer about it was not understood" };
|
|
580
|
+
if (progress === "not_found") {
|
|
581
|
+
// An order the exchange once gave an id to was placed. If the exchange does not know it now, something
|
|
582
|
+
// else is wrong (a different account in the settings file, say), and nothing is concluded from that.
|
|
583
|
+
if (order.venue_order_id !== null)
|
|
584
|
+
return { skipped: `the exchange has no record of order ${order.venue_order_id} for this account; check the account in the settings file and tell the owner` };
|
|
585
|
+
// An order that never got an id carries an expiry. Well past it, by the exchange's own clock, it was never placed.
|
|
586
|
+
const reported = Date.parse(order.reported_at ?? "");
|
|
587
|
+
if (reply.serverTime !== null && Number.isFinite(reported) && reply.serverTime > reported + ORDER_EXPIRY_MS + 60_000) {
|
|
588
|
+
return { status: "rejected", filled_size: 0, filled_notional_usd: 0, detail: "not placed: the exchange has no record of it and its expiry has passed" };
|
|
589
|
+
}
|
|
590
|
+
return { skipped: "the exchange has no record of it yet; ask again in a minute" };
|
|
591
|
+
}
|
|
592
|
+
const numericId = progress.orderId !== null ? Number(progress.orderId) : typeof oid === "number" ? oid : null;
|
|
593
|
+
let fillSize = 0;
|
|
594
|
+
let fillNotional = 0;
|
|
595
|
+
if (numericId !== null) {
|
|
596
|
+
for (const fill of await recentFills()) {
|
|
597
|
+
if (fill.oid !== numericId)
|
|
598
|
+
continue;
|
|
599
|
+
const size = Number(fill.sz);
|
|
600
|
+
const price = Number(fill.px);
|
|
601
|
+
if (!(size > 0) || !(price > 0))
|
|
602
|
+
continue;
|
|
603
|
+
fillSize += size;
|
|
604
|
+
fillNotional += size * price;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
// Rejected means it never rested and never filled; were a fill listed all the same, the fill is believed.
|
|
608
|
+
if (progress.state === "rejected" && fillSize === 0)
|
|
609
|
+
return { status: "rejected", filled_size: 0, filled_notional_usd: 0, detail: progress.venueState, venue_order_id: progress.orderId };
|
|
610
|
+
const byRecord = progress.state === "filled"
|
|
611
|
+
? progress.originalSize ?? order.size
|
|
612
|
+
: progress.originalSize !== null && progress.remainingSize !== null ? Math.max(0, progress.originalSize - progress.remainingSize) : 0;
|
|
613
|
+
const filledSize = Number(Math.max(fillSize, byRecord).toFixed(8));
|
|
614
|
+
// Whatever the listed fills do not cover is valued at the order's own price.
|
|
615
|
+
const filledNotional = fillNotional + Math.max(0, filledSize - fillSize) * order.price;
|
|
616
|
+
const status = progress.state === "open" ? (filledSize > 0 ? "partially_filled" : "submitted") : progress.state === "rejected" ? "cancelled" : progress.state;
|
|
617
|
+
return { status, filled_size: filledSize, filled_notional_usd: filledNotional, detail: `${progress.venueState}${filledSize > 0 ? `, filled ${filledSize}` : ""}`, venue_order_id: progress.orderId };
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Set the account's leverage for one perp, within the mandate's cap. Raising
|
|
622
|
+
* leverage is a risk decision the owner bounded in the mandate; without a cap
|
|
623
|
+
* there, the tool does not guess one.
|
|
624
|
+
*/
|
|
625
|
+
export async function setHyperliquidLeverage(input, deps) {
|
|
626
|
+
const configured = settingsOrReason(deps);
|
|
627
|
+
if ("reason" in configured)
|
|
628
|
+
return { ok: false, reason: configured.reason };
|
|
629
|
+
if (!Number.isInteger(input.leverage) || input.leverage < 1)
|
|
630
|
+
return { ok: false, reason: "Leverage is a whole number, 1 or more." };
|
|
631
|
+
try {
|
|
632
|
+
const asset = await resolveAsset(deps, input.symbol);
|
|
633
|
+
if ("reason" in asset)
|
|
634
|
+
return { ok: false, reason: asset.reason };
|
|
635
|
+
if (asset.kind !== "perp")
|
|
636
|
+
return { ok: false, reason: `${asset.coin} is a spot pair; leverage applies to perps.` };
|
|
637
|
+
let mandate;
|
|
638
|
+
try {
|
|
639
|
+
mandate = await readMandate(deps);
|
|
640
|
+
}
|
|
641
|
+
catch (err) {
|
|
642
|
+
return { ok: false, reason: `The mandate could not be read, so leverage was not changed: ${errorText(err)}` };
|
|
643
|
+
}
|
|
644
|
+
if (mandate.trading_paused)
|
|
645
|
+
return { ok: false, reason: "The owner has paused all trading in the console. Leverage was not changed." };
|
|
646
|
+
if (mandate.maxLeverage === null)
|
|
647
|
+
return { ok: false, reason: "The owner has not set a leverage limit for Hyperliquid in the mandate. Ask the owner to set one; leverage was not changed." };
|
|
648
|
+
if (input.leverage > mandate.maxLeverage)
|
|
649
|
+
return { ok: false, reason: `${input.leverage}x is above the mandate's limit of ${mandate.maxLeverage}x for Hyperliquid. Leverage was not changed.` };
|
|
650
|
+
if (asset.onlyIsolated && input.cross)
|
|
651
|
+
return { ok: false, reason: `${asset.coin} only supports isolated margin on Hyperliquid. Set cross to false.` };
|
|
652
|
+
if (asset.maxLeverage !== null && input.leverage > asset.maxLeverage)
|
|
653
|
+
return { ok: false, reason: `Hyperliquid allows at most ${asset.maxLeverage}x on ${asset.coin}.` };
|
|
654
|
+
const reply = await exchange(deps, configured.settings, { type: "updateLeverage", asset: asset.asset, isCross: input.cross, leverage: input.leverage }, null);
|
|
655
|
+
if (!reply.answered)
|
|
656
|
+
return { ok: false, reason: `The change got no answer (${reply.why}). Read the current leverage before relying on it.` };
|
|
657
|
+
if (reply.body.status !== "ok")
|
|
658
|
+
return { ok: false, reason: `Hyperliquid refused the change: ${String(reply.body.response)}` };
|
|
659
|
+
return { ok: true, coin: asset.coin, leverage: input.leverage, margin: input.cross ? "cross" : "isolated", max_leverage: mandate.maxLeverage };
|
|
660
|
+
}
|
|
661
|
+
catch (err) {
|
|
662
|
+
return { ok: false, reason: `Leverage was not changed: ${errorText(err)}` };
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
/** Tests only: forget the instrument list, signers and nonces. */
|
|
666
|
+
export function resetHyperliquidForTest() {
|
|
667
|
+
universe = null;
|
|
668
|
+
builderUniverse = null;
|
|
669
|
+
perpDexList = null;
|
|
670
|
+
signers.clear();
|
|
671
|
+
lastNonce.clear();
|
|
672
|
+
}
|
|
673
|
+
//# sourceMappingURL=hyperliquid-trading.js.map
|