Get your dream built 10x faster

How to integrate Hyperliquid Trading & Analysis with OpenClaw

We build custom applications 5x faster and cheaper 🚀

Book a Free Consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Stuck on an error? Book a 30-minute call with an engineer and get a direct fix + next steps. No pressure, no commitment.

How to integrate Hyperliquid Trading & Analysis with OpenClaw

Direct answer: Build a small, explicit OpenClaw skill that calls Hyperliquid’s REST APIs (or uses Hyperliquid OAuth flows), store credentials securely via ClawHub’s secret/environment configuration, host any webhook receivers and long-running or stateful work in an external service (web server + database), and wire the skill to invoke that service. Authenticate every API call, verify webhook signatures, handle token refresh and retries outside the agent runtime, and use logs and HTTP responses to debug. The integration is an explicit set of API calls, secrets, and webhooks — not magic — so design around clear authentication, scope limits, monitoring, and moving stateful components out of the agent runtime for reliability.

 

Planning and high-level design

 

  • Decide how Hyperliquid authenticates: API key (Bearer) or OAuth2. Consult Hyperliquid docs for exact endpoints and scopes. Your code must implement the flows the vendor documents.
  • Separate responsibilities: Keep the OpenClaw skill lightweight and stateless. Put webhooks, token refresh, scheduling, and persistence in an external service you control (web server + DB or queue).
  • Secrets and configuration: Store API keys, client secrets, webhook secrets, and environment variables in ClawHub’s secret/config mechanism when you install the skill. Do not hard-code them in the skill bundle.
  • Security model: Use least privilege scopes, rotate credentials, validate webhook HMACs, enforce TLS, and use signed requests where possible.
  • Observability: Add structured logs and correlation IDs, and expose metrics/alerts for failures, authentication errors, and rate-limit responses.

 

Concrete components you will build

 

  • External service (recommended): a web server (example: Node/Express) that:
    • Receives Hyperliquid webhooks and validates signatures.
    • Performs trade placement and polling that might be longer-running than the agent runtime allows.
    • Stores state (orders, positions, tokens) in a database or a secure secret store.
  • OpenClaw skill: a small handler that:
    • Accepts a request from an agent or user and forwards intent to your external service via authenticated REST calls.
    • Is stateless: it returns quickly and relies on the external service for persistence and long tasks.
  • Secret/config management: API keys, OAuth client_id/client_secret, webhook secret, and any DB connection strings uploaded via ClawHub as environment variables or secrets when installing the skill.

 

Example: webhook receiver (Node.js, Express) — verify HMAC and accept payload

 

// Example webhook receiver (Node.js + Express)
// It expects the vendor to send an HMAC header named 'x-hl-signature' (placeholder).
// Replace header name and HMAC algorithm with values from Hyperliquid docs.

const express = require('express');
const crypto = require('crypto');

const app = express();

// Use raw body so HMAC is computed on the exact bytes received
app.use(express.raw({ type: '*/*' }));

app.post('/webhook', (req, res) => {
  const signature = req.headers['x-hl-signature']; // <b>//</b> adjust header name to vendor docs
  const secret = process.env.HL_WEBHOOK_SECRET; // <b>//</b> set in ClawHub secrets
  if (!signature || !secret) {
    return res.status(401).send('unauthorized');
  }

  // <b>//</b> compute HMAC exactly as vendor requires (sha256 shown as common example)
  const computed = crypto.createHmac('sha256', secret).update(req.body).digest('hex');

  // <b>//</b> use timingSafeEqual to avoid timing attacks
  try {
    const valid = crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(signature));
    if (!valid) {
      return res.status(401).send('invalid signature');
    }
  } catch (err) {
    return res.status(401).send('invalid signature format');
  }

  const payload = JSON.parse(req.body.toString());
  // <b>//</b> enqueue or process the payload (store to DB, notify downstream systems)
  console.log('webhook payload', payload);

  res.sendStatus(200);
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`webhook listener on ${port}`));

 

Example: calling Hyperliquid REST API with an API key (Node.js fetch)

 

// HTTP call to vendor API using an API key
// Replace URL, endpoint and JSON fields with vendor-specific values.

const fetch = require('node-fetch');

