@reefclaw/openclaw-plugin 0.1.5 → 0.1.6

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.
Files changed (122) hide show
  1. package/ccxt/binance-private.d.ts +21 -0
  2. package/ccxt/binance-private.js +132 -22
  3. package/config/plugin-config-io.d.ts +6 -0
  4. package/config/tool-gate.js +3 -0
  5. package/exchange-adapter.d.ts +16 -0
  6. package/index.js +551 -54
  7. package/lifecycle/trading-operation-lock.d.ts +17 -0
  8. package/lifecycle/trading-operation-lock.js +14 -0
  9. package/live/bracket-id.d.ts +2 -3
  10. package/live/bracket-id.js +22 -9
  11. package/live/live-adapter.d.ts +24 -1
  12. package/live/live-adapter.js +114 -2
  13. package/live/local-signal-service.js +11 -6
  14. package/live/local-strategy-evaluator.js +4 -0
  15. package/live/proposal-decision-listener.d.ts +6 -0
  16. package/live/proposal-decision-listener.js +4 -0
  17. package/live/stop-watcher.d.ts +27 -1
  18. package/live/stop-watcher.js +59 -2
  19. package/onboarding/runtime.d.ts +13 -0
  20. package/onboarding/runtime.js +22 -2
  21. package/openclaw.plugin.json +1 -0
  22. package/package.json +1 -1
  23. package/portfolio/wave9-admission.d.ts +67 -0
  24. package/portfolio/wave9-admission.js +262 -0
  25. package/portfolio/wave9-policy.d.ts +36 -0
  26. package/portfolio/wave9-policy.js +183 -0
  27. package/signals/conditions/registry.js +50 -0
  28. package/simulator/exchange-simulator.js +5 -0
  29. package/simulator/fill-engine.js +5 -1
  30. package/simulator/types.d.ts +6 -1
  31. package/strategy/evaluator.d.ts +3 -0
  32. package/strategy/evaluator.js +5 -0
  33. package/tools/assessment-validation.d.ts +2 -0
  34. package/tools/attach-brackets.d.ts +7 -2
  35. package/tools/attach-brackets.js +36 -0
  36. package/tools/cancel-all-orders.d.ts +2 -0
  37. package/tools/cancel-all-orders.js +4 -1
  38. package/tools/cancel-order.d.ts +4 -0
  39. package/tools/cancel-order.js +49 -3
  40. package/tools/close-position.d.ts +23 -0
  41. package/tools/close-position.js +286 -13
  42. package/tools/create-order.d.ts +28 -0
  43. package/tools/create-order.js +1364 -192
  44. package/tools/get-analytics.js +2 -2
  45. package/tools/get-basis.js +2 -2
  46. package/tools/get-cascade-risk.js +2 -2
  47. package/tools/get-crypto-metrics.js +14 -4
  48. package/tools/get-cvd.js +2 -2
  49. package/tools/get-divergences.js +2 -2
  50. package/tools/get-funding-context.js +2 -2
  51. package/tools/get-liquidation-levels.js +2 -2
  52. package/tools/get-liquidation-pulse.js +2 -2
  53. package/tools/get-pattern-scan.js +2 -2
  54. package/tools/get-regime.js +2 -2
  55. package/tools/get-resting-liquidity.js +2 -2
  56. package/tools/get-risk-scenario.js +2 -2
  57. package/tools/get-session-review.js +2 -2
  58. package/tools/get-setup-detail.js +9 -1
  59. package/tools/get-signals.js +2 -2
  60. package/tools/get-sizing.js +2 -2
  61. package/tools/get-trade-feedback.js +2 -2
  62. package/tools/get-trade-flow.js +2 -2
  63. package/tools/get-volume-profile.js +2 -2
  64. package/tools/get-wave9-status.d.ts +127 -0
  65. package/tools/get-wave9-status.js +796 -0
  66. package/tools/intel-api.d.ts +20 -0
  67. package/tools/intel-api.js +67 -0
  68. package/tools/intel-cache.d.ts +1 -1
  69. package/tools/intel-cache.js +20 -5
  70. package/tools/list-strategies.d.ts +11 -1
  71. package/tools/list-strategies.js +17 -0
  72. package/tools/modify-stop.d.ts +4 -0
  73. package/tools/modify-stop.js +63 -24
  74. package/tools/modify-target.d.ts +4 -0
  75. package/tools/modify-target.js +62 -23
  76. package/tools/scan-pairs.js +19 -8
  77. package/tools/toggle-strategy.js +7 -0
  78. package/types.d.ts +5 -0
  79. package/venues/hyperliquid/hl-balance.d.ts +116 -0
  80. package/venues/hyperliquid/hl-balance.js +145 -0
  81. package/venues/hyperliquid/hl-brackets.d.ts +102 -0
  82. package/venues/hyperliquid/hl-brackets.js +172 -0
  83. package/venues/hyperliquid/hl-cloid.d.ts +22 -0
  84. package/venues/hyperliquid/hl-cloid.js +82 -0
  85. package/venues/hyperliquid/hl-info-cache.d.ts +46 -0
  86. package/venues/hyperliquid/hl-info-cache.js +125 -0
  87. package/venues/hyperliquid/hl-live-adapter.d.ts +88 -0
  88. package/venues/hyperliquid/hl-live-adapter.js +353 -0
  89. package/venues/hyperliquid/hl-precision.d.ts +61 -0
  90. package/venues/hyperliquid/hl-precision.js +176 -0
  91. package/venues/hyperliquid/hl-private.d.ts +88 -0
  92. package/venues/hyperliquid/hl-private.js +357 -0
  93. package/venues/hyperliquid/hl-public.d.ts +31 -4
  94. package/venues/hyperliquid/hl-public.js +155 -11
  95. package/venues/hyperliquid/hl-rate-gate.d.ts +57 -0
  96. package/venues/hyperliquid/hl-rate-gate.js +220 -0
  97. package/venues/hyperliquid/hl-user-stream.d.ts +90 -0
  98. package/venues/hyperliquid/hl-user-stream.js +220 -0
  99. package/venues/registry.d.ts +23 -9
  100. package/venues/registry.js +12 -13
  101. package/venues/symbols.d.ts +43 -0
  102. package/venues/symbols.js +107 -0
  103. package/wave9/live-account-capture.d.ts +67 -0
  104. package/wave9/live-account-capture.js +435 -0
  105. package/wave9/live-autonomous-protection.d.ts +39 -0
  106. package/wave9/live-autonomous-protection.js +112 -0
  107. package/wave9/live-durable-reconciliation-scheduler.d.ts +33 -0
  108. package/wave9/live-durable-reconciliation-scheduler.js +115 -0
  109. package/wave9/live-execution-ledger.d.ts +107 -0
  110. package/wave9/live-execution-ledger.js +498 -0
  111. package/wave9/live-position-confirmation.d.ts +18 -0
  112. package/wave9/live-position-confirmation.js +111 -0
  113. package/wave9/live-residual-protection.d.ts +18 -0
  114. package/wave9/live-residual-protection.js +250 -0
  115. package/wave9/live-startup-reconciliation.d.ts +38 -0
  116. package/wave9/live-startup-reconciliation.js +454 -0
  117. package/wave9/live-symbol-ownership.d.ts +20 -0
  118. package/wave9/live-symbol-ownership.js +132 -0
  119. package/wave9/paper-admission-guard.d.ts +199 -0
  120. package/wave9/paper-admission-guard.js +650 -0
  121. package/wave9/usdm-evidence-provider.d.ts +42 -0
  122. package/wave9/usdm-evidence-provider.js +133 -0