async function placeOrder(order) {
  const url = 'https://api.hyperliquid.example/v1/orders'; // <b>//</b> placeholder
  const resp = await fetch(url, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.HL_API_KEY}`, // <b>//</b> stored in ClawHub secrets
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(order)
  });

  if (!resp.ok) {
    const text = await resp.text();
    // <b>//</b> inspect status and body for vendor errors
    throw new Error(`Hyperliquid API error ${resp.status}: ${text}`);
  }
  return resp.json();
}

// <b>//</b> example usage
placeOrder({ symbol: 'BTCUSD', side: 'buy', size: 0.01 })
  .then(r => console.log('order placed', r))
  .catch(e => console.error('order failed', e));

 

Example: OAuth2 token refresh (generic)

 

// Generic OAuth2 token refresh using client credentials + refresh token
// Replace tokenUrl and parameters with vendor-provided endpoints and names.

const fetch = require('node-fetch');

async function refreshAccessToken(refreshToken) {
  const tokenUrl = 'https://auth.hyperliquid.example/oauth/token'; // <b>//</b> placeholder
  const params = new URLSearchParams();
  params.append('grant_type', 'refresh_token');
  params.append('refresh_token', refreshToken);
  params.append('client_id', process.env.HL_CLIENT_ID);
  params.append('client_secret', process.env.HL_CLIENT_SECRET);

  const res = await fetch(tokenUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: params
  });

  if (!res.ok) {
    const body = await res.text();
    throw new Error(`token refresh failed ${res.status}: ${body}`);
  }
  return res.json(); // <b>//</b> contains new access_token (+ maybe new refresh_token)
}

 

How the OpenClaw skill should interact with your external service

 

  • Skill invocation: the skill code (running in the agent runtime) should be minimal: validate input, call your external HTTP API (authenticated using a secret stored in ClawHub), and return an immediate response (ack or error). Do not try to hold long-running tasks in the skill runtime.
  • External endpoints: provide endpoints for actions the skill needs: /v1/execute-order, /v1/query-position, /v1/health, etc. The skill makes a short HTTP call to these endpoints.
  • Authentication between OpenClaw skill and external service: use an API key or mTLS between your skill and your service, and keep the key in ClawHub secrets. Rotate keys regularly.

 

ClawHub and secret management (vendor-neutral guidance)

 

  • When you publish/install a skill: upload the skill bundle and configure environment variables and secrets in ClawHub (or the platform’s secret store). Put HL_API_KEY, HL_CLIENT_ID, HL_CLIENT_SECRET, HL_WEBHOOK_SECRET, DB\_CONNECTION, and other sensitive values there.
  • Permissions/scopes: ensure the credential scopes match what you need (trading scope vs read-only). Ask Hyperliquid for least-privilege credentials if possible.
  • Where to store refresh tokens or persistent credentials: store them in a secure external store (vault/DB) used by your external service. The agent runtime should not be relied on for long-term storage or for refreshing tokens on schedule.

 

Testing and local development

 

  • Sandbox credentials: request sandbox API keys from Hyperliquid for development.
  • Local webhook testing: use a tunnel (ngrok) to expose your local webhook receiver so Hyperliquid can call it. Keep secrets secret; don’t commit them to source control.
  • Replay fixtures: record webhook payloads and replay them in tests to verify signature verification and processing logic.

 

Debugging checklist when things break

 

  • Inspect HTTP response codes and bodies from Hyperliquid. Log full request/response pairs (sanitized).
  • Verify credentials and their scopes; expired tokens are a common failure point.
  • Confirm webhook signature algorithm and header name exactly match vendor docs; signature mismatches are frequent.
  • Check rate-limit headers and backoff appropriately. Implement exponential retry with idempotency keys for create operations.
  • Ensure your external service’s certificates and DNS are valid so Hyperliquid can reach your webhook URL.
  • Validate that the OpenClaw skill is actually invoking your endpoint (use access logs, correlation IDs passed in headers).

 

Operational and security best practices

 

  • Least privilege: scope tokens & API keys to only what’s needed (trades vs read-only market data).
  • Secrets lifecycle: rotate credentials, store them in ClawHub secrets or a vault, and never embed them in code.
  • Idempotency: use idempotency keys for order creation to avoid duplicate executions on retry.
  • Keep state outside the agent: use a durable DB for orders/positions and a background worker for retries and reconciliation.
  • Observability: centralized logs, metrics for failed auth + rate-limit events, and alerting on webhook 401/403s.

 

What you must consult the Hyperliquid docs for

 

  • Exact REST endpoints, required request/response shapes, and JSON field names.
  • Authentication details: is it API key in Authorization header, or OAuth2 (and exact token endpoint and scopes)?
  • Webhook signature header name, algorithm, and exact canonicalization method for computing HMAC.
  • Rate limits and recommended retry/backoff semantics.

 

Final integration checklist (practical steps)

 

  • Obtain Hyperliquid sandbox/production credentials and note scopes.
  • Implement external service: webhook receiver, order execution endpoints, state store, token refresh.
  • Write the OpenClaw skill to call your service; keep it stateless and fast.
  • Store all secrets and env vars in ClawHub when installing the skill; ensure the skill reads from env vars.
  • Verify webhooks with HMAC and TLS; test with recorded webhook payloads.
  • Enable robust logging, retries, idempotency, and alerts for auth/rate-limit failures.

Book Your Free 30‑Minute Migration Call

Speak one‑on‑one with a senior engineer about your no‑code app, migration goals, and budget. In just half an hour you’ll leave with clear, actionable next steps—no strings attached.

Book a Free Consultation

Troubleshooting Hyperliquid Trading & Analysis and OpenClaw Integration

1

Why does ClawConnector fail WebSocket authentication to Hyperliquid with "401 Unauthorized" when using HMAC API key in claw_config.yaml?

Direct answer: The 401 happens because Hyperliquid’s WebSocket handshake requires a freshly computed HMAC (usually including a timestamp/nonce and the connect path/payload) but the ClawConnector configured via claw_config.yaml only provides static keys — it does not automatically compute or inject the dynamic signature into the WS handshake. The server therefore rejects an unsigned/incorrectly-signed connect.

 

Why it fails

 

The handshake must carry a valid, time‑bound signature. Common causes:

  • No dynamic signature: config supplies key/secret but no runtime HMAC generation.
  • Clock skew: timestamp in signature is outside allowed window.
  • Wrong secret or payload: wrong value used to compute digest or wrong canonical string.
  • Headers not forwarded: connector doesn’t send custom headers or query params on WS connect.

 

How to fix

 

Compute the HMAC at connect time and include it in the WS handshake (header or query param per Hyperliquid docs). Example (Node.js):

```js // compute signature and attach to websocket headers const crypto = require('crypto'); const sig = crypto.createHmac('sha256', secret).update(`${ts}${method}${path}`).digest('hex'); const ws = new WebSocket(url, { headers: { 'X-API-KEY': key, 'X-SIGNATURE': sig, 'X-TIMESTAMP': ts } }); ```

2

Why does ClawOrderBook drop Hyperliquid level2 deltas due to sequence number mismatch between snapshot and incremental updates?

 

Direct answer

 

ClawOrderBook drops Hyperliquid level2 deltas when the snapshot sequence number and the incoming incremental update sequence don’t line up, because applying out‑of‑order or gapped deltas would corrupt the local book. The implementation rejects unsafe deltas and forces a resync (fresh snapshot + aligned seq) rather than risking inconsistent state.

 

Why this happens and how to handle it

 

This is a safety-first design: level2 deltas assume a precise sequence when they are applied. If there’s a gap, overlap, or mismatch you must:

  • Detect the mismatch by comparing snapshot.seq to first delta.prev_seq.
  • Drop deltas that can’t be applied in order.
  • Resync by fetching a new snapshot and restarting delta consumption.
  • Log and monitor websocket/REST delivery and implement retries/backoff.

3

Why do Hyperliquid execution reports map to incorrect OpenClaw OrderManager statuses (e.g., PARTIAL_FILL vs FILLED) causing reconciliation errors?

 

Why this happens (direct answer)

 

Direct answer: Incorrect mapping usually comes from interpreting Hyperliquid's execution report fields incorrectly — using last-fill instead of cumulative-filled, misreading status enums, or letting tiny rounding remainders keep an order as PARTIAL_FILL; combined with out-of-order or missing events this produces reconciliation mismatches.

 

Expanded explanation and debugging steps

 
  • Inspect raw reports: log entire payload, timestamps, cumulativeQty vs lastQty, status enums.
  • Use cumulative fills: derive FILLED when cumulativeFilled >= orderQty - epsilon (handle decimals).
  • Handle ordering/idempotency: apply sequence numbers/timestamps and dedupe updates.
  • Watch webhooks/transport: lost/fuzzy retries can skip final fill events.
  • Fix mapping code: map enums explicitly, add epsilon for precision, and test with edge cases.

4

Why does ClawRiskModule reject Hyperliquid orders with "InvalidLotSize" or "InvalidTickSize" when ClawSymbolTable decimals and lot size settings differ from Hyperliquid symbol metadata?

Direct answer: ClawRiskModule rejects orders because it enforces that quantities and prices match the symbol rules (lot size/step and tick size/decimals) stored in ClawSymbolTable; if those configured values differ from Hyperliquid’s live symbol metadata the module flags a mismatch as InvalidLotSize or InvalidTickSize.

 

Why this happens and how to fix it

 

ClawRiskModule validates that order quantity is an integer multiple of the symbol’s lot step and that price aligns to the tick. Mismatched decimals or steps cause rounding/precision differences so the check fails.

  • Fetch Hyperliquid symbol metadata (minQty, stepSize, tickSize, decimals).
  • Update ClawSymbolTable to match, or quantize values before submit.
// Quantize price/qty to exchange rules
function quantize(value, step){
  // return nearest multiple of step
  return Math.round(value / step) * step;
}
// // use integer scaling if needed to avoid float errors
Book a Free Consultation

Still stuck?
Copy this prompt into ChatGPT and get a clear, personalized explanation.

This prompt helps an AI assistant understand your setup and guide you through the fix step by step, without assuming technical knowledge.

AI AI Prompt


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â