@@ -0,0 +1,176 @@
1
+ // Hyperliquid price/size precision — the rule, implemented HERE, on strings.
2
+ //
3
+ // ★ WHY NOT CCXT: `priceToPrecision` has a known rounding bug in the [1,10)
4
+ // range (ccxt#26132) and the whole point of a safety floor is that the stop
5
+ // price we compute is the stop price the exchange gets. Plan §5.5: own the math.
6
+ //
7
+ // ★ WHY NOT decimal.js: it would become a runtime dependency of the PUBLISHED
8
+ // plugin package. The rule below only needs exact DECIMAL-STRING manipulation
9
+ // (truncate / count significant figures) — no arithmetic on values — so strings
10
+ // are both exact and dependency-free. Every function takes and returns numbers at
11
+ // the boundary but never rounds through binary floating point.
12
+ //
13
+ // THE RULE (docs, verified 2026-07-11; re-verified live 2026-07-12):
14
+ // PRICE is valid iff
15
+ // - it is an INTEGER (always allowed, regardless of sig figs), OR
16
+ // - it has ≤ 5 significant figures AND ≤ (MAX_DECIMALS − szDecimals) decimals
17
+ // where MAX_DECIMALS = 6 for perps.
18
+ // SIZE is rounded DOWN to szDecimals (from `meta.universe`).
19
+ // MIN NOTIONAL is $10 (observed live: "Order must have minimum value of $10").
20
+ //
21
+ // Rounding direction is explicit at every call site — never "nearest" by default
22
+ // on a protective leg. `passive` semantics: a BUY rounds DOWN, a SELL rounds UP,
23
+ // so a rounded limit never crosses further into the book than intended.
24
+ const MAX_DECIMALS_PERP = 6;
25
+ /** HL minimum order value in USDC. Observed live 2026-07-12 (a $6 order was
26
+ * rejected: "Order must have minimum value of $10"). */
27
+ export const HL_MIN_NOTIONAL_USD = 10;
28
+ /** Split a finite number into its exact decimal string parts, expanding any
29
+ * exponent form ("1e-7") that JS produces for small/large magnitudes — the
30
+ * string rule below must never see an "e". */
31
+ function toPlainDecimalString(value) {
32
+ if (!Number.isFinite(value))
33
+ throw new Error(`not finite: ${value}`);
34
+ // toPrecision(17) is lossless for a double, and never yields exponent form for
35
+ // the magnitudes we trade; Number() re-parses to drop trailing zeros.
36
+ const s = String(value);
37
+ if (!s.includes('e') && !s.includes('E'))
38
+ return s;
39
+ // Exponent form → expand via toFixed with enough decimals (bounded: HL prices
40
+ // never need more than 20 decimals, and sizes are capped by szDecimals).
41
+ return value.toFixed(20).replace(/0+$/, '').replace(/\.$/, '');
42
+ }
43
+ /** Count significant figures of a decimal string (leading zeros are not
44
+ * significant; trailing zeros AFTER a decimal point are, but we always emit
45
+ * trimmed strings so they never appear). */
46
+ export function countSignificantFigures(value) {
47
+ const s = toPlainDecimalString(Math.abs(value));
48
+ const digits = s.replace('.', '').replace(/^0+/, '').replace(/0+$/, '');
49
+ // An integer like 1200 has 2 sig figs by this measure — which is the
50
+ // conservative reading, and integers are unconditionally allowed anyway.
51
+ return digits.length === 0 ? 1 : digits.length;
52
+ }
53
+ /** Decimal places of a value (0 for integers). */
54
+ export function decimalPlaces(value) {
55
+ const s = toPlainDecimalString(Math.abs(value));
56
+ const dot = s.indexOf('.');
57
+ return dot === -1 ? 0 : s.length - dot - 1;
58
+ }
59
+ /** Truncate a decimal string to N decimals, rounding in the requested direction.
60
+ * Exact — no binary float rounding anywhere. */
61
+ function roundDecimals(value, decimals, dir) {
62
+ if (decimals < 0)
63
+ decimals = 0;
64
+ const factor = 10 ** decimals;
65
+ // Work in an integer domain scaled by `factor`; the +/- 1e-9 nudge absorbs the
66
+ // classic 0.1*3 = 0.30000000000000004 representation error WITHOUT changing a
67
+ // value that is genuinely on the boundary.
68
+ const scaled = value * factor;
69
+ const eps = 1e-9;
70
+ const out = dir === 'down' ? Math.floor(scaled + eps) : Math.ceil(scaled - eps);
71
+ return out / factor;
72
+ }
73
+ /** Round a value to at most `sig` significant figures, in the given direction. */
74
+ function roundToSignificantFigures(value, sig, dir) {
75
+ if (value === 0)
76
+ return 0;
77
+ const magnitude = Math.floor(Math.log10(Math.abs(value)));
78
+ // decimals needed so that the value carries exactly `sig` significant figures
79
+ const decimals = sig - 1 - magnitude;
80
+ return roundDecimals(value, Math.max(decimals, 0), dir);
81
+ }
82
+ /** Is this price acceptable to Hyperliquid as-is? (The exact documented rule —
83
+ * used by tests and as a post-round assertion, never as a substitute for
84
+ * rounding.) */
85
+ export function isValidHlPrice(price, szDecimals) {
86
+ if (!Number.isFinite(price) || price <= 0)
87
+ return false;
88
+ if (Number.isInteger(price))
89
+ return true; // integers always allowed
90
+ const maxDecimals = MAX_DECIMALS_PERP - szDecimals;
91
+ return countSignificantFigures(price) <= 5 && decimalPlaces(price) <= maxDecimals;
92
+ }
93
+ /** Round a price to the nearest HL-legal value in the requested direction.
94
+ *
95
+ * Applies BOTH constraints (≤5 sig figs AND ≤ MAX_DECIMALS−szDecimals decimals),
96
+ * tightest-wins. An integer result is always legal, so the decimal cap can never
97
+ * push a price to an illegal value. */
98
+ export function roundHlPrice(price, szDecimals, dir) {
99
+ if (!Number.isFinite(price) || price <= 0) {
100
+ throw new Error(`Invalid HL price: ${price}`);
101
+ }
102
+ const maxDecimals = Math.max(MAX_DECIMALS_PERP - szDecimals, 0);
103
+ // 1) cap significant figures
104
+ let out = roundToSignificantFigures(price, 5, dir);
105
+ // 2) cap decimals (may reduce sig figs further — that stays legal)
106
+ if (decimalPlaces(out) > maxDecimals) {
107
+ out = roundDecimals(out, maxDecimals, dir);
108
+ }
109
+ // A rounded-to-zero price is never legal — fall back to the smallest legal tick.
110
+ if (out <= 0)
111
+ out = 1 / 10 ** maxDecimals;
112
+ return out;
113
+ }
114
+ /** Round an order size DOWN to szDecimals. Always DOWN: rounding a size up can
115
+ * overshoot the position (a reduce-only leg sized above the position is rejected)
116
+ * or exceed the intended risk. */
117
+ export function roundHlSize(size, szDecimals) {
118
+ if (!Number.isFinite(size) || size < 0) {
119
+ throw new Error(`Invalid HL size: ${size}`);
120
+ }
121
+ return roundDecimals(size, szDecimals, 'down');
122
+ }
123
+ /** Pre-flight validation mirroring `ExchangeInfoCache.validate`'s contract
124
+ * (same shape, same "round then check" order, same dollar-hint error copy) so
125
+ * the adapter's call sites are venue-symmetric.
126
+ *
127
+ * @param side drives passive rounding of a limit price (buy → down, sell → up).
128
+ * @param referencePrice mark/mid — used for the notional check when no limit
129
+ * price is given (market orders). */
130
+ export function validateHlOrder(args) {
131
+ const { amount, price, referencePrice, rules, side } = args;
132
+ const { szDecimals } = rules;
133
+ const roundedAmount = roundHlSize(amount, szDecimals);
134
+ if (roundedAmount <= 0) {
135
+ return {
136
+ valid: false,
137
+ error: `Amount ${amount} rounds to zero at ${szDecimals} decimals — increase the size`,
138
+ roundedAmount: 0,
139
+ };
140
+ }
141
+ let roundedPrice;
142
+ if (price !== undefined) {
143
+ roundedPrice = roundHlPrice(price, szDecimals, side === 'buy' ? 'down' : 'up');
144
+ }
145
+ const notionalPrice = roundedPrice ?? referencePrice;
146
+ if (notionalPrice !== undefined && notionalPrice > 0) {
147
+ const notional = roundedAmount * notionalPrice;
148
+ if (notional < HL_MIN_NOTIONAL_USD) {
149
+ const minAmount = HL_MIN_NOTIONAL_USD / notionalPrice;
150
+ return {
151
+ valid: false,
152
+ // Same dollar-hint shape the Binance path uses — the agent gets an
153
+ // actionable number, not a rule citation.
154
+ error: `Order value $${notional.toFixed(2)} is below Hyperliquid's $${HL_MIN_NOTIONAL_USD} minimum. ` +
155
+ `Increase size to at least ${minAmount.toFixed(szDecimals + 1)} (≈$${HL_MIN_NOTIONAL_USD}).`,
156
+ roundedAmount,
157
+ roundedPrice,
158
+ };
159
+ }
160
+ }
161
+ return { valid: true, roundedAmount, roundedPrice };
162
+ }
163
+ /** The IOC price bound that emulates a market order (HL has no native market
164
+ * order — plan §3.4). Explicit slippage ALWAYS — ccxt's `defaultSlippage: 0.05`
165
+ * (5%!) is never relied upon. */
166
+ export function marketIocPrice(args) {
167
+ const { referencePrice, side, slippagePct, szDecimals } = args;
168
+ if (!Number.isFinite(referencePrice) || referencePrice <= 0) {
169
+ throw new Error(`marketIocPrice needs a positive reference price, got ${referencePrice}`);
170
+ }
171
+ const slip = Math.min(Math.max(slippagePct, 0), 0.02); // hard clamp ≤2%
172
+ const raw = side === 'buy' ? referencePrice * (1 + slip) : referencePrice * (1 - slip);
173
+ // Round the bound OUTWARD (buy up / sell down) so rounding never makes the
174
+ // order less marketable than intended.
175
+ return roundHlPrice(raw, szDecimals, side === 'buy' ? 'up' : 'down');
176
+ }
@@ -0,0 +1,88 @@
1
+ import type { CcxtOrder, CcxtPosition, CcxtBalance } from '../../types.js';
2
+ export interface HlCredentials {
3
+ /** MASTER account address (0x…). Queries always use this — an agent wallet
4
+ * holds no balance and no positions (learned the hard way 2026-07-12). */
5
+ walletAddress: string;
6
+ /** AGENT (API) wallet private key — signs, never holds funds. */
7
+ agentPrivateKey: string;
8
+ testnet?: boolean;
9
+ }
10
+ /** The CCXT options that MUST be present on every authed HL client. Exported so
11
+ * `hl-private.test.ts` can assert them — if a future ccxt bump changes the
12
+ * option names, the test fails rather than the users paying a silent 1bp. */
13
+ export declare const HL_REQUIRED_OPTIONS: {
14
+ readonly builderFee: false;
15
+ readonly refSet: true;
16
+ };
17
+ export interface HlTriggerParams {
18
+ /** Trigger price (fires on MARK — HL has no workingType choice). */
19
+ triggerPrice: number;
20
+ /** 'sl' | 'tp' — HL's own naming. */
21
+ tpsl: 'sl' | 'tp';
22
+ reduceOnly: true;
23
+ cloid?: string;
24
+ }
25
+ export interface HlOrderRequest {
26
+ symbol: string;
27
+ side: 'buy' | 'sell';
28
+ /** 'market' is emulated: an IOC limit at `price` (the caller must have applied
29
+ * the slippage bound via hl-precision.marketIocPrice). */
30
+ type: 'market' | 'limit';
31
+ amount: number;
32
+ price: number;
33
+ reduceOnly?: boolean;
34
+ postOnly?: boolean;
35
+ cloid?: string;
36
+ trigger?: {
37
+ triggerPrice: number;
38
+ tpsl: 'sl' | 'tp';
39
+ };
40
+ }
41
+ export declare class HyperliquidPrivateApi {
42
+ private readonly creds;
43
+ private readonly exchange;
44
+ private readonly mutex;
45
+ private marketsLoaded;
46
+ constructor(creds: HlCredentials);
47
+ /** Exposed for the options-pin test + diagnostics. */
48
+ getExchange(): any;
49
+ loadMarkets(): Promise<boolean>;
50
+ /** Positions for the MASTER account. `null` = fetch failed (state unknown);
51
+ * `[]` = the exchange confirmed flat. */
52
+ fetchPositions(symbol?: string): Promise<CcxtPosition[] | null>;
53
+ /** Open orders INCLUDING trigger/TPSL legs. CCXT's HL `fetchOpenOrders`
54
+ * defaults to `frontendOpenOrders`, which is the only endpoint that returns
55
+ * trigger orders (plan §3.6) — the analog of Binance's merged algo endpoints. */
56
+ fetchOpenOrders(symbol?: string): Promise<CcxtOrder[] | null>;
57
+ fetchBalance(): Promise<CcxtBalance | null>;
58
+ /** Per-order status — the liveness resolver's REST tier (Tier 2 of the
59
+ * 3-tier rule). Weight 2. `null` = lookup FAILED (unknown), which callers
60
+ * must treat as "do not act", NOT as "gone". */
61
+ fetchOrder(orderId: string, symbol?: string): Promise<CcxtOrder | null>;
62
+ /** Own fills. WS is the authoritative ingress (plan + the audit-trail rule);
63
+ * this is the gap-fill/truth-check path. NOTE: only the 10,000 most recent
64
+ * fills exist server-side — deep history is NOT queryable on HL, which is why
65
+ * the `trades` table must be WS-first. */
66
+ fetchMyTrades(symbol?: string, since?: number, limit?: number): Promise<unknown[] | null>;
67
+ /** Refresh the ADDRESS action budget (the starvation guard). Weight 20 — call
68
+ * every ~5 min, never per-heartbeat. */
69
+ refreshAddressBudget(): Promise<void>;
70
+ /** Raw `POST /info` — for the handful of reads CCXT doesn't expose
71
+ * (userRateLimit, userNonFundingLedgerUpdates, portfolio). Never used for
72
+ * signed actions. */
73
+ rawInfo(body: Record<string, unknown>): Promise<any>;
74
+ /** Submit one order. Market orders are IOC-limit emulated — `price` is
75
+ * MANDATORY (ccxt throws without it) and the caller must already have applied
76
+ * the slippage bound + HL rounding (hl-precision). */
77
+ submitOrder(req: HlOrderRequest): Promise<CcxtOrder | null>;
78
+ /** Submit N orders as ONE signed action (one nonce, one `/exchange` call).
79
+ * This is how a bracket pair (SL+TP) is placed: atomic-ish, and it costs 1 IP
80
+ * weight unit but N address actions. */
81
+ submitOrders(reqs: HlOrderRequest[]): Promise<CcxtOrder[] | null>;
82
+ cancelOrder(orderId: string, symbol: string): Promise<CcxtOrder | null>;
83
+ /** Cancel by cloid — the bracket path's cancel (we always know our own cloid,
84
+ * and it survives a restart because it is derived, not stored). */
85
+ cancelOrderByCloid(cloid: string, symbol: string): Promise<CcxtOrder | null>;
86
+ private buildParams;
87
+ get isMarketsLoaded(): boolean;
88
+ }
@@ -0,0 +1,357 @@
1
+ // Hyperliquid signed-action client — the HL mirror of `ccxt/binance-private.ts`.
2
+ //
3
+ // CONTRACTS THIS FILE INHERITS FROM THE BINANCE SIDE (non-negotiable — the shared
4
+ // adapter-contract suite runs against both):
5
+ // ★ null ≠ empty. EVERY read returns `null` on a FAILED fetch, never `[]`.
6
+ // `[]` means "the exchange said: nothing". Callers make destructive decisions
7
+ // (cancel a bracket, close a position, trust a snapshot) on that difference.
8
+ // ★ Reads are pre-gated (`assertNotLimited`), order/cancel paths are NOT (an
9
+ // exit must never be blocked by our own pacer) but every path arms the gate
10
+ // via `noteError`.
11
+ //
12
+ // HYPERLIQUID-SPECIFIC LANDMINES (all verified live on testnet 2026-07-12):
13
+ // ★ ccxt AUTO-MONETIZES an authed HL client — `initializeClient()` enrolls
14
+ // CCXT's own builder fee (1bp/order) + referral code on the first signed call.
15
+ // `options.{builderFee:false, refSet:true}` disables both. A test pins this.
16
+ // ★ Market orders REQUIRE a reference price (ccxt derives the slippage cap from
17
+ // it) — `createOrder(sym,'market',side,size)` with no price THROWS client-side.
18
+ // There is no native market order on HL: it is an IOC limit at a bounded price.
19
+ // ★ Signed actions carry a NONCE (epoch ms) and HL keeps only the 100 highest
20
+ // per signer. Two actions signed in the same millisecond can collide → every
21
+ // signed action goes through a monotonic-nonce MUTEX (one in-flight at a time,
22
+ // strictly increasing ms). This is why `submitOrders` batches a bracket pair
23
+ // into ONE action rather than firing two.
24
+ // ★ Agent (API) wallets can only TRADE. `usdClassTransfer`/withdraw are
25
+ // user-signed actions and fail with "Must deposit before performing actions"
26
+ // when signed by an agent. We never call them.
27
+ import { createRequire } from 'node:module';
28
+ import { logger } from '../../logger.js';
29
+ import { toCcxtSymbol } from '../symbols.js';
30
+ import { assertNotLimited, noteError, noteSuccess, exchangeIpWeight, updateAddressBudget, } from './hl-rate-gate.js';
31
+ import { isValidHlCloid } from './hl-cloid.js';
32
+ // ccxt via CJS require — OpenClaw's ESM loader yields the wrong module shape
33
+ // (same rationale as binance-private.ts / hl-public.ts).
34
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
+ let ccxtCjs;
36
+ try {
37
+ const _require = createRequire(import.meta.url);
38
+ ccxtCjs = _require('ccxt');
39
+ }
40
+ catch {
41
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
42
+ ccxtCjs = require('ccxt');
43
+ }
44
+ const TAG = 'hl-private';
45
+ /** The CCXT options that MUST be present on every authed HL client. Exported so
46
+ * `hl-private.test.ts` can assert them — if a future ccxt bump changes the
47
+ * option names, the test fails rather than the users paying a silent 1bp. */
48
+ export const HL_REQUIRED_OPTIONS = {
49
+ builderFee: false,
50
+ refSet: true,
51
+ };
52
+ /**
53
+ * Serializes every signed action behind a monotonic nonce.
54
+ *
55
+ * HL keeps the 100 highest nonces per signer and rejects repeats; two actions
56
+ * signed inside the same millisecond can therefore collide and one is silently
57
+ * lost. Rather than hand-rolling nonces (ccxt owns that), we guarantee that no
58
+ * two signed actions are ever *issued* in the same millisecond from this process:
59
+ * each waits for the previous to settle AND for the clock to advance.
60
+ */
61
+ class NonceMutex {
62
+ chain = Promise.resolve();
63
+ lastIssuedMs = 0;
64
+ run(fn) {
65
+ const next = this.chain.then(async () => {
66
+ const now = Date.now();
67
+ if (now <= this.lastIssuedMs) {
68
+ // Same-ms collision guard: wait out the millisecond.
69
+ await new Promise((r) => setTimeout(r, this.lastIssuedMs - now + 1));
70
+ }
71
+ this.lastIssuedMs = Date.now();
72
+ return fn();
73
+ });
74
+ // Keep the chain alive even when a link rejects (otherwise one failed action
75
+ // would poison every later one).
76
+ this.chain = next.then(() => undefined, () => undefined);
77
+ return next;
78
+ }
79
+ }
80
+ export class HyperliquidPrivateApi {
81
+ creds;
82
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
+ exchange;
84
+ mutex = new NonceMutex();
85
+ marketsLoaded = false;
86
+ constructor(creds) {
87
+ this.creds = creds;
88
+ if (!creds.walletAddress || !creds.agentPrivateKey) {
89
+ throw new Error('HyperliquidPrivateApi requires walletAddress + agentPrivateKey');
90
+ }
91
+ this.exchange = new ccxtCjs.hyperliquid({
92
+ walletAddress: creds.walletAddress,
93
+ privateKey: creds.agentPrivateKey,
94
+ options: { ...HL_REQUIRED_OPTIONS },
95
+ enableRateLimit: true,
96
+ });
97
+ if (creds.testnet) {
98
+ this.exchange.setSandboxMode(true);
99
+ const url = JSON.stringify(this.exchange.urls?.api ?? '');
100
+ if (!url.includes('testnet')) {
101
+ throw new Error(`HL testnet requested but sandbox URL is not testnet: ${url.slice(0, 80)}`);
102
+ }
103
+ }
104
+ logger.info(TAG, `Hyperliquid private API initialized (${creds.testnet ? 'TESTNET' : 'MAINNET'}, master ${creds.walletAddress.slice(0, 8)}…)`);
105
+ }
106
+ /** Exposed for the options-pin test + diagnostics. */
107
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
108
+ getExchange() {
109
+ return this.exchange;
110
+ }
111
+ async loadMarkets() {
112
+ try {
113
+ assertNotLimited('meta');
114
+ await this.exchange.loadMarkets();
115
+ noteSuccess('meta');
116
+ this.marketsLoaded = true;
117
+ return true;
118
+ }
119
+ catch (err) {
120
+ noteError(err, 'loadMarkets');
121
+ logger.error(TAG, `loadMarkets failed: ${msg(err)}`);
122
+ return false;
123
+ }
124
+ }
125
+ // ---- Reads (null on failure — NEVER []) ----
126
+ /** Positions for the MASTER account. `null` = fetch failed (state unknown);
127
+ * `[]` = the exchange confirmed flat. */
128
+ async fetchPositions(symbol) {
129
+ try {
130
+ assertNotLimited('clearinghouseState');
131
+ const symbols = symbol ? [toCcxtSymbol('hyperliquid', symbol)] : undefined;
132
+ const raw = await this.exchange.fetchPositions(symbols);
133
+ noteSuccess('clearinghouseState');
134
+ if (!Array.isArray(raw))
135
+ return null;
136
+ return raw.filter((p) => Math.abs(Number(p.contracts ?? 0)) > 0);
137
+ }
138
+ catch (err) {
139
+ noteError(err, 'fetchPositions');
140
+ logger.error(TAG, `fetchPositions failed: ${msg(err)}`);
141
+ return null;
142
+ }
143
+ }
144
+ /** Open orders INCLUDING trigger/TPSL legs. CCXT's HL `fetchOpenOrders`
145
+ * defaults to `frontendOpenOrders`, which is the only endpoint that returns
146
+ * trigger orders (plan §3.6) — the analog of Binance's merged algo endpoints. */
147
+ async fetchOpenOrders(symbol) {
148
+ try {
149
+ assertNotLimited('frontendOpenOrders');
150
+ const s = symbol ? toCcxtSymbol('hyperliquid', symbol) : undefined;
151
+ const raw = await this.exchange.fetchOpenOrders(s);
152
+ noteSuccess('frontendOpenOrders');
153
+ return Array.isArray(raw) ? raw : null;
154
+ }
155
+ catch (err) {
156
+ noteError(err, 'fetchOpenOrders');
157
+ logger.error(TAG, `fetchOpenOrders failed: ${msg(err)}`);
158
+ return null;
159
+ }
160
+ }
161
+ async fetchBalance() {
162
+ try {
163
+ assertNotLimited('clearinghouseState');
164
+ const raw = await this.exchange.fetchBalance();
165
+ noteSuccess('clearinghouseState');
166
+ return raw ?? null;
167
+ }
168
+ catch (err) {
169
+ noteError(err, 'fetchBalance');
170
+ logger.error(TAG, `fetchBalance failed: ${msg(err)}`);
171
+ return null;
172
+ }
173
+ }
174
+ /** Per-order status — the liveness resolver's REST tier (Tier 2 of the
175
+ * 3-tier rule). Weight 2. `null` = lookup FAILED (unknown), which callers
176
+ * must treat as "do not act", NOT as "gone". */
177
+ async fetchOrder(orderId, symbol) {
178
+ try {
179
+ assertNotLimited('orderStatus');
180
+ const s = symbol ? toCcxtSymbol('hyperliquid', symbol) : undefined;
181
+ const raw = await this.exchange.fetchOrder(orderId, s);
182
+ noteSuccess('orderStatus');
183
+ return raw ?? null;
184
+ }
185
+ catch (err) {
186
+ noteError(err, 'fetchOrder');
187
+ logger.warn(TAG, `fetchOrder(${orderId}) failed: ${msg(err)}`);
188
+ return null;
189
+ }
190
+ }
191
+ /** Own fills. WS is the authoritative ingress (plan + the audit-trail rule);
192
+ * this is the gap-fill/truth-check path. NOTE: only the 10,000 most recent
193
+ * fills exist server-side — deep history is NOT queryable on HL, which is why
194
+ * the `trades` table must be WS-first. */
195
+ async fetchMyTrades(symbol, since, limit = 100) {
196
+ try {
197
+ assertNotLimited('userFills');
198
+ const s = symbol ? toCcxtSymbol('hyperliquid', symbol) : undefined;
199
+ const raw = await this.exchange.fetchMyTrades(s, since, limit);
200
+ noteSuccess('userFills');
201
+ return Array.isArray(raw) ? raw : null;
202
+ }
203
+ catch (err) {
204
+ noteError(err, 'fetchMyTrades');
205
+ logger.error(TAG, `fetchMyTrades failed: ${msg(err)}`);
206
+ return null;
207
+ }
208
+ }
209
+ /** Refresh the ADDRESS action budget (the starvation guard). Weight 20 — call
210
+ * every ~5 min, never per-heartbeat. */
211
+ async refreshAddressBudget() {
212
+ try {
213
+ assertNotLimited('userRateLimit');
214
+ const res = await this.rawInfo({ type: 'userRateLimit', user: this.creds.walletAddress });
215
+ noteSuccess('userRateLimit');
216
+ const used = Number(res?.nRequestsUsed);
217
+ const cap = Number(res?.nRequestsCap);
218
+ if (Number.isFinite(used) && Number.isFinite(cap)) {
219
+ updateAddressBudget({ nRequestsUsed: used, nRequestsCap: cap });
220
+ }
221
+ }
222
+ catch (err) {
223
+ noteError(err, 'userRateLimit');
224
+ logger.warn(TAG, `refreshAddressBudget failed: ${msg(err)}`);
225
+ }
226
+ }
227
+ /** Raw `POST /info` — for the handful of reads CCXT doesn't expose
228
+ * (userRateLimit, userNonFundingLedgerUpdates, portfolio). Never used for
229
+ * signed actions. */
230
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
231
+ async rawInfo(body) {
232
+ const base = this.creds.testnet
233
+ ? 'https://api.hyperliquid-testnet.xyz'
234
+ : 'https://api.hyperliquid.xyz';
235
+ const res = await fetch(`${base}/info`, {
236
+ method: 'POST',
237
+ headers: { 'content-type': 'application/json' },
238
+ body: JSON.stringify(body),
239
+ signal: AbortSignal.timeout(15_000),
240
+ });
241
+ if (!res.ok)
242
+ throw new Error(`POST /info ${String(body.type)} → ${res.status}`);
243
+ return res.json();
244
+ }
245
+ // ---- Signed actions (NEVER pre-gated; always nonce-serialized) ----
246
+ /** Submit one order. Market orders are IOC-limit emulated — `price` is
247
+ * MANDATORY (ccxt throws without it) and the caller must already have applied
248
+ * the slippage bound + HL rounding (hl-precision). */
249
+ async submitOrder(req) {
250
+ if (req.cloid && !isValidHlCloid(req.cloid)) {
251
+ throw new Error(`Invalid HL cloid ${req.cloid} — must be 0x + 32 hex chars`);
252
+ }
253
+ return this.mutex.run(async () => {
254
+ try {
255
+ const params = this.buildParams(req);
256
+ const order = await this.exchange.createOrder(toCcxtSymbol('hyperliquid', req.symbol), req.type === 'market' ? 'market' : 'limit', req.side, req.amount, req.price, // ★ always passed — ccxt needs it even for 'market'
257
+ params);
258
+ noteSuccess('exchange', { ipWeight: exchangeIpWeight(1), addressActions: 1 });
259
+ return order ?? null;
260
+ }
261
+ catch (err) {
262
+ noteError(err, 'submitOrder');
263
+ // Order paths RETHROW (the caller must see a rejection) — unlike reads,
264
+ // which collapse to null.
265
+ throw err;
266
+ }
267
+ });
268
+ }
269
+ /** Submit N orders as ONE signed action (one nonce, one `/exchange` call).
270
+ * This is how a bracket pair (SL+TP) is placed: atomic-ish, and it costs 1 IP
271
+ * weight unit but N address actions. */
272
+ async submitOrders(reqs) {
273
+ if (reqs.length === 0)
274
+ return [];
275
+ for (const r of reqs) {
276
+ if (r.cloid && !isValidHlCloid(r.cloid)) {
277
+ throw new Error(`Invalid HL cloid ${r.cloid} — must be 0x + 32 hex chars`);
278
+ }
279
+ }
280
+ return this.mutex.run(async () => {
281
+ try {
282
+ const ccxtReqs = reqs.map((r) => ({
283
+ symbol: toCcxtSymbol('hyperliquid', r.symbol),
284
+ type: r.type === 'market' ? 'market' : 'limit',
285
+ side: r.side,
286
+ amount: r.amount,
287
+ price: r.price,
288
+ params: this.buildParams(r),
289
+ }));
290
+ const orders = await this.exchange.createOrders(ccxtReqs);
291
+ noteSuccess('exchange', {
292
+ ipWeight: exchangeIpWeight(reqs.length),
293
+ addressActions: reqs.length, // ★ batches cost n against the ADDRESS budget
294
+ });
295
+ return Array.isArray(orders) ? orders : null;
296
+ }
297
+ catch (err) {
298
+ noteError(err, 'submitOrders');
299
+ throw err;
300
+ }
301
+ });
302
+ }
303
+ async cancelOrder(orderId, symbol) {
304
+ return this.mutex.run(async () => {
305
+ try {
306
+ const res = await this.exchange.cancelOrder(orderId, toCcxtSymbol('hyperliquid', symbol));
307
+ noteSuccess('exchange', { ipWeight: exchangeIpWeight(1), addressActions: 1 });
308
+ return res ?? null;
309
+ }
310
+ catch (err) {
311
+ noteError(err, 'cancelOrder');
312
+ throw err;
313
+ }
314
+ });
315
+ }
316
+ /** Cancel by cloid — the bracket path's cancel (we always know our own cloid,
317
+ * and it survives a restart because it is derived, not stored). */
318
+ async cancelOrderByCloid(cloid, symbol) {
319
+ return this.mutex.run(async () => {
320
+ try {
321
+ const res = await this.exchange.cancelOrder(cloid, toCcxtSymbol('hyperliquid', symbol), { clientOrderId: cloid });
322
+ noteSuccess('exchange', { ipWeight: exchangeIpWeight(1), addressActions: 1 });
323
+ return res ?? null;
324
+ }
325
+ catch (err) {
326
+ noteError(err, 'cancelOrderByCloid');
327
+ throw err;
328
+ }
329
+ });
330
+ }
331
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
332
+ buildParams(req) {
333
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
334
+ const params = {};
335
+ if (req.reduceOnly)
336
+ params.reduceOnly = true;
337
+ if (req.postOnly)
338
+ params.postOnly = true; // → ALO
339
+ if (req.cloid)
340
+ params.clientOrderId = req.cloid;
341
+ if (req.trigger) {
342
+ // HL trigger orders fire on MARK price only (no workingType choice).
343
+ params.triggerPrice = req.trigger.triggerPrice;
344
+ if (req.trigger.tpsl === 'tp')
345
+ params.takeProfitPrice = req.trigger.triggerPrice;
346
+ else
347
+ params.stopLossPrice = req.trigger.triggerPrice;
348
+ }
349
+ return params;
350
+ }
351
+ get isMarketsLoaded() {
352
+ return this.marketsLoaded;
353
+ }
354
+ }
355
+ function msg(err) {
356
+ return err instanceof Error ? err.message : String(err);
357
+ }
@@ -15,6 +15,9 @@ export declare class HyperliquidPublicApi implements PublicMarketDataApi {
15
15
  /** One upstream fetchTickers call serves every symbol within the TTL. */
16
16
  private tickersCache;
17
17
  private tickersInflight;
18
+ /** Coin → mid from one weight-2 allMids call (fetchTicker's price source). */
19
+ private midsCache;
20
+ private midsInflight;
18
21
  constructor(opts?: HyperliquidPublicApiOptions);
19
22
  private baseUrl;
20
23
  /** Canonical/ccxt symbol → this venue's ccxt symbol, or null (logged) when
@@ -24,11 +27,24 @@ export declare class HyperliquidPublicApi implements PublicMarketDataApi {
24
27
  /** Fetch-all-tickers with a short TTL + inflight dedup. Returns a map keyed
25
28
  * by ccxt symbol, or null on failure. */
26
29
  private getTickers;
30
+ /** Coin → mid price from one weight-2 `allMids` call (TTL-cached, inflight-
31
+ * deduped; docs: hyperliquid.gitbook.io → Info endpoint → "Retrieve mids
32
+ * for all coins"). Null on ANY failure — callers fall back to the full
33
+ * snapshot path. Spot entries (`@<idx>` keys) parse fine and are simply
34
+ * never looked up (we key by perp coin name). */
35
+ private getMids;
36
+ /** Fire-and-forget full-snapshot refresh once it ages past
37
+ * FULL_SNAPSHOT_REFRESH_MS — fetchTicker must never block on the heavy
38
+ * fetchTickers call when a fresh mid is available. getTickers' own
39
+ * inflight dedup + error handling make this safe to kick repeatedly. */
40
+ private maybeRefreshSnapshot;
27
41
  fetchTickerRaw(symbol: string): Promise<Record<string, any> | null>;
28
- /** Ticker from the cached all-assets snapshot. Hyperliquid's asset contexts
29
- * carry mark/mid rather than a trade-tape bid/ask; absent fields fall back
30
- * to `last` with zero modeled spread the paper fill engine models
31
- * slippage itself (same convention as IntelPublicApi). */
42
+ /** Price from the weight-2 allMids fast path; volume/change context from
43
+ * the last full snapshot (background-refreshed). Hyperliquid's asset
44
+ * contexts carry mark/mid rather than a trade-tape bid/ask; absent fields
45
+ * fall back to `last` with zero modeled spread — the paper fill engine
46
+ * models slippage itself (same convention as IntelPublicApi). Falls back
47
+ * to the original blocking full-snapshot path when allMids fails. */
32
48
  fetchTicker(symbol: string): Promise<CcxtTicker | null>;
33
49
  fetchFundingRate(symbol: string): Promise<Record<string, any> | null>;
34
50
  fetchOpenInterest(symbol: string): Promise<Record<string, any> | null>;
@@ -49,4 +65,15 @@ export declare class HyperliquidPublicApi implements PublicMarketDataApi {
49
65
  outcome: 'reachable' | 'geo_blocked' | 'unreachable' | 'unknown';
50
66
  driftMs: number | null;
51
67
  }>;
68
+ /** `meta` — the asset universe (szDecimals, maxLeverage, positional assetIndex).
69
+ * Keyless info read, weight 20. Feeds HyperliquidInfoCache. Returns null on any
70
+ * failure (never a partial universe — a half-loaded rules table would silently
71
+ * reject orders). */
72
+ fetchMeta(): Promise<any | null>;
73
+ /** ★ MARK price — the price HL trigger orders fire on (there is no workingType
74
+ * choice on this venue). Stop-distance validation and every trigger MUST use
75
+ * this, never `last`: the mark is a CEX-composite median that can diverge from
76
+ * HL's own last trade. Sourced from `metaAndAssetCtxs` (one weight-20 call
77
+ * covers every asset). Returns null on failure — never a stale guess. */
78
+ fetchMarkPrice(symbol: string): Promise<number | null>;
52
79
  }