__init__.py
"""
Hyperliquid Extension — Perpetual & Spot Trading on Hyperliquid DEX
Provides 19 tools for trading on Hyperliquid:
- 8 info tools: account state, balances, orders, market data, orderbook, fills, candles, funding
- 11 exchange tools: order, spot order, TP/SL order, cancel, cancel all, modify, leverage, USDC transfer, withdraw, deposit, set abstraction
Environment Variables:
- WALLET_SERVICE_URL: Privy wallet service URL (required for signing)
Usage:
This extension is auto-loaded by the ExtensionLoader.
"""
import logging
from typing import List
logger = logging.getLogger(__name__)
def register(api) -> List[str]:
"""
Extension entry point — register all Hyperliquid tools.
Args:
api: ExtensionApi instance with registry and config
Returns:
List of registered tool names
"""
registered = []
try:
from .tools import (
# Info tools (8)
HLAccountTool,
HLBalancesTool,
HLOpenOrdersTool,
HLMarketTool,
HLOrderbookTool,
HLFillsTool,
HLCandlesTool,
HLFundingTool,
# Exchange tools (11)
HLOrderTool,
HLSpotOrderTool,
HLTPSLOrderTool,
HLCancelTool,
HLCancelAllTool,
HLModifyTool,
HLLeverageTool,
HLTransferUsdTool,
HLWithdrawTool,
HLDepositTool,
HLSetAbstractionTool,
)
# Info tools
api.register_tool(HLAccountTool())
api.register_tool(HLBalancesTool())
api.register_tool(HLOpenOrdersTool())
api.register_tool(HLMarketTool())
api.register_tool(HLOrderbookTool())
api.register_tool(HLFillsTool())
api.register_tool(HLCandlesTool())
api.register_tool(HLFundingTool())
# Exchange tools
api.register_tool(HLOrderTool())
api.register_tool(HLSpotOrderTool())
api.register_tool(HLTPSLOrderTool())
api.register_tool(HLCancelTool())
api.register_tool(HLCancelAllTool())
api.register_tool(HLModifyTool())
api.register_tool(HLLeverageTool())
api.register_tool(HLTransferUsdTool())
api.register_tool(HLWithdrawTool())
api.register_tool(HLDepositTool())
api.register_tool(HLSetAbstractionTool())
registered = [
# Info (8)
"hl_account",
"hl_balances",
"hl_open_orders",
"hl_market",
"hl_orderbook",
"hl_fills",
"hl_candles",
"hl_funding",
# Exchange (11)
"hl_order",
"hl_spot_order",
"hl_tpsl_order",
"hl_cancel",
"hl_cancel_all",
"hl_modify",
"hl_leverage",
"hl_transfer_usd",
"hl_withdraw",
"hl_deposit",
"hl_set_abstraction",
]
logger.info(f"Registered Hyperliquid tools ({len(registered)} tools)")
except Exception as e:
logger.warning(f"Failed to load Hyperliquid tools: {e}")
return registered
# Extension metadata
EXTENSION_INFO = {
"name": "hyperliquid",
"version": "1.0.0",
"description": "Hyperliquid DEX trading — perpetual futures and spot",
"tools": [
"hl_account",
"hl_balances",
"hl_open_orders",
"hl_market",
"hl_orderbook",
"hl_fills",
"hl_candles",
"hl_funding",
"hl_order",
"hl_spot_order",
"hl_tpsl_order",
"hl_cancel",
"hl_cancel_all",
"hl_modify",
"hl_leverage",
"hl_transfer_usd",
"hl_withdraw",
"hl_deposit",
"hl_set_abstraction",
],
"env_vars": [
"WALLET_SERVICE_URL",
],
}
_trade_report.py
"""Fire-and-forget trade event reporting to the Starchild trade analytics API.
Posts executed orders/swaps to POST {AI_AGENT_API_URL}/v1/trade-events using
the machine's CONTAINER_JWT. Reporting must NEVER affect trading:
- runs in a daemon thread
- swallows all exceptions
- no-ops silently when env vars are missing (e.g. local dev)
Event dict fields (all optional except source/venue/event_type/dedupe_key):
source, venue, event_type ('order'|'fill'|'swap'|'cancel'),
dedupe_key, wallet_address, account_id, symbol, side ('buy'|'sell'),
price, size, notional_usd, fee, fee_currency, order_id, tx_hash,
raw (dict), occurred_at (ISO8601 str)
"""
import json
import logging
import os
import threading
import urllib.request
logger = logging.getLogger(__name__)
_TIMEOUT = 10
def report_trade_events(events):
"""Report a list of trade event dicts. Fire-and-forget, never raises."""
try:
if not events:
return
base = os.environ.get("AI_AGENT_API_URL", "").rstrip("/")
token = os.environ.get("CONTAINER_JWT", "")
if not base or not token:
return
def _send():
try:
req = urllib.request.Request(
f"{base}/v1/trade-events",
data=json.dumps({"events": events}).encode("utf-8"),
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
},
method="POST",
)
with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
resp.read()
except Exception as e: # noqa: BLE001 — reporting must never break trading
logger.debug(f"trade report failed (ignored): {e}")
threading.Thread(target=_send, daemon=True).start()
except Exception: # noqa: BLE001
pass
client.py
"""
Hyperliquid API Client — wraps /info (read-only) and /exchange (signed) endpoints.
Uses the hyperliquid-python-sdk Info class for reads, and custom signing
(via wallet service) for exchange actions.
"""
import logging
import os
import time
from decimal import Decimal
from typing import Any, Dict, Optional
import aiohttp
from .signing import sign_l1_action, sign_user_action, sign_user_set_abstraction, sign_approve_builder_fee
logger = logging.getLogger(__name__)
DEFAULT_API_URL = "https://api.hyperliquid.xyz"
DEFAULT_SLIPPAGE = 0.03 # 3% for market orders
# ── Builder Code (platform fee collection) ──────────────────────────────
# Starchild builder address — collects a small fee on each fill to support
# platform operations. Users must approve this builder once via ApproveBuilderFee.
# The builder fee parameter "f" is in tenths of basis points: f=20 → 2 bps.
BUILDER_ADDRESS = "0x2c5320F40305fFC933385c6DCec5493fbA7b98b8"
BUILDER_FEE_TENTHS_OF_BPS = 20 # 20 tenths-of-bps = 2 bps (0.02%)
BUILDER_MAX_FEE_RATE = "0.02%" # shown to user during ApproveBuilderFee
def float_to_wire(x: float) -> str:
"""Convert a float to a string matching Hyperliquid's server-side normalization.
Matches the official Hyperliquid Python SDK: rounds to 8 decimal places,
then strips trailing zeros via Decimal.normalize().
"""
rounded = f"{x:.8f}"
if abs(float(rounded) - x) >= 1e-12:
raise ValueError(f"float_to_wire: rounding loses precision for {x}")
if rounded == "-0.00000000":
rounded = "0.00000000"
normalized = Decimal(rounded).normalize()
return f"{normalized:f}"
# Hyperliquid bridge contract (for USDC deposits)
BRIDGE_ADDRESS = "0x2Df1c51E09aECF9cacB7bc98cB1742757f163dF7"
# USDC on Arbitrum
USDC_ADDRESS = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"
USDC_DECIMALS = 6
ARBITRUM_CHAIN_ID = 42161
MIN_DEPOSIT_USDC = 5
class HyperliquidClient:
"""
Async Hyperliquid client.
- Info methods: POST to /info (no auth)
- Exchange methods: POST to /exchange (signed)
"""
def __init__(self, api_url: Optional[str] = None):
self.api_url = api_url or os.environ.get(
"HYPERLIQUID_API_URL", DEFAULT_API_URL
)
# Cached metadata
self._meta: Optional[dict] = None
self._spot_meta: Optional[dict] = None
self._name_to_index: Dict[str, int] = {}
self._spot_name_to_index: Dict[str, int] = {}
self._spot_mid_key: Dict[str, str] = {} # user name → allMids key
self._sz_decimals: Dict[str, int] = {}
# Builder dex (HIP-3) metadata — lazy loaded
self._perp_dexs: Optional[list] = None # perpDexs API response
self._dex_offsets: Dict[str, int] = {} # dex_name -> asset index offset
self._builder_meta: Dict[str, dict] = {} # dex_name -> meta response
# ── Internal helpers ─────────────────────────────────────────────────
async def _post(self, endpoint: str, payload: dict) -> Any:
"""POST to Hyperliquid API."""
url = f"{self.api_url}{endpoint}"
async with aiohttp.ClientSession() as session:
async with session.post(
url,
json=payload,
timeout=aiohttp.ClientTimeout(total=15),
) as resp:
if resp.status >= 400:
body = await resp.text()
raise Exception(f"Hyperliquid API {resp.status}: {body}")
data = await resp.json()
# Hyperliquid returns HTTP 200 with {"status": "err", "response": "..."} for API-level errors
if isinstance(data, dict) and data.get("status") == "err":
raise Exception(f"Hyperliquid error: {data.get('response', data)}")
return data
async def _info(self, req_type: str, **kwargs) -> Any:
"""Query the /info endpoint."""
payload = {"type": req_type, **kwargs}
return await self._post("/info", payload)
async def _exchange(
self,
action: dict,
nonce: Optional[int] = None,
vault_address: Optional[str] = None,
) -> Any:
"""Submit a signed action to the /exchange endpoint.
Matches SDK's Exchange._post_action() behavior.
"""
if nonce is None:
nonce = int(time.time() * 1000)
action_type = action.get("type", "unknown")
wallet_addr = self._cached_address or "unknown"
logger.info(
f"_exchange: action_type={action_type}, wallet={wallet_addr}, nonce={nonce}"
)
signature = await sign_l1_action(action, nonce, vault_address)
# Match SDK payload structure exactly
# vaultAddress: included for most actions, None for usdClassTransfer/sendAsset
# expiresAfter: None by default (matches SDK's expires_after = None)
payload = {
"action": action,
"nonce": nonce,
"signature": signature,
"vaultAddress": vault_address if action_type not in ["usdClassTransfer", "sendAsset"] else None,
"expiresAfter": None, # matches SDK default
}
try:
result = await self._post("/exchange", payload)
self._report_exchange_action(action, result, wallet_addr, nonce)
return result
except Exception as e:
logger.error(
f"_exchange FAILED: action_type={action_type}, wallet={wallet_addr}, "
f"nonce={nonce}, error={e}"
)
raise
def _report_exchange_action(
self, action: dict, result: Any, wallet_addr: str, nonce: int
) -> None:
"""Report executed orders to trade analytics. Never raises."""
try:
if action.get("type") != "order":
return
from ._trade_report import report_trade_events
statuses = []
if isinstance(result, dict):
statuses = (
((result.get("response") or {}).get("data") or {}).get("statuses")
or []
)
idx_to_name = {v: k for k, v in self._name_to_index.items()}
spot_idx_to_name = {
10000 + v: k for k, v in self._spot_name_to_index.items()
}
events = []
for i, o in enumerate(action.get("orders", [])):
st = statuses[i] if i < len(statuses) and isinstance(statuses[i], dict) else {}
if "error" in st:
continue # rejected order — nothing executed
filled = st.get("filled") or {}
resting = st.get("resting") or {}
try:
price = float(filled.get("avgPx") or o.get("p") or 0)
size = float(filled.get("totalSz") or o.get("s") or 0)
except (TypeError, ValueError):
price, size = 0.0, 0.0
asset = o.get("a")
symbol = idx_to_name.get(asset) or spot_idx_to_name.get(asset) or str(asset)
oid = filled.get("oid") or resting.get("oid")
events.append({
"source": "hyperliquid",
"venue": "hyperliquid",
"event_type": "fill" if filled else "order",
"dedupe_key": f"hl:{wallet_addr}:{nonce}:{i}",
"wallet_address": wallet_addr,
"symbol": symbol,
"side": "buy" if o.get("b") else "sell",
"price": price,
"size": size,
"notional_usd": round(price * size, 6),
"order_id": str(oid) if oid is not None else None,
"raw": {"order": o, "status": st},
})
report_trade_events(events)
except Exception as e: # noqa: BLE001 — reporting must never break trading
logger.debug(f"trade report skipped: {e}")
async def _ensure_meta(self) -> None:
"""Fetch and cache perp + spot metadata for asset index resolution."""
if self._meta is None:
self._meta = await self._info("meta")
for i, asset in enumerate(self._meta.get("universe", [])):
name = asset["name"]
self._name_to_index[name] = i
self._sz_decimals[name] = asset.get("szDecimals", 0)
if self._spot_meta is None:
try:
self._spot_meta = await self._info("spotMeta")
for pair in self._spot_meta.get("universe", []):
# universe entries: {"tokens": [1,0], "name": "PURR/USDC", "index": 0}
# Non-canonical entries have names like "@1", "@2"
pair_name = pair.get("name", "")
idx = pair.get("index", 0)
if "/" in pair_name:
# Canonical pair like "PURR/USDC" — map base name
base = pair_name.split("/")[0]
self._spot_name_to_index[base] = idx
self._spot_mid_key[base] = pair_name # allMids uses "PURR/USDC"
elif pair_name:
# Non-canonical like "@1" — map as-is
self._spot_name_to_index[pair_name] = idx
self._spot_mid_key[pair_name] = pair_name
except Exception:
self._spot_meta = {}
async def _ensure_builder_dex(self, dex_name: str) -> None:
"""Lazy-load builder dex metadata (HIP-3 perps like xyz:NVDA).
Called only when a coin with ':' prefix is encountered.
Fetches perpDexs once to discover all builder dexes and compute offsets,
then fetches meta for the specific builder dex.
"""
# Already loaded this dex
if dex_name in self._builder_meta:
return
# Fetch perpDexs list once to compute offsets
if self._perp_dexs is None:
raw = await self._info("perpDexs")
# perpDexs returns [null, {"name": "xyz", ...}, {"name": "rage", ...}, ...]
# First element is null (default dex), rest are builder dex objects.
# Offset formula matches SDK: skip index 0, then 110000 + i * 10000
self._perp_dexs = raw
idx = 0
for entry in raw:
if entry is None:
continue
name = entry if isinstance(entry, str) else entry.get("name", "")
if name:
self._dex_offsets[name] = 110000 + idx * 10000
idx += 1
if dex_name not in self._dex_offsets:
raise ValueError(
f"Unknown builder dex: {dex_name}. "
f"Available: {list(self._dex_offsets.keys())}"
)
# Fetch meta for this specific builder dex
meta = await self._info("meta", dex=dex_name)
self._builder_meta[dex_name] = meta
offset = self._dex_offsets[dex_name]
for i, asset in enumerate(meta.get("universe", [])):
asset_name = asset["name"]
# meta(dex="xyz") returns names already prefixed: "xyz:NVDA"
# Use the name as-is if it contains ':', otherwise prefix it
full_name = asset_name if ":" in asset_name else f"{dex_name}:{asset_name}"
self._name_to_index[full_name] = offset + i
self._sz_decimals[full_name] = asset.get("szDecimals", 0)
async def _resolve_asset(self, coin: str) -> int:
"""Resolve coin name to perp asset index.
Supports builder perps via 'dex:COIN' format (e.g. 'xyz:NVDA').
"""
# Try direct match first
idx = self._name_to_index.get(coin)
if idx is not None:
return idx
# Case-insensitive fallback (e.g. "ai16z" -> "AI16Z")
coin_upper = coin.upper()
for name, i in self._name_to_index.items():
if name.upper() == coin_upper:
return i
# If coin contains ':', try loading the builder dex
if ":" in coin:
dex_name = coin.split(":")[0]
await self._ensure_builder_dex(dex_name)
idx = self._name_to_index.get(coin)
if idx is not None:
return idx
raise ValueError(
f"Unknown perp asset: {coin}. "
f"Available: {list(self._name_to_index.keys())[:20]}..."
)
async def _resolve_any_asset(self, coin: str) -> int:
"""Resolve coin name to asset index — tries perps, builder perps, then spot."""
await self._ensure_meta()
try:
return await self._resolve_asset(coin)
except ValueError:
pass
# Try spot (exact then case-insensitive)
idx = self._spot_name_to_index.get(coin)
if idx is not None:
return 10000 + idx
coin_upper = coin.upper()
for name, i in self._spot_name_to_index.items():
if name.upper() == coin_upper:
return 10000 + i
raise ValueError(f"Unknown asset: {coin}")
def _resolve_spot_asset(self, coin: str) -> int:
"""Resolve coin name to spot asset index (10000 + idx)."""
idx = self._spot_name_to_index.get(coin)
if idx is None:
raise ValueError(
f"Unknown spot asset: {coin}. "
f"Available: {list(self._spot_name_to_index.keys())[:20]}..."
)
return 10000 + idx
def _format_size(self, coin: str, size: float) -> str:
"""Format size using float_to_wire for exact Hyperliquid normalization."""
return float_to_wire(size)
def _format_price(self, price: float, coin: str = "", is_spot: bool = False) -> str:
"""Format price matching the official SDK's rounding rules.
Prices can have up to 5 significant figures, but no more than
(MAX_DECIMALS - szDecimals) decimal places where MAX_DECIMALS is 6
for perps and 8 for spot. Integer prices are always allowed.
"""
# Step 1: round to 5 significant figures
rounded = float(f"{price:.5g}")
# Step 2: constrain decimal places based on szDecimals
sz_decimals = self._sz_decimals.get(coin, 0)
max_decimals = 8 if is_spot else 6
max_dp = max_decimals - sz_decimals
if max_dp >= 0:
rounded = round(rounded, max_dp)
return float_to_wire(rounded)
async def _validate_order_margin(
self,
coin: str,
size: float,
price: float,
leverage: int = 1,
is_spot: bool = False,
) -> tuple[bool, str]:
"""Validate if account has sufficient margin for an order.
Returns: (is_valid, error_message)
"""
try:
# Spot orders don't use leverage/margin
if is_spot:
return (True, "")
# Calculate order notional value
order_value = size * price
# Check minimum order value ($10)
if order_value < 10:
return (
False,
f"Order value ${order_value:.2f} is below minimum $10. "
f"Increase size to at least {10 / price:.4f} {coin}",
)
# Calculate required margin (notional / leverage)
required_margin = order_value / max(leverage, 1)
# CRITICAL: Check abstraction mode FIRST to determine which account to query
# Unified account mode keeps funds in SPOT, not PERP
address = await self._get_address()
current_mode = "default"
try:
abstraction_state = await self.get_user_abstraction_state(address)
if isinstance(abstraction_state, str):
current_mode = abstraction_state
elif isinstance(abstraction_state, dict):
current_mode = abstraction_state.get("type", abstraction_state.get("state", "default"))
except Exception:
current_mode = "default"
# Get account state based on abstraction mode
if current_mode == "unifiedAccount":
# Unified account: funds are in SPOT (shared collateral)
spot_state = await self.get_spot_state(address)
# Find USDC balance in spot
usdc_balance = 0.0
for bal in spot_state.get("balances", []):
if bal.get("coin") == "USDC":
usdc_balance = float(bal.get("total", 0))
break
# Use SPOT balance as available margin
account_value = usdc_balance
total_margin_used = 0.0 # Unified account shares collateral
available_margin = account_value
logger.info(
f"Margin validation for {coin} (UNIFIED ACCOUNT): "
f"spot_usdc=${usdc_balance:.2f}, "
f"available=${available_margin:.2f}"
)
else:
# Default/disabled mode: check PERP account
state = await self.get_account_state(address)
margin_summary = state.get("marginSummary", {})
account_value = float(margin_summary.get("accountValue", 0))
total_margin_used = float(margin_summary.get("totalMarginUsed", 0))
available_margin = account_value - total_margin_used
logger.info(
f"Margin validation for {coin} (PERP ACCOUNT): "
f"accountValue=${account_value:.2f}, "
f"totalMarginUsed=${total_margin_used:.2f}, "
f"available=${available_margin:.2f}"
)
# Require a safety buffer (5%)
safe_available = available_margin * 0.95
if required_margin > safe_available:
error_msg = (
f"Insufficient margin for {coin} order. "
f"Required: ${required_margin:.2f}, "
f"Available: ${safe_available:.2f} "
f"(Account value: ${account_value:.2f}, Used: ${total_margin_used:.2f}). "
)
# Add mode-specific guidance
if current_mode == "unifiedAccount":
error_msg += (
f"\n\n⚠️ UNIFIED ACCOUNT MODE ACTIVE: Checked SPOT balance (${account_value:.2f}) where your collateral is. "
f"If you think you have more funds, use `hl_total_balance` tool to see the complete picture. "
f"DO NOT use `hl_account` or `hl_balances` alone - they only show partial balances!"
)
elif account_value == 0:
error_msg += (
"\n\n💡 NOTE: Showing $0 balance in PERP account."
" If you have funds in SPOT, enable unified"
" account mode to share collateral across"
" spot/perp, or manually transfer USDC to"
" perp using `hl_transfer_usd`."
)
if ":" in coin:
# Builder perp specific guidance
dex_name = coin.split(":")[0]
error_msg += (
f"\n\n🏗️ BUILDER PERP ({dex_name}): "
f"DEX abstraction auto-transfers funds from main account → {dex_name} dex when order is placed. "
f"Validation checks main account available margin (not {dex_name} dex balance)."
)
error_msg += (
f"\n\n✅ SOLUTIONS:\n"
f"1) Use `hl_total_balance` to check actual available funds\n"
f"2) Reduce size to {safe_available * leverage / price:.4f} {coin} or less\n"
f"3) Increase leverage (if below max for this asset)\n"
f"4) Deposit more USDC to your Hyperliquid account\n"
f"5) Close other positions to free up margin"
)
return (False, error_msg)
return (True, "")
except Exception as e:
logger.warning(f"Order validation failed: {e}")
# Don't block order on validation errors - let exchange validate
return (True, "")
# ── Info Methods (read-only, no auth) ────────────────────────────────
async def get_account_state(self, address: str, dex: Optional[str] = None) -> dict:
"""Get perp positions, margin, account value.
Args:
address: Wallet address
dex: Builder dex name (e.g. 'xyz') for HIP-3 perp positions.
None for default perp positions.
"""
if dex:
return await self._info("clearinghouseState", user=address, dex=dex)
return await self._info("clearinghouseState", user=address)
async def get_spot_state(self, address: str) -> dict:
"""Get spot token balances."""
return await self._info("spotClearinghouseState", user=address)
async def get_open_orders(self, address: str) -> list:
"""Get all open orders."""
return await self._info("openOrders", user=address)
async def get_all_mids(self, dex: Optional[str] = None) -> dict:
"""Get current mid prices for all assets.
Args:
dex: Builder dex name (e.g. 'xyz') for builder perp mid prices.
None for default perp/spot mid prices.
"""
if dex:
return await self._info("allMids", dex=dex)
return await self._info("allMids")
async def get_l2_book(self, coin: str) -> dict:
"""Get L2 orderbook snapshot."""
return await self._info("l2Book", coin=coin)
async def get_meta(self) -> dict:
"""Get perp universe metadata."""
await self._ensure_meta()
return self._meta
async def get_spot_meta(self) -> dict:
"""Get spot universe metadata."""
await self._ensure_meta()
return self._spot_meta
async def get_candles(
self, coin: str, interval: str, start: int, end: int
) -> list:
"""Get OHLCV candlestick data."""
return await self._info(
"candleSnapshot",
req={"coin": coin, "interval": interval, "startTime": start, "endTime": end},
)
async def get_user_fills(self, address: str) -> list:
"""Get recent trade fills."""
return await self._info("userFills", user=address)
async def get_funding_history(
self, coin: str, start: int
) -> list:
"""Get historical funding rates."""
return await self._info(
"fundingHistory", coin=coin, startTime=start
)
async def get_predicted_fundings(self) -> list:
"""Get predicted next funding rates for all assets."""
return await self._info("predictedFundings")
async def get_user_fees(self, address: str) -> dict:
"""Get user fee schedule."""
return await self._info("userFees", user=address)
async def get_user_abstraction_state(self, address: str) -> dict:
"""Query current abstraction state for a user.
Returns abstraction mode: "default", "unifiedAccount", "portfolioMargin", or "disabled"
"""
return await self._info("userAbstraction", user=address)
async def get_order_status(self, address: str, oid: int) -> dict:
"""Look up a single order by oid."""
return await self._info("orderStatus", user=address, oid=oid)
# ── Exchange Methods (require signing) ───────────────────────────────
async def place_order(
self,
coin: str,
is_buy: bool,
size: float,
price: Optional[float] = None,
order_type: str = "limit",
reduce_only: bool = False,
cloid: Optional[str] = None,
is_spot: bool = False,
trigger_px: Optional[float] = None,
tpsl: Optional[str] = None,
) -> dict:
"""
Place a perp or spot order.
Args:
coin: Asset name (e.g. "BTC", "ETH")
is_buy: True for buy, False for sell
size: Order size in base asset
price: Limit price. None = market order (IoC with slippage)
order_type: "limit" (GTC), "ioc", "alo" (post-only)
reduce_only: If True, only reduces position
cloid: Optional client order ID
is_spot: If True, use spot asset index
trigger_px: Trigger price for stop loss / take profit orders
tpsl: "tp" for take profit, "sl" for stop loss
"""
await self._ensure_meta()
# Auto-approve Starchild builder (one-time, idempotent)
# This ensures a small platform fee is collected on each fill
try:
await self.ensure_builder_approved()
except Exception as e:
logger.warning(f"place_order: builder approval check failed (continuing without builder): {e}")
# Builder perps (HIP-3) need DEX abstraction for collateral
# Enable BEFORE validation so we can check actual available margin
logger.info(f"place_order DEX check: coin={coin}, is_spot={is_spot}, has_colon={':' in coin}")
if not is_spot and ":" in coin:
logger.info(f"place_order: triggering DEX abstraction for builder perp {coin}")
await self.ensure_dex_abstraction()
else:
logger.info(f"place_order: skipping DEX abstraction (is_spot={is_spot}, coin={coin})")
asset_idx = (
self._resolve_spot_asset(coin)
if is_spot
else await self._resolve_asset(coin)
)
# Market order: fetch mid price and apply slippage
# IMPORTANT: Skip this for trigger orders - they use trigger_px, not current mid
if price is None and trigger_px is None:
# Regular market order (non-trigger)
# Builder perps use dex-specific allMids
if not is_spot and ":" in coin:
dex_name = coin.split(":")[0]
mids = await self.get_all_mids(dex=dex_name)
# allMids(dex="xyz") returns keys like "xyz:NVDA", use full coin name
mid_key = coin
else:
mids = await self.get_all_mids()
# Spot uses pair name in allMids (e.g. "PURR/USDC" or "@1")
if is_spot:
mid_key = self._spot_mid_key.get(coin, coin)
else:
mid_key = coin
mid_str = mids.get(mid_key)
if not mid_str:
raise ValueError(f"No mid price for {coin} (looked up '{mid_key}')")
mid = float(mid_str)
slippage = DEFAULT_SLIPPAGE
price = mid * (1 + slippage) if is_buy else mid * (1 - slippage)
order_type = "ioc" # Force IoC for market orders
# Pre-flight validation: check margin requirements
# CRITICAL: When unified account is active, funds are shared across spot/perp/builder-dexes
# Check SPOT balance instead of perp, since that's where the collateral actually is
if not is_spot and not reduce_only:
try:
address = await self._get_address()
# Check if unified account is active
try:
abstraction_state = await self.get_user_abstraction_state(address)
if isinstance(abstraction_state, str):
current_abstraction = abstraction_state
elif isinstance(abstraction_state, dict):
current_abstraction = abstraction_state.get("type", abstraction_state.get("state", "default"))
else:
current_abstraction = "default"
except Exception:
current_abstraction = "default"
# Get margin state - check SPOT if unified, otherwise check perp
if current_abstraction == "unifiedAccount":
# Unified account: check SPOT balance (where collateral actually is)
spot_state = await self.get_spot_state(address)
# Find USDC balance in spot
usdc_balance = 0.0
for bal in spot_state.get("balances", []):
if bal.get("coin") == "USDC":
usdc_balance = float(bal.get("total", 0))
break
# Create a synthetic margin summary from spot balance
state = {
"marginSummary": {
"accountValue": str(usdc_balance),
"totalMarginUsed": "0.0", # Unified account shares collateral
"totalNtlPos": "0.0",
"totalRawUsd": str(usdc_balance),
},
"assetPositions": [], # Will check metadata for leverage
}
logger.info(f"Unified account active: using SPOT balance ${usdc_balance:.2f} for margin validation")
else:
# Default mode: check perp clearinghouse
state = await self.get_account_state(address)
# Extract leverage from assetPositions or use default
leverage = 1
for pos in state.get("assetPositions", []):
position = pos.get("position", pos)
if position.get("coin") == coin:
lev_info = position.get("leverage", {})
leverage = lev_info.get("value", 1)
break
# If no position, check metadata for default/max leverage
if leverage == 1:
if ":" in coin:
dex_name = coin.split(":")[0]
meta = self._builder_meta.get(dex_name, {})
for asset in meta.get("universe", []):
if asset["name"] == coin or asset["name"] == coin.split(":", 1)[-1]:
# Use max leverage as estimate if no position exists
leverage = asset.get("maxLeverage", 1)
break
else:
if self._meta:
for asset in self._meta.get("universe", []):
if asset["name"] == coin:
leverage = asset.get("maxLeverage", 1)
break
# Validate margin
is_valid, error_msg = await self._validate_order_margin(
coin=coin,
size=size,
price=price,
leverage=leverage,
is_spot=is_spot,
)
if not is_valid:
raise ValueError(error_msg)
except ValueError:
# Re-raise validation errors
raise
except Exception as e:
# Don't block order on validation errors
logger.warning(f"Order validation error (non-blocking): {e}")
# Build order type spec
if trigger_px is not None:
# Trigger order - use float_to_wire directly (matches SDK)
# This ensures consistent serialization when price == trigger_px
formatted_trigger = float_to_wire(trigger_px)
formatted_price = float_to_wire(price)
is_market_trigger = (price == trigger_px) if price is not None else True
# CRITICAL: Field order must match SDK exactly for msgpack hash consistency
# SDK uses: isMarket, triggerPx, tpsl (not triggerPx first!)
trigger_spec = {
"isMarket": is_market_trigger,
"triggerPx": formatted_trigger,
"tpsl": tpsl or "tp",
}
tif_spec = {"trigger": trigger_spec}
elif order_type == "limit":
# Regular orders - keep existing validation
formatted_price = self._format_price(price, coin=coin, is_spot=is_spot)
tif_spec = {"limit": {"tif": "Gtc"}}
elif order_type == "ioc":
formatted_price = self._format_price(price, coin=coin, is_spot=is_spot)
tif_spec = {"limit": {"tif": "Ioc"}}
elif order_type == "alo":
formatted_price = self._format_price(price, coin=coin, is_spot=is_spot)
tif_spec = {"limit": {"tif": "Alo"}}
else:
formatted_price = self._format_price(price, coin=coin, is_spot=is_spot)
tif_spec = {"limit": {"tif": "Gtc"}}
order = {
"a": asset_idx,
"b": is_buy,
"p": formatted_price,
"s": self._format_size(coin, size),
"r": reduce_only,
"t": tif_spec,
}
if cloid:
order["c"] = cloid
action = {
"type": "order",
"orders": [order],
"grouping": "na",
}
# Inject Starchild builder fee parameter at action level
# "b": builder address (MUST be lowercase — SDK lowercases it before hashing,
# and msgpack serializes strings by exact bytes, so case mismatch changes
# the action hash and causes signature verification failure on the server)
# "f": fee in tenths of basis points (20 = 2 bps)
action["builder"] = {"b": BUILDER_ADDRESS.lower(), "f": BUILDER_FEE_TENTHS_OF_BPS}
logger.info(
f"place_order: coin={coin}, is_buy={is_buy}, size={size}, "
f"price={formatted_price}, order_type={order_type}, "
f"asset_idx={asset_idx}"
)
# DEBUG: Log the full action structure for trigger orders
if trigger_px is not None:
import json
logger.info(f"TRIGGER ORDER ACTION: {json.dumps(action, indent=2)}")
result = await self._exchange(action)
logger.info(f"place_order result: {result}")
return result
async def cancel_order(self, coin: str, oid: int) -> dict:
"""Cancel an order by oid."""
await self._ensure_meta()
asset_idx = await self._resolve_any_asset(coin)
action = {
"type": "cancel",
"cancels": [{"a": asset_idx, "o": oid}],
}
return await self._exchange(action)
async def cancel_by_cloid(self, coin: str, cloid: str) -> dict:
"""Cancel an order by client order ID."""
await self._ensure_meta()
asset_idx = await self._resolve_any_asset(coin)
action = {
"type": "cancelByCloid",
"cancels": [{"asset": asset_idx, "cloid": cloid}],
}
return await self._exchange(action)
async def cancel_all(self, coin: Optional[str] = None) -> list:
"""
Cancel all open orders, optionally filtered by coin.
Returns list of cancel results.
"""
# No batch cancel action in HL — cancel individually
address = await self._get_address()
orders = await self.get_open_orders(address)
if coin:
orders = [o for o in orders if o.get("coin") == coin]
results = []
for order in orders:
try:
r = await self.cancel_order(
order["coin"], order["oid"]
)
results.append(r)
except Exception as e:
results.append({"error": str(e), "oid": order.get("oid")})
return results
async def modify_order(
self,
oid: int,
coin: str,
is_buy: bool,
size: float,
price: float,
order_type: str = "limit",
) -> dict:
"""Modify an existing order."""
await self._ensure_meta()
asset_idx = await self._resolve_any_asset(coin)
if order_type == "limit":
tif_spec = {"limit": {"tif": "Gtc"}}
elif order_type == "ioc":
tif_spec = {"limit": {"tif": "Ioc"}}
elif order_type == "alo":
tif_spec = {"limit": {"tif": "Alo"}}
else:
tif_spec = {"limit": {"tif": "Gtc"}}
action = {
"type": "modify",
"oid": oid,
"order": {
"a": asset_idx,
"b": is_buy,
"p": self._format_price(price, coin=coin),
"s": self._format_size(coin, size),
"r": False,
"t": tif_spec,
},
}
return await self._exchange(action)
# ── DEX Abstraction (HIP-3 builder perps collateral) ─────────────────
_dex_abstraction_enabled: bool = False
async def ensure_dex_abstraction(self) -> dict:
"""Enable DEX abstraction so collateral auto-transfers to builder dexes.
Required for trading HIP-3 builder perps (xyz:NVDA, xyz:TSLA, etc.).
Without this, the wallet has no collateral in builder dex clearinghouses
and all orders fail with "Insufficient margin".
Checks current abstraction state first, then tries multiple methods:
1. agentSetAbstraction("u") - modern agent-signed approach
2. agentEnableDexAbstraction - legacy agent-signed approach
3. userSetAbstraction("unifiedAccount") - user-signed fallback
Safe to call multiple times — Hyperliquid handles idempotency.
"""
address = await self._get_address()
# ALWAYS check current state first - don't trust cache
# The cache might be stale if the state was changed externally or if enable failed
try:
state_result = await self.get_user_abstraction_state(address)
# API may return string ("default") or dict ({"type": "default"})
if isinstance(state_result, str):
current_state = state_result
elif isinstance(state_result, dict):
current_state = state_result.get("type", state_result.get("state", "unknown"))
else:
current_state = "unknown"
logger.info(f"DEX abstraction: current state for {address} = {current_state}")
# If already in unifiedAccount mode, we're done
if current_state == "unifiedAccount":
logger.info("DEX abstraction: already enabled (unifiedAccount mode)")
self._dex_abstraction_enabled = True
return {"status": "already_enabled", "state": current_state}
# If cache says enabled but state check shows otherwise, reset cache
if self._dex_abstraction_enabled and current_state != "unifiedAccount":
logger.warning(
f"DEX abstraction: cache says enabled but state is '{current_state}'. "
f"Resetting cache and retrying enable."
)
self._dex_abstraction_enabled = False
# SDK comment says: "the account must be in 'default' mode to succeed"
if current_state not in ("default", "disabled"):
logger.warning(
f"DEX abstraction: account in {current_state} mode. "
f"Transitions may fail if not in 'default' mode."
)
except Exception as e:
logger.warning(f"DEX abstraction: failed to query current state: {e}")
# Continue anyway, state check is informational
# Try Method 1: agentSetAbstraction with "u" (unified account)
logger.info(f"DEX abstraction: trying agentSetAbstraction(u) for {address}")
action = {
"type": "agentSetAbstraction",
"abstraction": "u", # "u" = unified account (DEX abstraction enabled)
}
try:
result = await self._exchange(action, vault_address=None)
logger.info(f"DEX abstraction: agentSetAbstraction result = {result}")
self._dex_abstraction_enabled = True
return result
except Exception as e:
err_str = str(e).lower()
logger.warning(f"DEX abstraction: agentSetAbstraction failed: {e}")
# If it says "already" or "enabled", that's success
if "already" in err_str or "enabled" in err_str:
self._dex_abstraction_enabled = True
return {"status": "ok", "detail": str(e)}
# Try Method 2: agentEnableDexAbstraction (legacy)
logger.info(f"DEX abstraction: trying agentEnableDexAbstraction for {address}")
action = {
"type": "agentEnableDexAbstraction",
}
try:
result = await self._exchange(action, vault_address=None)
logger.info(f"DEX abstraction: agentEnableDexAbstraction result = {result}")
self._dex_abstraction_enabled = True
return result
except Exception as e:
err_str = str(e).lower()
logger.warning(f"DEX abstraction: agentEnableDexAbstraction failed: {e}")
if "already" in err_str or "enabled" in err_str:
self._dex_abstraction_enabled = True
return {"status": "ok", "detail": str(e)}
# Try Method 3: userSetAbstraction (user-signed, not agent-signed)
# This uses a different signing domain (HyperliquidSignTransaction vs Agent)
# SDK example shows this works when account is in "default" mode
logger.info(f"DEX abstraction: trying userSetAbstraction(unifiedAccount) for {address}")
try:
result = await self._user_set_abstraction(address, "unifiedAccount")
logger.info(f"DEX abstraction: userSetAbstraction result = {result}")
# Verify the state actually changed
try:
new_state_result = await self.get_user_abstraction_state(address)
if isinstance(new_state_result, str):
new_state = new_state_result
elif isinstance(new_state_result, dict):
new_state = new_state_result.get("type", new_state_result.get("state", "unknown"))
else:
new_state = "unknown"
logger.info(f"DEX abstraction: state AFTER userSetAbstraction = {new_state}")
if new_state == "unifiedAccount":
logger.info("DEX abstraction: successfully enabled (verified)")
self._dex_abstraction_enabled = True
return result
else:
logger.warning(
f"DEX abstraction: userSetAbstraction returned success but state is still '{new_state}', not 'unifiedAccount'. "
f"This may indicate the account has restrictions. Full result: {result}"
)
except Exception as verify_err:
logger.warning(f"DEX abstraction: failed to verify state after userSetAbstraction: {verify_err}")
self._dex_abstraction_enabled = True
return result
except Exception as e:
err_str = str(e).lower()
logger.error(f"DEX abstraction: userSetAbstraction failed: {e}")
if "already" in err_str or "enabled" in err_str:
self._dex_abstraction_enabled = True
return {"status": "ok", "detail": str(e)}
# All methods failed
raise RuntimeError(
f"Failed to enable DEX abstraction for {address}. "
f"Your account may have DEX abstraction manually disabled. "
f"Please enable it at app.hyperliquid.xyz:\n"
f"1. Go to Settings (top right)\n"
f"2. Find 'Disable HIP-3 Dex Abstraction' checkbox\n"
f"3. UNCHECK it to enable DEX abstraction\n"
f"4. Then retry your order"
)
async def _user_set_abstraction(self, user: str, abstraction: str) -> dict:
"""Set abstraction mode for user (user-signed action).
Matches SDK's user_set_abstraction exactly.
Args:
user: User wallet address
abstraction: "unifiedAccount", "portfolioMargin", or "disabled"
Returns: API response
"""
nonce = int(time.time() * 1000)
# Action payload must include signatureChainId and hyperliquidChain
# These are required for all user-signed actions
action = {
"type": "userSetAbstraction",
"user": user.lower(),
"abstraction": abstraction,
"nonce": nonce,
"signatureChainId": "0xa4b1", # 42161 in hex (Arbitrum mainnet)
"hyperliquidChain": "Mainnet",
}
signature = await sign_user_set_abstraction(
user=user,
abstraction=abstraction,
nonce=nonce,
)
payload = {
"action": action,
"nonce": nonce,
"signature": signature,
}
return await self._post("/exchange", payload)
# ── Builder Code (platform fee collection) ───────────────────────────
async def approve_builder_fee(
self,
builder: str = BUILDER_ADDRESS,
max_fee_rate: str = BUILDER_MAX_FEE_RATE,
) -> dict:
"""Approve a builder to charge fees on the user's fills (one-time).
This is a user-signed action that must come from the main wallet.
Once approved, all subsequent orders will include the builder parameter
automatically, directing a small fee to the builder address.
Args:
builder: Builder address to approve (default: Starchild builder)
max_fee_rate: Max fee rate as percentage string (default: "0.02%" = 2 bps)
Returns: API response from /exchange
"""
nonce = int(time.time() * 1000)
action = {
"type": "approveBuilderFee",
"maxFeeRate": max_fee_rate,
"builder": builder.lower(),
"nonce": nonce,
"signatureChainId": "0xa4b1", # Arbitrum mainnet (42161)
"hyperliquidChain": "Mainnet",
}
signature = await sign_approve_builder_fee(
max_fee_rate=max_fee_rate,
builder=builder,
nonce=nonce,
)
payload = {
"action": action,
"nonce": nonce,
"signature": signature,
}
return await self._post("/exchange", payload)
async def get_max_builder_fee(self, user: str, builder: str = BUILDER_ADDRESS) -> Any:
"""Query the max builder fee a user has approved for a builder.
Returns the approved max fee rate, or None/0 if not approved.
Args:
user: User wallet address
builder: Builder address (default: Starchild builder)
"""
return await self._info(
"maxBuilderFee",
user=user.lower(),
builder=builder.lower(),
)
async def get_referral_info(self, address: str) -> Any:
"""Get referral and builder reward info for a user.
Includes unclaimed rewards, builder rewards, and referrer state.
Args:
address: User wallet address
"""
return await self._info("referral", user=address.lower())
async def ensure_builder_approved(self) -> dict:
"""Check if Starchild builder is approved; if not, auto-approve.
Called automatically before placing orders. If the user has not yet
approved the Starchild builder, this will submit the ApproveBuilderFee
action. If already approved, returns silently.
Returns: {"approved": bool, "maxFeeRate": str | None}
"""
address = await self._get_address()
try:
result = await self.get_max_builder_fee(address, BUILDER_ADDRESS)
# Result is the max fee rate string (e.g. "0.02%") or null
if result and result != "0" and result != 0:
logger.info(f"Builder already approved: maxFeeRate={result}")
return {"approved": True, "maxFeeRate": str(result)}
except Exception as e:
logger.warning(f"Failed to check builder approval: {e}")
# Not approved — submit approval
logger.info(f"Auto-approving Starchild builder {BUILDER_ADDRESS} with maxFeeRate={BUILDER_MAX_FEE_RATE}")
result = await self.approve_builder_fee()
logger.info(f"Builder approval result: {result}")
return {"approved": True, "maxFeeRate": BUILDER_MAX_FEE_RATE, "approval_result": result}
async def update_leverage(
self, coin: str, leverage: int, is_cross: bool = True
) -> dict:
"""Set leverage for a perp."""
await self._ensure_meta()
# Builder perps need DEX abstraction
logger.info(f"update_leverage DEX check: coin={coin}, has_colon={':' in coin}")
if ":" in coin:
logger.info(f"update_leverage: triggering DEX abstraction for builder perp {coin}")
await self.ensure_dex_abstraction()
else:
logger.info(f"update_leverage: skipping DEX abstraction for {coin}")
asset_idx = await self._resolve_asset(coin)
action = {
"type": "updateLeverage",
"asset": asset_idx,
"isCross": is_cross,
"leverage": leverage,
}
return await self._exchange(action)
async def market_open(
self,
coin: str,
is_buy: bool,
size: float,
slippage: float = DEFAULT_SLIPPAGE,
is_spot: bool = False,
) -> dict:
"""Convenience: open a position with an IoC market order."""
return await self.place_order(
coin=coin,
is_buy=is_buy,
size=size,
price=None, # triggers market order logic
order_type="ioc",
is_spot=is_spot,
)
async def market_close(
self, coin: str, address: str, slippage: float = DEFAULT_SLIPPAGE
) -> dict:
"""Close entire perp position for a coin."""
# Builder perps (HIP-3) have separate clearinghouse state per dex
if ":" in coin:
dex_name = coin.split(":")[0]
state = await self._info("clearinghouseState", user=address, dex=dex_name)
else:
state = await self.get_account_state(address)
positions = state.get("assetPositions", [])
pos = None
for p in positions:
position = p.get("position", p)
if position.get("coin") == coin:
pos = position
break
if not pos:
raise ValueError(f"No open position for {coin}")
size = abs(float(pos["szi"]))
is_buy = float(pos["szi"]) < 0 # Close short = buy, close long = sell
return await self.place_order(
coin=coin,
is_buy=is_buy,
size=size,
price=None,
order_type="ioc",
reduce_only=True,
)
async def transfer_usd(
self, amount: float, to_perp: bool = True
) -> dict:
"""
Transfer USDC between spot and perp.
Uses user-signed action (HyperliquidSignTransaction domain).
"""
address = await self._get_address()
# Query balances BEFORE transfer for verification
try:
perp_state_before = await self.get_account_state(address)
spot_state_before = await self.get_spot_state(address)
perp_value_before = float(perp_state_before.get("marginSummary", {}).get("accountValue", 0))
spot_balances_before = spot_state_before.get("balances", [])
logger.info(
f"transfer_usd: BEFORE transfer - "
f"perp_value=${perp_value_before:.2f}, "
f"spot_balances={spot_balances_before}"
)
except Exception as e:
logger.warning(f"transfer_usd: failed to query balances before transfer: {e}")
nonce = int(time.time() * 1000)
action = {
"type": "usdClassTransfer",
"amount": str(amount),
"toPerp": to_perp,
"nonce": nonce,
"signatureChainId": "0xa4b1", # 42161 in hex (Arbitrum mainnet)
"hyperliquidChain": "Mainnet",
}
types = {
"HyperliquidTransaction:UsdClassTransfer": [
{"name": "hyperliquidChain", "type": "string"},
{"name": "amount", "type": "string"},
{"name": "toPerp", "type": "bool"},
{"name": "nonce", "type": "uint64"},
]
}
signature = await sign_user_action(
action={
"hyperliquidChain": "Mainnet",
"amount": str(amount),
"toPerp": to_perp,
"nonce": nonce,
},
types=types,
primary_type="HyperliquidTransaction:UsdClassTransfer",
)
payload = {
"action": action,
"nonce": nonce,
"signature": signature,
}
logger.info(f"transfer_usd: submitting ${amount} transfer ({'spot→perp' if to_perp else 'perp→spot'})")
try:
result = await self._post("/exchange", payload)
logger.info(f"transfer_usd: API response SUCCESS = {result}")
except Exception as api_error:
logger.error(f"transfer_usd: API call FAILED: {api_error}", exc_info=True)
# Re-raise so caller sees the error
raise
# Query balances AFTER transfer for verification
try:
perp_state_after = await self.get_account_state(address)
spot_state_after = await self.get_spot_state(address)
perp_value_after = float(perp_state_after.get("marginSummary", {}).get("accountValue", 0))
spot_balances_after = spot_state_after.get("balances", [])
logger.info(
f"transfer_usd: AFTER transfer - "
f"perp_value=${perp_value_after:.2f}, "
f"spot_balances={spot_balances_after}"
)
except Exception as e:
logger.warning(f"transfer_usd: failed to query balances after transfer: {e}")
return result
async def withdraw_from_bridge(
self, amount: float, destination: Optional[str] = None
) -> dict:
"""
Withdraw USDC from Hyperliquid to an Arbitrum wallet (L1 bridge withdrawal).
Fee: 1 USDC (deducted by Hyperliquid). Processing: ~5 minutes.
Args:
amount: USDC amount to withdraw
destination: Target wallet address (defaults to agent's own wallet)
"""
if not destination:
destination = await self._get_address()
nonce = int(time.time() * 1000)
action = {
"type": "withdraw3",
"hyperliquidChain": "Mainnet",
"signatureChainId": "0xa4b1", # 42161 in hex (Arbitrum mainnet)
"destination": destination,
"amount": str(amount),
"time": nonce,
}
types = {
"HyperliquidTransaction:Withdraw": [
{"name": "hyperliquidChain", "type": "string"},
{"name": "destination", "type": "string"},
{"name": "amount", "type": "string"},
{"name": "time", "type": "uint64"},
]
}
signature = await sign_user_action(
action={
"hyperliquidChain": "Mainnet",
"destination": destination,
"amount": str(amount),
"time": nonce,
},
types=types,
primary_type="HyperliquidTransaction:Withdraw",
)
payload = {
"action": action,
"nonce": nonce,
"signature": signature,
}
return await self._post("/exchange", payload)
async def deposit_usdc(self, amount: float) -> dict:
"""
Deposit USDC from agent's Arbitrum wallet into Hyperliquid.
Sends an ERC-20 transfer of USDC to the Hyperliquid bridge contract.
Minimum deposit: 5 USDC.
Args:
amount: USDC amount to deposit (minimum 5)
"""
from eth_utils import keccak
from core.wallet_runtime import wallet_request as _wallet_request, is_fly_machine as _is_fly_machine
if not _is_fly_machine():
raise RuntimeError("Not running on a Fly Machine — wallet unavailable")
if amount < MIN_DEPOSIT_USDC:
raise ValueError(f"Minimum deposit is {MIN_DEPOSIT_USDC} USDC")
amount_base = int(amount * (10 ** USDC_DECIMALS))
# Step 1: ERC-20 approve(bridge, amount)
approve_selector = keccak(b"approve(address,uint256)")[:4]
bridge_bytes = bytes.fromhex(BRIDGE_ADDRESS.replace("0x", "")).rjust(32, b"\x00")
amount_bytes = amount_base.to_bytes(32, "big")
approve_data = "0x" + (approve_selector + bridge_bytes + amount_bytes).hex()
logger.info(f"HL deposit: approve TX (amount_base={amount_base})")
approve_result = await _wallet_request("POST", "/agent/transfer", {
"to": USDC_ADDRESS,
"amount": "0",
"data": approve_data,
"chain_id": ARBITRUM_CHAIN_ID,
})
approve_tx = approve_result.get("tx_hash", approve_result.get("hash", "unknown"))
logger.info(f"HL deposit: approve TX = {approve_tx}")
# Step 2: ERC-20 transfer(bridge, amount)
transfer_selector = keccak(b"transfer(address,uint256)")[:4]
transfer_data = "0x" + (transfer_selector + bridge_bytes + amount_bytes).hex()
logger.info(f"HL deposit: transfer TX to bridge {BRIDGE_ADDRESS}")
transfer_result = await _wallet_request("POST", "/agent/transfer", {
"to": USDC_ADDRESS,
"amount": "0",
"data": transfer_data,
"chain_id": ARBITRUM_CHAIN_ID,
})
transfer_tx = transfer_result.get("tx_hash", transfer_result.get("hash", "unknown"))
logger.info(f"HL deposit: transfer TX = {transfer_tx}")
return {
"approve_tx_hash": approve_tx,
"transfer_tx_hash": transfer_tx,
"amount_deposited": amount,
"amount_base_units": amount_base,
"bridge_contract": BRIDGE_ADDRESS,
"chain_id": ARBITRUM_CHAIN_ID,
}
# ── Address helper ───────────────────────────────────────────────────
_cached_address: Optional[str] = None
async def _get_address(self) -> str:
"""Get the agent's EVM address from wallet service (cached)."""
if self._cached_address:
return self._cached_address
from core.wallet_runtime import wallet_request as _wallet_request, is_fly_machine as _is_fly_machine
if not _is_fly_machine():
raise RuntimeError("Not running on Fly — wallet unavailable")
data = await _wallet_request("GET", "/agent/wallet")
wallets = data if isinstance(data, list) else data.get("wallets", [])
for w in wallets:
if w.get("chain_type") == "ethereum":
self._cached_address = w["wallet_address"]
return self._cached_address
raise RuntimeError("No ethereum wallet found")
exports.py
"""
Hyperliquid skill exports — read-only tools, sync via requests.
Bypasses the async client entirely. Uses direct POST to /info endpoint.
ADDRESS HANDLING (v1.8.0): every user-scoped function takes an optional
`address` argument. Omit it to query the agent's own wallet (resolved via
Fly OIDC -> wallet-service, cached); pass any 0x address to inspect a third
party. Before v1.8.0 these were hard-bound to the agent's own wallet, so
"analyse this wallet's Hyperliquid PnL" was impossible to answer.
Write operations (hl_order, hl_cancel, etc.) are NOT exported — they require
the agent's signing pipeline. Use HyperliquidClient for those.
Usage in task scripts:
from core.skill_tools import hyperliquid
account = hyperliquid.hl_account() # agent's own
other = hyperliquid.hl_account(address="0x1f16...") # someone else's
pnl = hyperliquid.hl_portfolio(address="0x1f16...") # PnL time series
mids = hyperliquid.hl_market()
candles = hyperliquid.hl_candles(coin="BTC", interval="1h", hours_back=24)
"""
import os
import json
import time
import http.client
import socket
import requests
HL_API = os.environ.get("HYPERLIQUID_API_URL", "https://api.hyperliquid.xyz")
FLY_API_SOCKET = "/.fly/api"
WALLET_SERVICE_URL = os.environ.get("WALLET_SERVICE_URL", "https://wallet-service-dev.fly.dev")
OIDC_AUDIENCE = os.environ.get("WALLET_OIDC_AUDIENCE", WALLET_SERVICE_URL)
_cached_address = None
def _get_oidc_token():
"""Get OIDC token from Fly unix socket."""
conn = http.client.HTTPConnection("localhost")
conn.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
conn.sock.connect(FLY_API_SOCKET)
body = json.dumps({"aud": OIDC_AUDIENCE}).encode()
conn.request("POST", "/v1/tokens/oidc", body=body,
headers={"Host": "localhost", "Content-Type": "application/json"})
resp = conn.getresponse()
token = resp.read().decode().strip()
conn.close()
return token
def _get_address():
"""Get agent's own EVM wallet address (cached)."""
global _cached_address
if _cached_address:
return _cached_address
if not os.path.exists(FLY_API_SOCKET):
raise RuntimeError("Not on Fly machine — wallet unavailable")
token = _get_oidc_token()
r = requests.get(f"{WALLET_SERVICE_URL}/agent/wallet",
headers={"Authorization": f"Bearer {token}"}, timeout=15)
r.raise_for_status()
data = r.json()
for w in (data if isinstance(data, list) else data.get("wallets", [])):
if w.get("chain_type") == "ethereum":
_cached_address = w["wallet_address"]
return _cached_address
raise RuntimeError("No ethereum wallet found")
def _addr(address=None):
"""Resolve a target address: explicit arg wins, else the agent's own wallet.
Validates shape early — an unchecked bad address makes Hyperliquid return
an empty result rather than an error, which reads as "no positions" and
is worse than a clear failure.
"""
if address is None:
return _get_address()
a = str(address).strip()
if not (a.startswith("0x") and len(a) == 42):
raise ValueError(f"Invalid EVM address: {address!r} (expected 0x + 40 hex chars)")
return a
def _info(req_type, **kwargs):
"""POST to Hyperliquid /info endpoint."""
payload = {"type": req_type, **kwargs}
r = requests.post(f"{HL_API}/info", json=payload, timeout=15)
r.raise_for_status()
data = r.json()
if isinstance(data, dict) and data.get("status") == "err":
raise Exception(f"Hyperliquid error: {data.get('response', data)}")
return data
def _ms_ago(hours=None, days=None):
"""Epoch-ms timestamp for N hours/days back from now."""
secs = 0
if hours:
secs += hours * 3600
if days:
secs += days * 86400
return int((time.time() - secs) * 1000)
# ── Account state ────────────────────────────────────────────────────────
def hl_account(address=None, dex=None):
"""Perp account state: positions, margin, unrealized PnL.
Args:
address: wallet to inspect (default: the agent's own)
dex: HIP-3 builder dex name (default: the first perp dex)
Unrealized PnL per position is in assetPositions[].position.unrealizedPnl.
For realized PnL use hl_fills (closedPnl) or hl_portfolio (time series).
"""
kw = {"user": _addr(address)}
if dex:
kw["dex"] = dex
return _info("clearinghouseState", **kw)
def hl_balances(address=None):
"""Spot token balances."""
return _info("spotClearinghouseState", user=_addr(address))
def hl_total_balance(address=None):
"""Total available balance across spot + perp, aware of abstraction mode.
Use this for "how much can I trade with" checks — hl_account shows perp
only (often $0 under unified account) and hl_balances shows spot only.
Returns dict:
totalAvailable: USDC available for trading (rounded 2dp)
abstractionMode: "unifiedAccount" | "disabled" | "default" | ...
note: human-readable explanation of how the total was derived
breakdown: {spot:{usdc}, perp:{accountValue, marginUsed, available}}
"""
addr = _addr(address)
# Abstraction mode — tolerate string or dict shapes, default on any error.
try:
abstraction_result = _info("userAbstraction", user=addr)
if isinstance(abstraction_result, str):
abstraction_mode = abstraction_result
elif isinstance(abstraction_result, dict):
abstraction_mode = abstraction_result.get(
"type", abstraction_result.get("state", "default")
)
else:
abstraction_mode = "default"
except Exception:
abstraction_mode = "default"
spot_state = _info("spotClearinghouseState", user=addr)
perp_state = _info("clearinghouseState", user=addr)
spot_usdc = 0.0
for bal in spot_state.get("balances", []):
if bal.get("coin") == "USDC":
spot_usdc = float(bal.get("total", 0))
break
perp_margin = perp_state.get("marginSummary", {})
perp_value = float(perp_margin.get("accountValue", 0))
perp_used = float(perp_margin.get("totalMarginUsed", 0))
perp_available = perp_value - perp_used
if abstraction_mode == "unifiedAccount":
total_available = spot_usdc + perp_available
note = "Unified account: funds are shared across spot/perp/builder-dexes"
else:
total_available = perp_available
note = "Disabled mode: perp and spot are separate"
return {
"totalAvailable": round(total_available, 2),
"abstractionMode": abstraction_mode,
"note": note,
"breakdown": {
"spot": {"usdc": round(spot_usdc, 2)},
"perp": {
"accountValue": round(perp_value, 2),
"marginUsed": round(perp_used, 2),
"available": round(perp_available, 2),
},
},
}
def hl_user_role(address=None):
"""Account role: "user", "agent", "vault", "subAccount", "missing".
"missing" means the address has never traded on Hyperliquid — check this
before reporting "no positions", which otherwise looks identical.
"""
return _info("userRole", user=_addr(address))
def hl_user_fees(address=None):
"""Fee schedule and 14-day volume."""
return _info("userFees", user=_addr(address))
def hl_rate_limit(address=None):
"""Request rate-limit state: cumVlm, nRequestsUsed, nRequestsCap."""
return _info("userRateLimit", user=_addr(address))
def hl_sub_accounts(address=None):
"""Sub-accounts owned by this address (None if it has none)."""
return _info("subAccounts", user=_addr(address))
def hl_referral(address=None):
"""Referral state: referrer, code, cumVlm, builder/claimed rewards."""
return _info("referral", user=_addr(address))
def hl_extra_agents(address=None):
"""Approved API agent wallets and their expiry."""
return _info("extraAgents", user=_addr(address))
# ── PnL and history ──────────────────────────────────────────────────────
def hl_portfolio(address=None):
"""PnL and account-value time series — the direct answer to "what is this
wallet's PnL over time".
Returns a list of [period, data] pairs covering 8 windows:
day, week, month, allTime, perpDay, perpWeek, perpMonth, perpAllTime
Each data dict holds:
accountValueHistory: [[epoch_ms, "value_usd"], ...]
pnlHistory: [[epoch_ms, "pnl_usd"], ...]
vlm: traded volume for the window
The bare "day"/"week"/... keys cover the whole account; the "perp*" keys
are perps only. Note pnlHistory restarts at 0 at the start of each window,
so allTime is the one to read for lifetime PnL.
"""
return _info("portfolio", user=_addr(address))
def hl_fills(address=None):
"""Most recent trade fills (capped at 2000, newest last).
Each fill carries closedPnl — realized PnL for that fill. For a bounded
window or to page beyond 2000 fills, use hl_fills_by_time.
"""
return _info("userFills", user=_addr(address))
def hl_fills_by_time(address=None, days_back=30, start=None, end=None,
aggregate_by_time=False):
"""Trade fills within a time range (max 2000 per call).
Args:
address: wallet to inspect (default: the agent's own)
days_back: lookback window in days (default 30)
start/end: explicit epoch-ms timestamps (override days_back)
aggregate_by_time: merge partial fills of the same order
To walk a long history, page forward: pass the last fill's `time` as the
next `start` until fewer than 2000 fills come back.
"""
if start is None:
start = _ms_ago(days=days_back)
kw = {"user": _addr(address), "startTime": int(start)}
if end is not None:
kw["endTime"] = int(end)
if aggregate_by_time:
kw["aggregateByTime"] = True
return _info("userFillsByTime", **kw)
def hl_historical_orders(address=None):
"""Recent order history including cancelled and rejected orders.
hl_open_orders shows only what is live now; this shows what happened.
"""
return _info("historicalOrders", user=_addr(address))
def hl_ledger(address=None, days_back=30, start=None, end=None):
"""Non-funding ledger updates: deposits, withdrawals, transfers, liquidations.
This is the money-in/money-out record. Cost basis for an all-time PnL
calculation comes from here — trade fills alone cannot tell you how much
capital entered the account.
"""
if start is None:
start = _ms_ago(days=days_back)
kw = {"user": _addr(address), "startTime": int(start)}
if end is not None:
kw["endTime"] = int(end)
return _info("userNonFundingLedgerUpdates", **kw)
def hl_funding_payments(address=None, days_back=30, start=None, end=None):
"""Funding payments this wallet paid or received (max 500 per call).
Distinct from hl_funding, which is an asset's market-wide funding rate.
"""
if start is None:
start = _ms_ago(days=days_back)
kw = {"user": _addr(address), "startTime": int(start)}
if end is not None:
kw["endTime"] = int(end)
return _info("userFunding", **kw)
def hl_twap_fills(address=None):
"""Fills from TWAP orders (kept separate from ordinary fills)."""
return _info("userTwapSliceFills", user=_addr(address))
def hl_vault_equities(address=None):
"""Vault deposits held by this address."""
return _info("userVaultEquities", user=_addr(address))
# ── Orders ───────────────────────────────────────────────────────────────
def hl_open_orders(address=None):
"""Currently open orders (basic form)."""
return _info("openOrders", user=_addr(address))
def hl_open_orders_full(address=None):
"""Open orders with trigger/TP-SL detail.
Includes triggerCondition, isTrigger, triggerPx, isPositionTpsl and
orderType — none of which hl_open_orders returns. Use this when stop
losses or take profits matter.
"""
return _info("frontendOpenOrders", user=_addr(address))
def hl_order_status(oid, address=None):
"""Look up a single order by oid (or cloid string)."""
return _info("orderStatus", user=_addr(address), oid=oid)
# ── Market data ──────────────────────────────────────────────────────────
def hl_market(dex=None):
"""Current mid prices for all assets."""
if dex:
return _info("allMids", dex=dex)
return _info("allMids")
def hl_orderbook(coin):
"""L2 orderbook snapshot for a coin."""
return _info("l2Book", coin=coin)
def hl_candles(coin, interval="1h", hours_back=24, start=None, end=None):
"""OHLCV candlestick data.
Args:
coin: e.g. "BTC", "ETH"
interval: "1m","5m","15m","1h","4h","1d"
hours_back: lookback period in hours (default 24)
start/end: explicit timestamps in ms (override hours_back)
"""
if end is None:
end = int(time.time() * 1000)
if start is None:
start = end - hours_back * 3600 * 1000
return _info("candleSnapshot", req={"coin": coin, "interval": interval,
"startTime": start, "endTime": end})
def hl_funding(coin, hours_back=24, start=None):
"""An asset's market-wide historical funding rates.
For what a specific wallet paid or received, use hl_funding_payments.
"""
if start is None:
start = _ms_ago(hours=hours_back)
return _info("fundingHistory", coin=coin, startTime=start)
def hl_predicted_funding():
"""Predicted next funding rates across venues for all assets."""
return _info("predictedFundings")
def hl_meta(dex=None):
"""Perp universe metadata: name, szDecimals, maxLeverage, margin tables.
szDecimals is required to size an order correctly — a size with more
decimals than the asset allows is rejected.
"""
if dex:
return _info("meta", dex=dex)
return _info("meta")
def hl_meta_ctxs(dex=None):
"""Perp metadata plus live context per asset.
Returns [meta, contexts] where each context has markPx, midPx, oraclePx,
funding, openInterest, dayNtlVlm, premium, impactPxs, prevDayPx. This is
the one call for a market-wide scan — hl_market gives only mid prices.
"""
if dex:
return _info("metaAndAssetCtxs", dex=dex)
return _info("metaAndAssetCtxs")
def hl_spot_meta():
"""Spot universe metadata: tokens, pairs, indices, EVM contracts."""
return _info("spotMeta")
def hl_spot_meta_ctxs():
"""Spot metadata plus live context (markPx, midPx, dayNtlVlm, prevDayPx)."""
return _info("spotMetaAndAssetCtxs")
def hl_perp_dexs():
"""All perp dexes, including HIP-3 builder-deployed ones.
Index 0 is null — that is the first/native perp dex. Named entries (e.g.
"xyz") carry their own universe; their assets appear as "dex:SYMBOL" and
need the dex argument on hl_account / hl_meta / hl_market.
"""
return _info("perpDexs")
# ── Staking ──────────────────────────────────────────────────────────────
def hl_staking(address=None):
"""Staking summary: delegated, undelegated, pending withdrawals."""
return _info("delegatorSummary", user=_addr(address))
def hl_staking_delegations(address=None):
"""Per-validator stake delegations."""
return _info("delegations", user=_addr(address))
def hl_staking_rewards(address=None):
"""Staking reward history."""
return _info("delegatorRewards", user=_addr(address))
signing.py
"""
Hyperliquid L1 Action Signing — phantom agent EIP-712 pattern.
Hyperliquid trading actions (orders, cancels, leverage, modify) require an EIP-712
"Agent" signature over a keccak256 hash of the msgpack-serialized action.
Since we don't have direct private key access (Privy server wallet), we delegate
EIP-712 signing to the wallet service's /agent/sign-typed-data endpoint.
Two signing schemes:
1. L1 Action (orders, cancels, leverage) — msgpack → keccak → Agent struct
2. User-Signed (USDC transfers, withdrawals) — direct EIP-712 over action fields
The connectionId field (bytes32) encoding must match what the Privy wallet service
expects. We try multiple encodings and verify each with local ecrecover.
"""
import logging
from typing import Optional
import msgpack
from eth_utils import keccak
from core.wallet_runtime import wallet_request as _wallet_request
logger = logging.getLogger(__name__)
# Hyperliquid chain constants
MAINNET_SOURCE = "a"
# EIP-712 domains
L1_DOMAIN = {
"name": "Exchange",
"version": "1",
"chainId": 1337,
"verifyingContract": "0x0000000000000000000000000000000000000000",
}
USER_SIGNED_DOMAIN = {
"name": "HyperliquidSignTransaction",
"version": "1",
"chainId": 42161, # Arbitrum mainnet
"verifyingContract": "0x0000000000000000000000000000000000000000",
}
# EIP-712 types for Agent struct
AGENT_TYPES = {
"Agent": [
{"name": "source", "type": "string"},
{"name": "connectionId", "type": "bytes32"},
]
}
# ── Wallet address cache ─────────────────────────────────────────────────
_cached_wallet_address: Optional[str] = None
async def _get_wallet_address() -> Optional[str]:
"""Get the Privy wallet address for signature verification (cached)."""
global _cached_wallet_address
if _cached_wallet_address:
return _cached_wallet_address
try:
from core.wallet_runtime import is_fly_machine as _is_fly_machine
if not _is_fly_machine():
return None
data = await _wallet_request("GET", "/agent/wallet")
wallets = data if isinstance(data, list) else data.get("wallets", [])
for w in wallets:
if w.get("chain_type") == "ethereum":
_cached_wallet_address = w["wallet_address"].lower()
return _cached_wallet_address
except Exception as e:
logger.debug(f"Could not fetch wallet address for verification: {e}")
return None
# ── EIP-712 hash computation (manual, no encode_typed_data dependency) ────
def _eip712_domain_separator(domain: dict) -> bytes:
"""Compute EIP-712 domain separator hash."""
type_hash = keccak(
b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
)
encoded = type_hash
encoded += keccak(domain["name"].encode())
encoded += keccak(domain["version"].encode())
encoded += domain["chainId"].to_bytes(32, "big")
addr = domain["verifyingContract"].replace("0x", "")
encoded += bytes.fromhex(addr).rjust(32, b"\x00")
return keccak(encoded)
def _eip712_encode_field(field_type: str, value) -> bytes:
"""ABI-encode a single EIP-712 field value to 32 bytes."""
if field_type == "string":
return keccak(value.encode() if isinstance(value, str) else value)
elif field_type == "bytes32":
if isinstance(value, bytes):
return value.ljust(32, b"\x00")
elif isinstance(value, str):
return bytes.fromhex(value.replace("0x", "")).ljust(32, b"\x00")
elif isinstance(value, list):
return bytes(value).ljust(32, b"\x00")
elif field_type in ("uint256", "uint64"):
return int(value).to_bytes(32, "big")
elif field_type == "bool":
return int(bool(value)).to_bytes(32, "big")
elif field_type == "address":
return bytes.fromhex(value.replace("0x", "")).rjust(32, b"\x00")
raise ValueError(f"Unsupported EIP-712 type: {field_type}")
def _eip712_hash_struct(primary_type: str, types: dict, message: dict) -> bytes:
"""Compute hashStruct for an EIP-712 message."""
fields = types[primary_type]
type_string = (
primary_type
+ "("
+ ",".join(f"{f['type']} {f['name']}" for f in fields)
+ ")"
)
encoded = keccak(type_string.encode())
for field in fields:
encoded += _eip712_encode_field(field["type"], message[field["name"]])
return keccak(encoded)
def _eip712_digest(domain: dict, types: dict, primary_type: str, message: dict) -> bytes:
"""Compute the full EIP-712 digest: keccak256(0x1901 || domainSep || structHash)."""
domain_sep = _eip712_domain_separator(domain)
struct_hash = _eip712_hash_struct(primary_type, types, message)
return keccak(b"\x19\x01" + domain_sep + struct_hash)
# ── Local ecrecover verification ──────────────────────────────────────────
def _verify_signature_locally(
domain: dict,
types: dict,
primary_type: str,
message: dict,
signature_hex: str,
expected_address: Optional[str],
) -> bool:
"""
Verify an EIP-712 signature locally using ecrecover.
Computes the EIP-712 hash manually (no encode_typed_data dependency)
and recovers the signer address from the signature.
Returns True if the recovered address matches expected_address.
"""
if not expected_address:
return True # Can't verify without address, assume OK
try:
from eth_keys import keys
digest = _eip712_digest(domain, types, primary_type, message)
sig_bytes = bytes.fromhex(signature_hex.replace("0x", ""))
r = int.from_bytes(sig_bytes[:32], "big")
s = int.from_bytes(sig_bytes[32:64], "big")
v = sig_bytes[64]
if v >= 27:
v -= 27
sig = keys.Signature(vrs=(v, r, s))
public_key = sig.recover_public_key_from_msg_hash(digest)
recovered = public_key.to_checksum_address()
recovered_lower = recovered.lower()
expected_lower = expected_address.lower()
if recovered_lower == expected_lower:
logger.info(f"EIP-712 ecrecover OK: {recovered}")
return True
else:
logger.warning(
f"EIP-712 ecrecover MISMATCH: recovered={recovered}, expected={expected_address}"
)
return False
except Exception as e:
logger.warning(f"Local ecrecover verification failed: {e}")
return False
def _signature_to_hex(sig: dict) -> str:
"""Convert {r, s, v} dict to flat hex signature string."""
r = sig["r"].replace("0x", "").zfill(64)
s = sig["s"].replace("0x", "").zfill(64)
v = sig["v"]
return "0x" + r + s + format(v, "02x")
# ── Core hashing ──────────────────────────────────────────────────────────
def action_hash(action: dict, vault_address: Optional[str], nonce: int) -> bytes:
"""
Compute keccak256 hash of a Hyperliquid L1 action.
Steps:
1. msgpack serialize the action dict
2. Append nonce as 8-byte big-endian
3. Append vault flag: 0x01 if vault_address else 0x00
4. If vault, append 20 bytes of vault address
5. keccak256 the whole blob
"""
data = msgpack.packb(action)
data += nonce.to_bytes(8, "big")
if vault_address:
data += b"\x01"
# Remove 0x prefix if present, decode hex to bytes
addr_bytes = bytes.fromhex(vault_address.replace("0x", ""))
data += addr_bytes
else:
data += b"\x00"
return keccak(data)
# ── L1 Action Signing (orders, cancels, leverage) ────────────────────────
async def sign_l1_action(
action: dict,
nonce: int,
vault_address: Optional[str] = None,
) -> dict:
"""
Sign an L1 action (order, cancel, leverage, modify) via wallet service.
Tries multiple connectionId encodings and verifies each with local ecrecover.
Uses the first encoding that produces a signature matching the wallet address.
Returns: {"r": "0x...", "s": "0x...", "v": 27|28}
"""
hash_bytes = action_hash(action, vault_address, nonce)
source = MAINNET_SOURCE
expected_address = await _get_wallet_address()
# Multiple connectionId encodings to try
encodings = [
("hex_with_0x", "0x" + hash_bytes.hex()), # current: hex string with prefix
("byte_array", list(hash_bytes)), # byte array as list of ints
("hex_no_prefix", hash_bytes.hex()), # hex string without 0x prefix
]
last_error = None
for encoding_name, connection_id_value in encodings:
try:
payload = {
"domain": L1_DOMAIN,
"types": AGENT_TYPES,
"primaryType": "Agent",
"message": {
"source": source,
"connectionId": connection_id_value,
},
}
logger.info(
f"sign_l1_action: trying encoding={encoding_name}, "
f"connectionId type={type(connection_id_value).__name__}"
)
result = await _wallet_request("POST", "/agent/sign-typed-data", payload)
sig = _parse_signature(result)
# Verify locally with ecrecover
# For verification, connectionId must be the raw bytes32
verify_message = {
"source": source,
"connectionId": hash_bytes,
}
sig_hex = _signature_to_hex(sig)
match = _verify_signature_locally(
domain=L1_DOMAIN,
types=AGENT_TYPES,
primary_type="Agent",
message=verify_message,
signature_hex=sig_hex,
expected_address=expected_address,
)
if match:
logger.info(f"sign_l1_action: encoding={encoding_name} VERIFIED")
return sig
else:
logger.warning(
f"sign_l1_action: encoding={encoding_name} signature mismatch, trying next"
)
except Exception as e:
logger.warning(f"sign_l1_action: encoding={encoding_name} failed: {e}")
last_error = e
raise RuntimeError(
f"sign_l1_action: No encoding produced a verified signature. "
f"Expected address: {expected_address}. Last error: {last_error}"
)
# ── User-Signed Action (transfers, withdrawals, abstraction) ──────────────────────────
async def sign_user_set_abstraction(
user: str,
abstraction: str,
nonce: int,
) -> dict:
"""Sign a user set abstraction action.
Uses HyperliquidSignTransaction domain for user-signed actions.
Matches SDK's sign_user_set_abstraction_action exactly.
Args:
user: User address (lowercase)
abstraction: Abstraction mode ("unifiedAccount", "portfolioMargin", "disabled")
nonce: Timestamp in milliseconds
Returns: {"r": "0x...", "s": "0x...", "v": 27|28}
"""
types = {
"HyperliquidTransaction:UserSetAbstraction": [
{"name": "hyperliquidChain", "type": "string"},
{"name": "user", "type": "address"}, # ADDRESS, not string!
{"name": "abstraction", "type": "string"},
{"name": "nonce", "type": "uint64"},
]
}
action = {
"hyperliquidChain": "Mainnet",
"user": user.lower(),
"abstraction": abstraction,
"nonce": nonce,
}
return await sign_user_action(
action=action,
types=types,
primary_type="HyperliquidTransaction:UserSetAbstraction",
)
async def sign_approve_builder_fee(
max_fee_rate: str,
builder: str,
nonce: int,
) -> dict:
"""Sign an ApproveBuilderFee action (user-signed).
Allows a builder address to charge a fee on the user's fills, up to max_fee_rate.
Must be signed by the user's main wallet (not an API/agent wallet).
Args:
max_fee_rate: Max fee rate as a percentage string, e.g. "0.02%" for 2 bps
builder: Builder address (hex string)
nonce: Timestamp in milliseconds
Returns: {"r": "0x...", "s": "0x...", "v": 27|28}
"""
types = {
"HyperliquidTransaction:ApproveBuilderFee": [
{"name": "hyperliquidChain", "type": "string"},
{"name": "maxFeeRate", "type": "string"},
{"name": "builder", "type": "address"},
{"name": "nonce", "type": "uint64"},
]
}
action = {
"hyperliquidChain": "Mainnet",
"maxFeeRate": max_fee_rate,
"builder": builder.lower(),
"nonce": nonce,
}
return await sign_user_action(
action=action,
types=types,
primary_type="HyperliquidTransaction:ApproveBuilderFee",
)
async def sign_user_action(
action: dict,
types: dict,
primary_type: str,
) -> dict:
"""
Sign a user-level action (USDC transfer, withdrawal) via wallet service.
Uses the HyperliquidSignTransaction domain (no msgpack/keccak).
Verifies the signature locally with ecrecover before returning.
Returns: {"r": "0x...", "s": "0x...", "v": 27|28}
"""
expected_address = await _get_wallet_address()
payload = {
"domain": USER_SIGNED_DOMAIN,
"types": types,
"primaryType": primary_type,
"message": action,
}
result = await _wallet_request("POST", "/agent/sign-typed-data", payload)
sig = _parse_signature(result)
# Verify locally
sig_hex = _signature_to_hex(sig)
match = _verify_signature_locally(
domain=USER_SIGNED_DOMAIN,
types=types,
primary_type=primary_type,
message=action,
signature_hex=sig_hex,
expected_address=expected_address,
)
if not match:
logger.error(
f"sign_user_action: signature mismatch! "
f"Expected address: {expected_address}, action type: {primary_type}"
)
return sig
# ── Signature parsing ─────────────────────────────────────────────────────
def _parse_signature(result: dict) -> dict:
"""
Parse signature from wallet service into {r, s, v} format.
The wallet service may return either:
- A flat hex signature string in result["signature"]
- Already-split {r, s, v} components
"""
sig = result.get("signature", result)
if isinstance(sig, str):
# Flat hex signature — split into r, s, v
sig_hex = sig.replace("0x", "")
if len(sig_hex) == 130:
r = "0x" + sig_hex[:64]
s = "0x" + sig_hex[64:128]
v = int(sig_hex[128:130], 16)
# Normalize v to 27/28
if v < 27:
v += 27
return {"r": r, "s": s, "v": v}
raise ValueError(f"Unexpected signature length: {len(sig_hex)}")
if isinstance(sig, dict):
# Already has components
r = sig.get("r", "")
s = sig.get("s", "")
v = sig.get("v", 0)
if isinstance(v, str):
v = int(v, 16) if v.startswith("0x") else int(v)
if v < 27:
v += 27
return {"r": r, "s": s, "v": v}
raise ValueError(f"Cannot parse signature from wallet response: {result}")
SKILL.md
---
name: hyperliquid
version: 1.8.0
description: |
Trade perp futures, spot, and RWA on Hyperliquid DEX with up to asset max leverage.
Use when placing perp or spot orders, setting TP/SL, or moving funds on Hyperliquid (e.g. long BTC 5x, sell ETH, deposit USDC, set stop).
delivery: script
metadata:
starchild:
emoji: "📈"
skillKey: hyperliquid
requires:
env: [WALLET_SERVICE_URL]
user-invocable: true
disable-model-invocation: false
---
# Hyperliquid Trading
Trade perpetual futures and spot tokens on Hyperliquid, a fully on-chain decentralized exchange. Orders are signed using this agent's EVM wallet and submitted directly to the Hyperliquid L1.
## Prerequisites
Before trading, the wallet policy must be active. Load the **wallet-policy** skill and propose the standard wildcard policy (deny key export + allow `*`). This covers all Hyperliquid operations — USDC deposits, EIP-712 order signing, and withdrawals.
## Runtime Model: How to Call Hyperliquid (Read This First)
This skill is **script-delivery**. It registers **no** `hl_*` agent tools — calling
`hl_deposit`, `hl_order`, or any other `hl_*` name as a tool will always fail with
"not found in registry". That is by design, not a bug or a missing install.
There are exactly two working lanes:
### Lane 1 — Read-only queries (`exports.py`)
```python
from core.skill_tools import hyperliquid
account = hyperliquid.hl_account()
mids = hyperliquid.hl_market()
candles = hyperliquid.hl_candles(coin="BTC", interval="1h", hours_back=24)
```
**Any wallet, not just your own.** Every user-scoped function takes an optional
`address`. Omit it for the agent's own wallet; pass a 0x address to inspect a
third party. This is what makes "analyse this wallet's Hyperliquid PnL"
answerable — Hyperliquid is an off-chain order book, so a DeBank-style
chain scan cannot see any of it.
```python
hyperliquid.hl_portfolio(address="0x1f16...") # PnL time series
hyperliquid.hl_account(address="0x1f16...") # their open positions
```
32 functions, grouped:
| Group | Functions |
|-------|-----------|
| Account | `hl_account` `hl_balances` `hl_total_balance` `hl_user_role` `hl_user_fees` `hl_rate_limit` `hl_sub_accounts` `hl_referral` `hl_extra_agents` |
| PnL & history | `hl_portfolio` `hl_fills` `hl_fills_by_time` `hl_historical_orders` `hl_ledger` `hl_funding_payments` `hl_twap_fills` `hl_vault_equities` |
| Orders | `hl_open_orders` `hl_open_orders_full` `hl_order_status` |
| Market | `hl_market` `hl_orderbook` `hl_candles` `hl_funding` `hl_predicted_funding` `hl_meta` `hl_meta_ctxs` `hl_spot_meta` `hl_spot_meta_ctxs` `hl_perp_dexs` |
| Staking | `hl_staking` `hl_staking_delegations` `hl_staking_rewards` |
Read-only only — no writes on this lane.
### Answering "what is this wallet's PnL?"
`hl_portfolio` returns 8 windows — `day`, `week`, `month`, `allTime` and the
`perp*` equivalents — each with `accountValueHistory` and `pnlHistory` as
`[epoch_ms, value]` pairs. `pnlHistory` restarts at 0 at the start of each
window, so read `allTime` for lifetime PnL.
```python
pf = dict(hyperliquid.hl_portfolio(address=addr))
pnl = float(pf["allTime"]["pnlHistory"][-1][1])
```
For a cost-basis reconstruction, combine three sources: `hl_ledger` (capital
in/out — deposits, withdrawals, vault moves), `hl_fills_by_time` (realized
`closedPnl` per fill, 2000 max per call — page by passing the last fill's
`time` as the next `start`), and `hl_funding_payments` (funding paid/received).
Check `hl_user_role` first: role `"missing"` means the address never traded
here, which is not the same as "no positions".
### Lane 2 — Writes: orders, cancels, transfers, deposits (`client.py`)
Every write goes through `HyperliquidClient`, which owns the EIP-712 signing
pipeline. It is an **async** class — `await` every call.
```python
from skills.hyperliquid.client import HyperliquidClient
client = HyperliquidClient()
# Deposit USDC to the Hyperliquid bridge (minimum 5 USDC)
res = await client.deposit_usdc(amount=500)
# Place an order
res = await client.place_order(
coin="BTC", is_buy=True, size=0.001, price=95000, order_type="limit",
)
# Cancel / leverage / transfer / withdraw
await client.cancel_all("BTC")
await client.update_leverage(coin="BTC", leverage=5, is_cross=True)
await client.transfer_usd(amount=100, to_perp=True)
await client.withdraw_from_bridge(amount=50)
```
Prerequisite for Lane 2: the wallet policy must be active — load the
**wallet-policy** skill and propose the standard wildcard policy (deny key
export + allow `*`). That covers deposits, EIP-712 order signing, and withdrawals.
**Naming note:** the rest of this document refers to operations by their
historical `hl_*` names (e.g. "`hl_deposit`"). Those are *labels for the
operation*, not callable tools — always reach them via Lane 1 or Lane 2 above.
## Available Tools
### Account & Market Info
| Tool | What it does |
|------|--------------|
| `hl_total_balance` | Check how much you can trade with (use this for balance checks!) |
| `hl_account` | Open positions and unrealized PnL |
| `hl_balances` | Token holdings (USDC, HYPE, etc.) |
| `hl_portfolio` | **PnL and account value over time** — day/week/month/allTime |
| `hl_ledger` | Deposits, withdrawals, transfers — the capital in/out record |
| `hl_fills_by_time` | Fills within a date range, for cost-basis work |
| `hl_market` | Get current prices for crypto or stocks |
| `hl_meta_ctxs` | Market-wide scan: markPx, funding, OI, volume per asset |
| `hl_orderbook` | Check order book depth and liquidity |
| `hl_fills` | See recent trade fills and execution prices |
| `hl_candles` | Get price charts (1m, 5m, 1h, 4h, 1d) |
| `hl_funding` | Check funding rates for perps |
| `hl_open_orders` | See pending orders |
| `hl_open_orders_full` | Pending orders **with** stop-loss / take-profit detail |
All of the above accept `address="0x..."` to inspect any wallet, not just
the agent's own.
### Trading
| Tool | What it does |
|------|--------------|
| `hl_order` | Buy or sell perps (crypto/stocks) |
| `hl_spot_order` | Buy or sell spot tokens |
| `hl_tpsl_order` | Place stop loss or take profit orders |
| `hl_leverage` | Set leverage (1x to asset max) |
| `hl_cancel` | Cancel a specific order |
| `hl_cancel_all` | Cancel all open orders |
| `hl_modify` | Change order price or size |
### Funds
| Tool | What it does |
|------|--------------|
| `hl_deposit` | Add USDC from Arbitrum (min $5) |
| `hl_withdraw` | Send USDC to Arbitrum (1 USDC fee, ~5 min) |
| `hl_transfer_usd` | Move USDC between spot/perp (rarely needed) |
### Platform
| Tool | What it does |
|------|--------------|
| `hl_approve_builder` | Approve Starchild builder fee collection (auto-done on first order) |
| `hl_builder_status` | Check builder approval status and collected rewards |
---
## Quick Start
Just tell the agent what you want to trade - it handles everything automatically.
**Examples:**
```
User: "Buy $20 of Bitcoin with 5x leverage"
Agent: [checks balance → sets leverage → places order → reports fill]
Result: "✓ Bought 0.0002 BTC at $95,432 with 5x leverage. Position opened."
User: "Long NVIDIA with $50, 10x"
Agent: [auto-detects NVIDIA = xyz:NVDA → executes → verifies]
Result: "✓ Bought 0.25 NVDA at $198.50 with 10x leverage. Filled at $198.62."
User: "Sell my ETH position"
Agent: [checks position size → closes → reports PnL]
Result: "✓ Sold 0.5 ETH at $3,421. Realized PnL: +$12.50"
```
**You don't need to:**
- Understand account modes or fund transfers
- Check balances manually (agent does it)
- Calculate position sizes (agent does it)
- Verify fills (agent does it)
**Just say what you want, the agent handles the rest.**
---
## Agent Behavior Guidelines
**🤖 As the agent, you should ALWAYS do these automatically (never ask the user):**
1. **Check available funds** - Use `hl_total_balance` before EVERY trade to see total available margin
2. **Detect asset type** - Recognize if user wants crypto (BTC, ETH, SOL) or stocks/RWA (NVIDIA→xyz:NVDA, TESLA→xyz:TSLA)
3. **Set leverage** - Always call `hl_leverage` before placing orders (unless user specifies not to)
4. **Verify fills** - After placing ANY order, immediately call `hl_fills` to check if it filled
5. **Report results** - Tell user the outcome: filled price, size, and any PnL
6. **Suggest risk management** - For leveraged positions, remind users about stop losses or offer to set them
**🎯 User just says:** "buy X" or "sell Y" or "long Z with $N"
**🔧 You figure out:**
- Current balance (hl_total_balance)
- Asset resolution (crypto vs RWA)
- Leverage settings (hl_leverage)
- Order sizing (calculate from user's $ amount or size)
- Execution (hl_order)
- Verification (hl_fills)
- Final report to user
**📊 Balance checking hierarchy:**
- ✅ Use `hl_total_balance` - shows ACTUAL available margin regardless of account mode
- ❌ Don't use `hl_account` for balance - may show $0 even if funds available
- ❌ Don't use `hl_balances` for margin - only shows spot tokens
**🚀 Be proactive, not reactive:**
- Don't wait for user to ask "did it fill?" - check automatically
- Don't ask "should I check your balance?" - just do it
- Don't explain account modes - user doesn't care, just execute
---
## Tool Usage Examples
### Check Account State
```
hl_account() # Default crypto perps account
hl_account(dex="xyz") # Builder dex (RWA/stock perps) account
```
Returns `marginSummary` (accountValue, totalMarginUsed, withdrawable) and `assetPositions` array with each position's coin, szi (signed size), entryPx, unrealizedPnl, leverage.
**Important:** Builder perps (xyz:NVDA, xyz:TSLA, etc.) have separate clearinghouses. Always check the correct dex when trading RWA/stock perps.
### Check Spot Balances
```
hl_balances()
```
Returns balances array with coin, hold, total for USDC and all spot tokens.
### Check Market Prices
```
hl_market() # All mid prices
hl_market(coin="BTC") # BTC price + metadata (maxLeverage, szDecimals)
```
### Side Parameter Convention (read this first)
All order tools (`hl_order`, `hl_spot_order`, `hl_tpsl_order`, `hl_modify`)
use the same `side` parameter. **Use `"buy"` or `"sell"`** — these are the
documented values and should be your default.
For safety, the tools also accept these aliases so a model guess doesn't
reverse direction on a leveraged order:
- Buy family: `"buy"`, `"B"`, `"bid"`, `"long"`, `"L"`, `1`, `true`
- Sell family: `"sell"`, `"S"`, `"A"`, `"ask"`, `"short"`, `0`, `false`
**An unrecognized value will fail the call with a clear error** — the tool
never defaults to sell (or buy) when `side` is ambiguous. This is intentional:
silently reversing direction on a leveraged position is the worst failure mode.
Note: Hyperliquid's L1 wire protocol uses `"B"` and `"A"` internally, but the
tool interface here is `buy`/`sell`. Stick to `buy`/`sell` in your calls and
you will never be surprised.
### Place a Perp Limit Order
```
hl_order(coin="BTC", side="buy", size=0.01, price=95000)
```
Places a GTC limit buy for 0.01 BTC at $95,000.
### Place a Perp Market Order
```
hl_order(coin="ETH", side="sell", size=0.1)
```
Omitting `price` submits an IoC order at mid price +/- 3% slippage.
**Parameter format behavior:**
- Preferred: pass correct JSON types (`size` as number, `reduce_only` as boolean)
- Hyperliquid tools now include tolerant coercion for common LLM formatting mistakes:
- numeric strings like `"0.01"` → `0.01`
- boolean strings like `"true"/"false"` → `true/false`
- integer strings like `"5"`/`"5.0"` → `5`
- Invalid/empty/non-finite values still fail with explicit validation errors
### Place a Post-Only Order
```
hl_order(coin="BTC", side="buy", size=0.01, price=94000, order_type="alo")
```
ALO (Add Liquidity Only) = post-only. Rejected if it would immediately fill.
**Practical guardrail for bots:** If your ALO price is too close to mid (often within ~0.1% on liquid pairs), Hyperliquid may reject it. For market-making/grid bots, compute current mid first and skip or shift levels that sit inside your no-cross buffer zone.
### Place a Stop Loss Order
```
hl_tpsl_order(coin="BTC", side="sell", size=0.01, trigger_px=90000, tpsl="sl")
```
Automatically sells 0.01 BTC if the price drops to $90,000. Executes as market order when triggered.
For a limit order when triggered (instead of market):
```
hl_tpsl_order(coin="BTC", side="sell", size=0.01, trigger_px=90000, tpsl="sl", is_market=false, limit_px=89900)
```
### Place a Take Profit Order
```
hl_tpsl_order(coin="ETH", side="sell", size=0.5, trigger_px=3500, tpsl="tp")
```
Automatically sells 0.5 ETH if the price rises to $3,500. Executes as market order when triggered.
### Close a Perp Position
```
hl_order(coin="BTC", side="sell", size=0.01, reduce_only=true)
```
Use `reduce_only=true` to ensure it only closes, never opens a new position.
### Place a Spot Order
```
hl_spot_order(coin="HYPE", side="buy", size=10, price=25.0)
```
Spot orders use the same interface — just specify the token name.
### Cancel an Order
```
hl_cancel(coin="BTC", order_id=12345678)
```
Get `order_id` from `hl_open_orders`.
### Cancel All Orders
```
hl_cancel_all() # Cancel everything
hl_cancel_all(coin="BTC") # Cancel only BTC orders
```
### Modify an Order
```
hl_modify(order_id=12345678, coin="BTC", side="buy", size=0.02, price=94500)
```
### Set Leverage
```
hl_leverage(coin="BTC", leverage=10) # 10x cross margin
hl_leverage(coin="ETH", leverage=5, cross=false) # 5x isolated margin
```
### Transfer USDC (rarely needed)
```
hl_transfer_usd(amount=1000, to_perp=true) # Spot → Perp
hl_transfer_usd(amount=500, to_perp=false) # Perp → Spot
```
Note: Usually not needed - funds are automatically shared. Only use if you get an error saying you need to transfer.
### Withdraw USDC to Arbitrum
```
hl_withdraw(amount=100) # Withdraw to own wallet
hl_withdraw(amount=50, destination="0xABC...") # Withdraw to specific address
```
Fee: 1 USDC deducted by Hyperliquid. Processing takes ~5 minutes.
### Deposit USDC from Arbitrum
```
hl_deposit(amount=500)
```
Sends USDC from the agent's Arbitrum wallet to the Hyperliquid bridge contract. Minimum deposit: 5 USDC. Requires USDC balance on Arbitrum.
### Get Candles
```
hl_candles(coin="BTC", interval="1h", lookback=48)
```
Intervals: `1m`, `5m`, `15m`, `1h`, `4h`, `1d`. Lookback in hours.
### Check Funding Rates
```
hl_funding() # All predicted fundings
hl_funding(coin="BTC") # BTC predicted + 24h history
```
### Get Recent Fills
```
hl_fills(limit=10)
```
---
## Coin vs RWA Resolution
When a user asks to trade a ticker, you need to determine whether it's a **native crypto perp** (use plain name) or an **RWA/stock perp** (use `xyz:TICKER` prefix).
### Decision Workflow
1. **Known crypto** → use plain name: `"BTC"`, `"ETH"`, `"SOL"`, `"DOGE"`, `"HYPE"`, etc.
2. **Known stock/commodity/forex** → use `xyz:` prefix: `"xyz:NVDA"`, `"xyz:TSLA"`, `"xyz:GOLD"`, etc.
3. **Unsure** → resolve with tool calls:
- First try `hl_market(coin="X")` — if it returns a price, it's a crypto perp
- If not found, try `hl_market(dex="xyz")` to list all RWA markets and search the results
- Use whichever returns a match
### Common RWA Categories (all use `xyz:` prefix)
| Category | Examples |
|----------|----------|
| **US Stocks** | `xyz:NVDA`, `xyz:TSLA`, `xyz:AAPL`, `xyz:MSFT`, `xyz:AMZN`, `xyz:GOOG`, `xyz:META`, `xyz:TSM` |
| **Commodities — Metals** | `xyz:GOLD`, `xyz:SILVER`, `xyz:COPPER`, `xyz:PLATINUM`, `xyz:PALLADIUM`, `xyz:ALUMINIUM` |
| **Commodities — Energy** | `xyz:CL` (WTI), `xyz:BRENTOIL`, `xyz:NATGAS`, `xyz:TTF` (EU Gas) |
| **Commodities — Agriculture** | `xyz:CORN`, `xyz:WHEAT` |
| **Commodities — Other** | `xyz:URANIUM` |
| **Indices** | `xyz:SPY` |
| **Forex** | `xyz:EUR`, `xyz:GBP`, `xyz:JPY` |
> If a user says "buy NVDA" or "trade GOLD", use `xyz:NVDA` / `xyz:GOLD`. These are real-world assets, not crypto.
### ⚠️ HIP-3 Commodity Price Lookup
**All 13 commodity markets are HIP-3 builder-deployed perps.** Their symbols use the `xyz:` prefix (e.g. `xyz:GOLD`, `xyz:CL`), NOT standard formats like XAU, XAG, or WTI.
**Full commodity list:** GOLD, SILVER, COPPER, PLATINUM, PALLADIUM, ALUMINIUM, CL (WTI crude), BRENTOIL, NATGAS, TTF (EU gas), CORN, WHEAT, URANIUM.
**Key gotcha:** HIP-3 assets are **NOT included in `allMids`** (the standard price feed). This means:
- `hl_market(coin="xyz:GOLD")` may return **no price** or fail to find the asset
- `hl_market(dex="xyz")` lists all builder markets but may not include mid prices
**The reliable way to get commodity prices is `hl_candles`:**
```
# Get latest gold price (use 1h candles, lookback=24 for 24h data)
hl_candles(coin="xyz:GOLD", interval="1h", lookback=24)
# Get latest copper price
hl_candles(coin="xyz:COPPER", interval="1h", lookback=24)
# Get latest silver price
hl_candles(coin="xyz:SILVER", interval="1h", lookback=24)
```
The `close` field of the most recent candle = current price. The oldest candle's `open` vs latest `close` gives 24h change.
### Prefixed Name — Same Tools
All existing tools work with `xyz:TICKER` — just pass the prefixed coin name:
```
hl_market(coin="xyz:NVDA") # Check NVIDIA stock perp price
hl_market(dex="xyz") # List ALL available RWA/stock perps
hl_orderbook(coin="xyz:NVDA") # Check liquidity
hl_leverage(coin="xyz:NVDA", leverage=3) # Set leverage (auto-isolated)
hl_order(coin="xyz:NVDA", side="buy", size=0.5, price=188) # Limit buy 0.5 NVDA
hl_order(coin="xyz:TSM", side="buy", size=1) # Market buy 1 TSM
hl_cancel(coin="xyz:NVDA", order_id=12345678) # Cancel order
```
### Example: User Says "Buy NVIDIA"
1. Recognize NVIDIA = stock → use `xyz:NVDA`
2. `hl_market(coin="xyz:NVDA")` — Check current price, leverage limits
3. `hl_leverage(coin="xyz:NVDA", leverage=3)` — Set leverage (builder perps use isolated margin)
4. `hl_order(coin="xyz:NVDA", side="buy", size=0.5, price=188)` — Place limit buy
5. `hl_fills()` — Check if filled
### Notes
- Builder perps (HIP-3) use isolated margin only — `hl_leverage` handles this automatically
- The `dex` prefix (e.g. `xyz`) identifies which builder deployed the perp
- All tools (candles, orderbook, funding, etc.) work the same way with prefixed names
---
## Common Workflows
### Query Commodity Prices
User: "What's the gold price?" or "Show me commodity prices" or "Oil price?"
**Name → Symbol mapping:**
- Metals: GOLD→`xyz:GOLD`, SILVER→`xyz:SILVER`, COPPER→`xyz:COPPER`, PLATINUM→`xyz:PLATINUM`, PALLADIUM→`xyz:PALLADIUM`, ALUMINIUM→`xyz:ALUMINIUM`
- Energy: WTI/Crude Oil→`xyz:CL`, Brent→`xyz:BRENTOIL`, Natural Gas→`xyz:NATGAS`, EU Gas→`xyz:TTF`
- Agriculture: Corn→`xyz:CORN`, Wheat→`xyz:WHEAT`
- Other: Uranium→`xyz:URANIUM`
**Steps:**
1. Map commodity name → HIP-3 symbol using the table above
2. `hl_candles(coin="xyz:GOLD", interval="1h", lookback=24)` — Get 24h of hourly candles
3. Current price = last candle's `close`
4. 24h change = `(last_close - first_open) / first_open * 100`
5. Repeat for each commodity as needed
**Do NOT use `hl_market()` for commodities** — HIP-3 assets are not in `allMids`. Always use `hl_candles`.
**Liquidity note:** CL (WTI) and BRENTOIL have the highest volume. ALUMINIUM, URANIUM, CORN, WHEAT, TTF may have zero or very low liquidity — warn the user before trading these.
### Trade Crypto Perps (BTC, ETH, SOL, etc.)
User: "Buy BTC" or "Long ETH with 5x"
Agent workflow:
1. `hl_total_balance()` → Check available funds
2. `hl_leverage(coin="BTC", leverage=5)` → Set leverage
3. `hl_order(...)` → Place order
4. `hl_fills()` → Verify fill and report result
### Trade Stocks/RWA (NVIDIA, TESLA, GOLD, etc.)
User: "Buy NVIDIA" or "Short TESLA"
Agent workflow:
1. Detect asset type → Convert "NVIDIA" to "xyz:NVDA"
2. `hl_total_balance()` → Check available funds
3. `hl_leverage(coin="xyz:NVDA", leverage=10)` → Set leverage
4. `hl_order(coin="xyz:NVDA", ...)` → Place order
5. `hl_fills()` → Verify fill and report result
### Close Positions
User: "Close my BTC position"
Agent workflow:
1. `hl_account()` → Get current position size
2. `hl_order(coin="BTC", side="sell", size=X, reduce_only=true)` → Close position
3. `hl_fills()` → Report PnL
### Grid / Market-Making Bot Loop (service mode)
For always-on bots running inside FastAPI/worker services:
1. Read open orders via `get_open_orders(address)`
2. Read fills via `get_user_fills(address)`
3. Use **fills as source of truth** for "order executed" events
4. On fill:
- buy fill → place paired sell at next grid level
- sell fill → place paired buy at previous grid level
5. Keep periodic reconciliation: local state vs exchange open orders
**Important:** Do not treat "order disappeared from open orders" as guaranteed fill. It can also mean cancel/reject/expired. Always confirm with `get_user_fills` (or `get_order_status` when needed).
### Spot Trading
User: "Buy 100 HYPE tokens"
Agent workflow:
1. `hl_total_balance()` → Check available USDC
2. `hl_spot_order(coin="HYPE", side="buy", size=100)` → Buy tokens
3. `hl_balances()` → Verify purchase
### Deposit/Withdraw Funds
**Deposit:**
User: "Deposit $500 USDC to Hyperliquid"
Agent: `hl_deposit(amount=500)` → Done
**Withdraw:**
User: "Withdraw $100 to my Arbitrum wallet"
Agent: `hl_withdraw(amount=100)` → Done (5 min, 1 USDC fee)
---
## Order Types
| Type | Parameter | Behavior |
|------|-----------|----------|
| **Limit (GTC)** | `order_type="limit"` | Rests on book until filled or cancelled |
| **Market (IoC)** | omit `price` | Immediate-or-Cancel at mid +/- 3% slippage |
| **Post-Only (ALO)** | `order_type="alo"` | Rejected if it would cross the spread |
| **Fill-or-Kill** | `order_type="ioc"` + explicit price | Fill immediately at price or cancel |
| **Stop Loss** | `hl_tpsl_order` with `tpsl="sl"` | Triggers when price drops to limit losses |
| **Take Profit** | `hl_tpsl_order` with `tpsl="tp"` | Triggers when price rises to lock gains |
---
## Stop Loss & Take Profit Orders
Stop loss and take profit orders are **trigger orders** that automatically execute when the market reaches a specified price level. Use these to manage risk and lock in profits without monitoring positions 24/7.
### How They Work
1. **Order Placement**: Place a dormant trigger order with a trigger price
2. **Monitoring**: Order sits inactive, watching the market price
3. **Trigger**: When market price reaches `trigger_px`, order activates
4. **Execution**: Order executes immediately (as market or limit order)
### Stop Loss (SL)
**Use case**: Limit losses on a position by automatically exiting if price moves against you.
**Example**: You're long BTC at $95,000 and want to exit if it drops below $90,000.
```
hl_tpsl_order(coin="BTC", side="sell", size=0.1, trigger_px=90000, tpsl="sl")
```
- **trigger_px=90000**: Activates when BTC drops to $90k
- **side="sell"**: Closes your long position
- **tpsl="sl"**: Marks this as a stop loss order
- **Default**: Executes as market order when triggered (instant exit)
### Take Profit (TP)
**Use case**: Lock in gains by automatically exiting when price reaches your profit target.
**Example**: You're long ETH at $3,000 and want to take profit at $3,500.
```
hl_tpsl_order(coin="ETH", side="sell", size=1.0, trigger_px=3500, tpsl="tp")
```
- **trigger_px=3500**: Activates when ETH rises to $3,500
- **side="sell"**: Closes your long position
- **tpsl="tp"**: Marks this as a take profit order
- **Default**: Executes as market order when triggered (instant exit)
### Market vs Limit Execution
By default, TP/SL orders execute as **market orders** when triggered (instant fill, possible slippage).
For more control, use a **limit order** when triggered:
```
hl_tpsl_order(
coin="BTC",
side="sell",
size=0.1,
trigger_px=90000,
tpsl="sl",
is_market=false,
limit_px=89900
)
```
- **trigger_px=90000**: Activates at $90k
- **is_market=false**: Use limit order (not market)
- **limit_px=89900**: Limit price when triggered ($89,900)
**Trade-off**: Limit orders avoid slippage but may not fill in fast-moving markets.
### Short Positions
For short positions, reverse the `side` parameter:
**Stop loss on short** (exit if price rises):
```
hl_tpsl_order(coin="BTC", side="buy", size=0.1, trigger_px=98000, tpsl="sl")
```
**Take profit on short** (exit if price drops):
```
hl_tpsl_order(coin="BTC", side="buy", size=0.1, trigger_px=92000, tpsl="tp")
```
### Best Practices
1. **Always use `reduce_only=true`** (default) - ensures TP/SL only closes positions, never opens new ones
2. **Match size to position** - TP/SL size should equal or be less than your position size
3. **Set both TP and SL** - protect both upside (take profit) and downside (stop loss)
4. **Account for volatility** - don't set stops too tight or they'll trigger on normal price swings
5. **Check open orders** - use `hl_open_orders` to verify TP/SL orders are active
### Common Mistakes
| Mistake | Problem | Solution |
|---------|---------|----------|
| Wrong side | SL buys instead of sells | Long position → `side="sell"` for SL/TP |
| Size too large | TP/SL opens new position | Set `size` ≤ position size, use `reduce_only=true` |
| Trigger = limit | Confusion about prices | `trigger_px` = when to activate, `limit_px` = execution price |
| No SL on leverage | Liquidation risk | Always set stop loss on leveraged positions |
---
## Perps vs Spot
| Aspect | Perps | Spot |
|--------|-------|------|
| Tool | `hl_order` | `hl_spot_order` |
| Leverage | Yes (up to asset max) | No |
| Funding | Paid/received every hour | None |
| Short selling | Yes (native) | Must own tokens to sell |
| Check positions | `hl_account` | `hl_balances` |
---
## Risk Management
- **Always check account state before trading** — know your margin usage and existing positions
- **Set leverage explicitly** before opening new positions (default may vary)
- **Use reduce_only** when closing to avoid accidentally opening the opposite direction
- **Monitor funding rates** — high positive funding means longs are expensive to hold
- **Start with small sizes** — Hyperliquid has minimum order sizes per asset (check szDecimals)
- **Post-only (ALO) orders** save on fees (maker vs taker rates)
- **Check fills after market orders** — IoC orders may partially fill or not fill at all
---
## Builder Code (Platform Fee)
Starchild automatically collects a **2 bps (0.02%) builder fee** on every perp and spot order placed through this skill. This fee supports platform operations and is separate from Hyperliquid's own trading fees.
**How it works:**
- The first time a user places an order, the skill auto-approves the Starchild builder address via the `ApproveBuilderFee` action (signed by the user's main wallet)
- All subsequent orders include a `builder` parameter: `{"b": "0x2c5320F40305fFC933385c6DCec5493fbA7b98b8", "f": 20}` (20 tenths-of-bps = 2 bps)
- The fee is collected in the quote/collateral asset (USDC) and accumulates in the builder's referral rewards
- Users can revoke approval at any time on app.hyperliquid.xyz
**Tools:**
- `hl_approve_builder` — Manually approve the Starchild builder (normally auto-done on first order)
- `hl_builder_status` — Check approval status and view unclaimed builder rewards
**If builder approval fails:** Orders still go through without the builder parameter. The error is logged but does not block trading.
---
## Common Errors
| Error | Fix |
|-------|-----|
| "Unknown perp asset" | Check coin name. Crypto: "BTC", "ETH". Stocks: "xyz:NVDA", "xyz:TSLA" |
| "Insufficient margin" | Use `hl_total_balance` to check funds. Reduce size or add more USDC |
| "Order must have minimum value of $10" | Increase size. Formula: `size × price ≥ $10` |
| "Size too small" | BTC min is typically 0.001. Check asset's szDecimals |
| "Order would cross" | ALO order rejected. Use regular limit order instead |
| "User or wallet does not exist" | Deposit USDC first with `hl_deposit(amount=500)` |
| "Minimum deposit is 5 USDC" | Hyperliquid requires at least $5 per deposit |
| "Policy violation" | Load wallet-policy skill and propose wildcard policy |
| "Action disabled when unified account is active" | Transfers blocked in unified mode (default). Just place orders directly |
| "'side' must be one of: buy/sell ..." | You passed an unrecognized direction. Use `"buy"` or `"sell"`. See **Side Parameter Convention** above |
tools.py
"""
Hyperliquid Trading Tools — BaseTool subclasses for agent use.
Info tools (9): hl_account, hl_balances, hl_total_balance, hl_open_orders, hl_market,
hl_orderbook, hl_fills, hl_candles, hl_funding
Exchange tools (10): hl_order, hl_spot_order, hl_cancel, hl_cancel_all,
hl_modify, hl_leverage, hl_transfer_usd, hl_withdraw, hl_deposit,
hl_set_abstraction
"""
import time
import math
import logging
from core.tool import BaseTool, ToolContext, ToolResult
from .client import HyperliquidClient
logger = logging.getLogger(__name__)
# Module-level shared client instance
_client: HyperliquidClient = None
def _get_client() -> HyperliquidClient:
global _client
if _client is None:
_client = HyperliquidClient()
return _client
async def _get_address() -> str:
"""Get the agent's EVM address."""
return await _get_client()._get_address()
def _coerce_float(value, field_name: str):
"""Best-effort numeric coercion for tolerant tool inputs."""
if isinstance(value, bool) or value is None:
raise ValueError(f"'{field_name}' must be a number")
if isinstance(value, (int, float)):
f = float(value)
elif isinstance(value, str):
s = value.strip()
if not s:
raise ValueError(f"'{field_name}' must be a number")
try:
f = float(s)
except ValueError:
raise ValueError(f"'{field_name}' must be a number")
else:
raise ValueError(f"'{field_name}' must be a number")
if not math.isfinite(f):
raise ValueError(f"'{field_name}' must be a finite number")
return f
def _coerce_int(value, field_name: str):
"""Best-effort integer coercion with strict decimal rejection."""
if isinstance(value, bool) or value is None:
raise ValueError(f"'{field_name}' must be an integer")
if isinstance(value, int):
return value
if isinstance(value, float):
if value.is_integer() and math.isfinite(value):
return int(value)
raise ValueError(f"'{field_name}' must be an integer")
if isinstance(value, str):
s = value.strip()
if not s:
raise ValueError(f"'{field_name}' must be an integer")
if s.lstrip("+-").isdigit():
return int(s)
# allow "5.0" but reject "5.1"
try:
f = float(s)
if math.isfinite(f) and f.is_integer():
return int(f)
except ValueError:
pass
raise ValueError(f"'{field_name}' must be an integer")
def _coerce_bool(value, field_name: str):
"""Best-effort boolean coercion."""
if isinstance(value, bool):
return value
if isinstance(value, (int, float)) and value in (0, 1):
return bool(value)
if isinstance(value, str):
lowered = value.strip().lower()
if lowered in {"true", "1", "yes", "y", "on"}:
return True
if lowered in {"false", "0", "no", "n", "off"}:
return False
raise ValueError(f"'{field_name}' must be a boolean")
# Accepted aliases for the `side` parameter across all Hyperliquid order tools.
# Some models emit Hyperliquid's L1 wire codes (B/A) or natural-language
# directions (long/short, 做多/做空) instead of the documented buy/sell.
# Normalizing here is safer than silently falling back to sell when the input
# doesn't match the literal "buy" — accidental direction reversal on a
# leveraged order is the worst failure mode we can produce.
_SIDE_BUY_ALIASES = frozenset({
"buy", "b", "bid", "long", "l", "做多",
"1", "true", # some models stringify booleans when unsure
})
_SIDE_SELL_ALIASES = frozenset({
"sell", "s", "a", "ask", "short", "做空",
"0", "false",
})
def _coerce_side(value, field_name: str = "side") -> bool:
"""Normalize a `side` parameter into a boolean ``is_buy``.
Accepts the documented ``buy``/``sell`` plus common aliases that models
reach for when they guess:
- Buy family: buy, B, bid, long, L, 做多, 1, true
- Sell family: sell, S, A, ask, short, 做空, 0, false
Also accepts a real ``bool`` (True → buy, False → sell) — some tool
runtimes pre-coerce boolean-looking strings.
Raises ``ValueError`` for anything else. NEVER falls back to a default —
on a leveraged order, guessing the wrong direction is catastrophic.
"""
# Pre-coerced boolean from the tool runtime or an explicit caller.
if isinstance(value, bool):
return value
if value is None:
raise ValueError(f"'{field_name}' is required (one of: buy, sell)")
if isinstance(value, (int, float)) and not isinstance(value, bool):
if value == 1:
return True
if value == 0:
return False
raise ValueError(
f"'{field_name}' numeric must be 1 (buy) or 0 (sell); got {value!r}"
)
if isinstance(value, str):
s = value.strip().lower()
if not s:
raise ValueError(f"'{field_name}' is required (one of: buy, sell)")
if s in _SIDE_BUY_ALIASES:
return True
if s in _SIDE_SELL_ALIASES:
return False
raise ValueError(
f"'{field_name}' must be one of: buy/sell (also accepted: "
f"B/A, long/short, 做多/做空); got {value!r}"
)
raise ValueError(
f"'{field_name}' must be a string like 'buy' or 'sell'; "
f"got {type(value).__name__}"
)
# ── Info Tools ───────────────────────────────────────────────────────────────
class HLAccountTool(BaseTool):
"""Get perp account state — positions, margin, PnL."""
@property
def name(self) -> str:
return "hl_account"
@property
def description(self) -> str:
return """Get Hyperliquid perpetual account state: open positions, margin balances, unrealized PnL, and account value.
**⚠️ WARNING: This tool shows PERP account only! With unified account mode (default), your funds may be in SPOT.**
**🎯 Use `hl_total_balance` instead to check if you have funds to place orders!**
**Understanding account modes:**
- **Unified Account (default)**: Funds are shared across spot/perp. This tool may show $0 even if you have USDC in spot!
- **Disabled mode**: Spot and perp are separate. This tool accurately shows perp margin.
**When to use this tool:**
- To check open positions and their PnL
- To see margin usage on perp side
- To monitor position sizes and liquidation risk
- NOT to check if you have funds to place orders (use `hl_total_balance` for that!)
**🚨 CRITICAL for RWA/Stock Perps (xyz:NVDA, xyz:TSLA, etc.):**
- ✅ Check MAIN account (`hl_account()`) for positions, NOT for available funds
- ❌ DO NOT check xyz dex (`hl_account(dex="xyz")`) before placing orders - it shows $0 until you have positions!
- ✅ xyz dex showing $0 is NORMAL and EXPECTED before your first builder perp order
- ✅ DEX abstraction auto-transfers funds from main → xyz dex when you place orders
- ✅ Only check xyz dex AFTER placing orders to verify positions opened
Parameters:
- dex: (optional) Builder dex name (e.g. "xyz"). Omit for main crypto perps account.
Returns: marginSummary (accountValue, totalMarginUsed, totalNtlPos), assetPositions array"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"dex": {
"type": "string",
"description": "Builder dex name (e.g. 'xyz') for RWA/stock perps. Omit for default crypto perps.",
},
},
}
async def execute(self, ctx: ToolContext, dex: str = "", **kwargs) -> ToolResult:
try:
client = _get_client()
address = await _get_address()
data = await client.get_account_state(address, dex=dex if dex else None)
return ToolResult(success=True, output=data)
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLBalancesTool(BaseTool):
"""Get spot token balances (USDC, tokens)."""
@property
def name(self) -> str:
return "hl_balances"
@property
def description(self) -> str:
return """Get Hyperliquid spot balances: USDC and all token holdings.
**⚠️ WARNING: This tool shows SPOT account only!**
**🎯 Use `hl_total_balance` to check total available funds for trading!**
**Understanding account modes:**
- **Unified Account (default)**: SPOT USDC is shared collateral for all trading (spot/perp/builder-dexes)
- **Disabled mode**: Spot and perp are separate, you may need to transfer between them
**When to use this tool:**
- To check spot token holdings (e.g. PURR, HYPE, etc.)
- To see USDC available for spot trading
- NOT as the sole indicator of available margin (use `hl_total_balance` for that!)
Returns: balances array with coin, hold, total for each token"""
@property
def parameters(self) -> dict:
return {"type": "object", "properties": {}}
async def execute(self, ctx: ToolContext, **kwargs) -> ToolResult:
try:
client = _get_client()
address = await _get_address()
data = await client.get_spot_state(address)
return ToolResult(success=True, output=data)
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLTotalBalanceTool(BaseTool):
"""Get total available balance (accounts for unified account mode)."""
@property
def name(self) -> str:
return "hl_total_balance"
@property
def description(self) -> str:
return """Get total available balance across all Hyperliquid accounts.
**🎯 Use this to check if you have enough funds to place orders!**
This tool intelligently checks the RIGHT account based on your abstraction mode:
- **Unified Account Mode (default)**: Returns SPOT balance (shared collateral for all trading)
- **Disabled Mode**: Returns PERP balance separately
**Why use this instead of hl_account or hl_balances?**
- hl_account shows perp only ($0 if funds are in spot with unified account)
- hl_balances shows spot only
- hl_total_balance shows ACTUAL available margin regardless of mode
Returns:
- totalAvailable: Total USDC available for trading
- abstractionMode: Current mode (unifiedAccount, disabled, etc.)
- breakdown: Where the funds actually are (spot/perp)"""
@property
def parameters(self) -> dict:
return {"type": "object", "properties": {}}
async def execute(self, ctx: ToolContext, **kwargs) -> ToolResult:
try:
client = _get_client()
address = await _get_address()
# Check abstraction mode
try:
abstraction_result = await client.get_user_abstraction_state(address)
if isinstance(abstraction_result, str):
abstraction_mode = abstraction_result
elif isinstance(abstraction_result, dict):
abstraction_mode = abstraction_result.get("type", abstraction_result.get("state", "default"))
else:
abstraction_mode = "default"
except Exception:
abstraction_mode = "default"
# Get spot and perp balances
spot_state = await client.get_spot_state(address)
perp_state = await client.get_account_state(address)
# Calculate spot USDC
spot_usdc = 0.0
for bal in spot_state.get("balances", []):
if bal.get("coin") == "USDC":
spot_usdc = float(bal.get("total", 0))
break
# Calculate perp margin
perp_margin = perp_state.get("marginSummary", {})
perp_value = float(perp_margin.get("accountValue", 0))
perp_used = float(perp_margin.get("totalMarginUsed", 0))
perp_available = perp_value - perp_used
# Determine total available based on mode
if abstraction_mode == "unifiedAccount":
# Unified mode: all USDC is shared collateral
total_available = spot_usdc + perp_available
note = "Unified account: funds are shared across spot/perp/builder-dexes"
else:
# Separate mode: perp and spot are independent
total_available = perp_available
note = "Disabled mode: perp and spot are separate"
return ToolResult(
success=True,
output={
"totalAvailable": round(total_available, 2),
"abstractionMode": abstraction_mode,
"note": note,
"breakdown": {
"spot": {
"usdc": round(spot_usdc, 2),
},
"perp": {
"accountValue": round(perp_value, 2),
"marginUsed": round(perp_used, 2),
"available": round(perp_available, 2),
},
},
},
)
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLOpenOrdersTool(BaseTool):
"""Get all open orders (perp + spot)."""
@property
def name(self) -> str:
return "hl_open_orders"
@property
def description(self) -> str:
return """Get all open orders on Hyperliquid (both perp and spot).
Use this to see pending limit orders, check order status, or find order IDs for cancellation.
Returns: array of orders with coin, side, sz, limitPx, oid, timestamp"""
@property
def parameters(self) -> dict:
return {"type": "object", "properties": {}}
async def execute(self, ctx: ToolContext, **kwargs) -> ToolResult:
try:
client = _get_client()
address = await _get_address()
data = await client.get_open_orders(address)
return ToolResult(success=True, output=data)
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLMarketTool(BaseTool):
"""Get market info — mid prices, metadata."""
@property
def name(self) -> str:
return "hl_market"
@property
def description(self) -> str:
return """Get Hyperliquid market info: current mid prices and asset metadata.
If coin is specified, returns targeted info for that asset. Otherwise returns all mid prices.
**Crypto perps**: Use plain names — "BTC", "ETH", "SOL", etc.
**RWA / stocks / commodities**: Use "xyz:TICKER" format — "xyz:NVDA", "xyz:TSLA", "xyz:AAPL", "xyz:GOLD", "xyz:SILVER", etc.
Use dex="xyz" to list all available RWA/stock perps.
Parameters:
- coin: (optional) Specific asset like "BTC", "ETH", "xyz:NVDA". Omit for all crypto perps.
- dex: (optional) Builder dex name like "xyz" to list all assets on that dex (stocks/RWAs).
Returns: mid prices, and if coin specified: maxLeverage, szDecimals"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Asset name (e.g. 'BTC', 'xyz:NVDA'). Omit for all.",
},
"dex": {
"type": "string",
"description": "Builder dex name (e.g. 'xyz') to list all RWA/stock perps on that dex.",
},
},
}
async def execute(self, ctx: ToolContext, coin: str = "", dex: str = "", **kwargs) -> ToolResult:
try:
client = _get_client()
# List all assets on a builder dex (e.g. dex="xyz" for RWA/stocks)
if dex and not coin:
await client._ensure_meta()
await client._ensure_builder_dex(dex)
mids = await client.get_all_mids(dex=dex)
return ToolResult(success=True, output=mids)
if coin and ":" in coin:
# Builder perp (e.g. "xyz:NVDA")
dex_name = coin.split(":", 1)[0]
await client._ensure_meta()
await client._ensure_builder_dex(dex_name)
mids = await client.get_all_mids(dex=dex_name)
# allMids keys are prefixed: "xyz:NVDA"
mid = mids.get(coin)
if mid is None:
return ToolResult(
success=False,
error=f"No mid price for {coin}. Available: {list(mids.keys())[:10]}",
)
meta = client._builder_meta.get(dex_name, {})
universe = meta.get("universe", [])
asset_info = {}
for asset in universe:
# meta returns names like "xyz:NVDA" (prefixed)
if asset["name"] == coin or asset["name"] == coin.split(":", 1)[1]:
asset_info = asset
break
return ToolResult(
success=True,
output={
"coin": coin,
"dex": dex_name,
"midPrice": mid,
"maxLeverage": asset_info.get("maxLeverage"),
"szDecimals": asset_info.get("szDecimals"),
},
)
mids = await client.get_all_mids()
if coin:
mid = mids.get(coin)
# Case-insensitive fallback (e.g. "ai16z" -> "AI16Z")
if mid is None:
coin_upper = coin.upper()
for key, val in mids.items():
if key.upper() == coin_upper:
coin = key # Use the canonical name
mid = val
break
if mid is None:
return ToolResult(
success=False,
error=f"No data for {coin}. If this is a stock/RWA, use 'xyz:{coin}' format (e.g. 'xyz:NVDA'). Use hl_market(dex=\"xyz\") to list all available RWA/stock perps.",
)
await client._ensure_meta()
meta = client._meta or {}
universe = meta.get("universe", [])
asset_info = {}
for asset in universe:
if asset["name"] == coin:
asset_info = asset
break
return ToolResult(
success=True,
output={
"coin": coin,
"midPrice": mid,
"maxLeverage": asset_info.get("maxLeverage"),
"szDecimals": asset_info.get("szDecimals"),
},
)
return ToolResult(success=True, output=mids)
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLOrderbookTool(BaseTool):
"""Get L2 orderbook snapshot."""
@property
def name(self) -> str:
return "hl_orderbook"
@property
def description(self) -> str:
return """Get the L2 orderbook for a Hyperliquid asset.
Shows current bid/ask levels with sizes. Useful for checking liquidity and spread.
Supports builder perps via "dex:COIN" format (e.g. "xyz:NVDA").
Parameters:
- coin: Asset name (required, e.g. "BTC", "ETH", "xyz:NVDA")
Returns: levels array with [[price, size], ...] for bids and asks"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Asset name (e.g. 'BTC', 'xyz:NVDA')",
},
},
"required": ["coin"],
}
async def execute(self, ctx: ToolContext, coin: str = "", **kwargs) -> ToolResult:
if not coin:
return ToolResult(success=False, error="'coin' is required")
try:
client = _get_client()
data = await client.get_l2_book(coin)
return ToolResult(success=True, output=data)
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLFillsTool(BaseTool):
"""Get recent trade fills."""
@property
def name(self) -> str:
return "hl_fills"
@property
def description(self) -> str:
return """Get recent trade fills (executed orders) for this wallet.
Use this to verify if orders were filled, check execution prices, or review trade history.
Parameters:
- limit: Number of fills to return (default: 20)
Returns: array of fills with coin, side, px, sz, fee, time"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"limit": {
"type": "integer",
"description": "Number of fills (default: 20)",
},
},
}
async def execute(self, ctx: ToolContext, limit: int = 20, **kwargs) -> ToolResult:
try:
client = _get_client()
address = await _get_address()
fills = await client.get_user_fills(address)
return ToolResult(success=True, output=fills[:limit])
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLCandlesTool(BaseTool):
"""Get OHLCV candlestick data."""
@property
def name(self) -> str:
return "hl_candles"
@property
def description(self) -> str:
return """Get OHLCV candlestick data for a Hyperliquid asset.
Use this for price analysis, charting, and identifying trends.
Parameters:
- coin: Asset name (required, e.g. "BTC")
- interval: Candle interval (default: "1h"). Options: 1m, 5m, 15m, 1h, 4h, 1d
- lookback: Hours of history to fetch (default: 24)
Returns: array of candles with t (time), o, h, l, c (prices), v (volume)"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Asset name (e.g. 'BTC')",
},
"interval": {
"type": "string",
"description": "Candle interval: 1m, 5m, 15m, 1h, 4h, 1d (default: 1h)",
},
"lookback": {
"type": "integer",
"description": "Hours of history (default: 24)",
},
},
"required": ["coin"],
}
async def execute(
self,
ctx: ToolContext,
coin: str = "",
interval: str = "1h",
lookback: int = 24,
**kwargs,
) -> ToolResult:
if not coin:
return ToolResult(success=False, error="'coin' is required")
try:
client = _get_client()
end = int(time.time() * 1000)
start = end - (lookback * 3600 * 1000)
data = await client.get_candles(coin, interval, start, end)
return ToolResult(success=True, output=data)
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLFundingTool(BaseTool):
"""Get funding rate info."""
@property
def name(self) -> str:
return "hl_funding"
@property
def description(self) -> str:
return """Get funding rate information for Hyperliquid perps.
Shows predicted next funding and recent historical funding rates. Positive = longs pay shorts.
Parameters:
- coin: (optional) Specific asset. Omit for all predicted fundings.
- lookback: Hours of funding history (default: 24, only used if coin specified)
Returns: predicted funding rates, and if coin specified: historical rates"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Asset name (e.g. 'BTC'). Omit for all.",
},
"lookback": {
"type": "integer",
"description": "Hours of history (default: 24)",
},
},
}
async def execute(
self, ctx: ToolContext, coin: str = "", lookback: int = 24, **kwargs
) -> ToolResult:
try:
client = _get_client()
predicted = await client.get_predicted_fundings()
if coin:
# predictedFundings returns [[coin, [[venue, data], ...]], ...]
coin_predicted = None
for entry in predicted:
if isinstance(entry, list) and len(entry) >= 2 and entry[0] == coin:
# entry[1] is [[venue, {fundingRate, ...}], ...]
coin_predicted = {
venue: data
for venue, data in entry[1]
}
break
# Fetch historical
start = int((time.time() - lookback * 3600) * 1000)
history = await client.get_funding_history(coin, start)
return ToolResult(
success=True,
output={
"coin": coin,
"predicted": coin_predicted or "No predicted funding found",
"history": history,
},
)
# Summarize all predicted fundings into a readable dict
summary = {}
for entry in predicted:
if isinstance(entry, list) and len(entry) >= 2:
name = entry[0]
venues = entry[1]
# Pick HlPerp rate if available, otherwise first venue
for venue, data in venues:
if venue == "HlPerp":
summary[name] = data.get("fundingRate", "N/A")
break
else:
if venues:
summary[name] = venues[0][1].get("fundingRate", "N/A")
return ToolResult(success=True, output={"predicted": summary})
except Exception as e:
return ToolResult(success=False, error=str(e))
# ── Exchange Tools ───────────────────────────────────────────────────────────
class HLOrderTool(BaseTool):
"""Place a perp limit or market order."""
@property
def name(self) -> str:
return "hl_order"
@property
def description(self) -> str:
return """Place a perpetual futures order on Hyperliquid.
**Crypto**: Use plain names — "BTC", "ETH", "SOL"
**Stocks/RWA**: Use "xyz:TICKER" — "xyz:NVDA", "xyz:TSLA", "xyz:AAPL", "xyz:GOLD"
Parameters:
- coin: Asset name (required, e.g. "BTC", "ETH", "xyz:NVDA")
- side: Direction. **Use "buy" or "sell"** — these are the documented values.
Aliases are also accepted as a safety net (B/A, long/short, 做多/做空)
but "buy"/"sell" is strongly preferred for clarity and auditability.
An unrecognized value will FAIL the call rather than default, to
prevent accidental direction reversal on leveraged orders.
- size: Order size in base asset (required, e.g. 0.01 for 0.01 BTC)
- price: Limit price (optional — omit for market order)
- order_type: "limit" (GTC, default), "ioc" (fill-or-kill), "alo" (post-only)
- reduce_only: If true, only reduces existing position (default: false)
Market orders (no price): Uses IoC at mid price +/- 3% slippage.
Returns: order status with oid, filled size, price"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Asset name (e.g. 'BTC', 'xyz:NVDA')",
},
"side": {
"type": "string",
"enum": ["buy", "sell"],
"description": "Order side",
},
"size": {
"type": "number",
"description": "Order size in base asset",
},
"price": {
"type": "number",
"description": "Limit price (omit for market order)",
},
"order_type": {
"type": "string",
"enum": ["limit", "ioc", "alo"],
"description": "Order type (default: limit)",
},
"reduce_only": {
"type": "boolean",
"description": "Reduce-only (default: false)",
},
},
"required": ["coin", "side", "size"],
}
async def execute(
self,
ctx: ToolContext,
coin: str = "",
side: str = "",
size: float = 0,
price: float = None,
order_type: str = "limit",
reduce_only: bool = False,
**kwargs,
) -> ToolResult:
try:
if not coin or not side:
return ToolResult(success=False, error="'coin' and 'side' are required")
size = _coerce_float(size, "size")
if size <= 0:
return ToolResult(success=False, error="'size' must be positive")
if price is not None:
price = _coerce_float(price, "price")
if price <= 0:
return ToolResult(success=False, error="'price' must be positive when provided")
reduce_only = _coerce_bool(reduce_only, "reduce_only")
if isinstance(order_type, str):
order_type = order_type.strip().lower() or "limit"
if order_type not in {"limit", "ioc", "alo"}:
return ToolResult(success=False, error="'order_type' must be one of: limit, ioc, alo")
is_buy = _coerce_side(side)
logger.info(
"hl_order: coin=%s side_raw=%r → is_buy=%s size=%s price=%s "
"order_type=%s reduce_only=%s",
coin, side, is_buy, size, price, order_type, reduce_only,
)
client = _get_client()
data = await client.place_order(
coin=coin,
is_buy=is_buy,
size=size,
price=price,
order_type=order_type,
reduce_only=reduce_only,
)
return ToolResult(success=True, output=data)
except ValueError as e:
return ToolResult(success=False, error=str(e))
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLSpotOrderTool(BaseTool):
"""Place a spot limit or market order."""
@property
def name(self) -> str:
return "hl_spot_order"
@property
def description(self) -> str:
return """Place a spot order on Hyperliquid.
Parameters:
- coin: Token name (required, e.g. "PURR", "HYPE")
- side: Direction. **Use "buy" or "sell"** — these are the documented values.
Aliases accepted (B/A, long/short, 做多/做空) but "buy"/"sell" is
preferred. Unknown values FAIL rather than default.
- size: Order size in base token (required)
- price: Limit price (optional — omit for market order)
- order_type: "limit" (GTC, default), "ioc" (fill-or-kill), "alo" (post-only)
Market orders (no price): Uses IoC at mid price +/- 3% slippage.
Returns: order status with oid, filled size, price"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Token name (e.g. 'PURR', 'HYPE')",
},
"side": {
"type": "string",
"enum": ["buy", "sell"],
"description": "Order side",
},
"size": {
"type": "number",
"description": "Order size in base token",
},
"price": {
"type": "number",
"description": "Limit price (omit for market order)",
},
"order_type": {
"type": "string",
"enum": ["limit", "ioc", "alo"],
"description": "Order type (default: limit)",
},
},
"required": ["coin", "side", "size"],
}
async def execute(
self,
ctx: ToolContext,
coin: str = "",
side: str = "",
size: float = 0,
price: float = None,
order_type: str = "limit",
**kwargs,
) -> ToolResult:
try:
if not coin or not side:
return ToolResult(success=False, error="'coin' and 'side' are required")
size = _coerce_float(size, "size")
if size <= 0:
return ToolResult(success=False, error="'size' must be positive")
if price is not None:
price = _coerce_float(price, "price")
if price <= 0:
return ToolResult(success=False, error="'price' must be positive when provided")
if isinstance(order_type, str):
order_type = order_type.strip().lower() or "limit"
if order_type not in {"limit", "ioc", "alo"}:
return ToolResult(success=False, error="'order_type' must be one of: limit, ioc, alo")
is_buy = _coerce_side(side)
logger.info(
"hl_spot_order: coin=%s side_raw=%r → is_buy=%s size=%s price=%s "
"order_type=%s",
coin, side, is_buy, size, price, order_type,
)
client = _get_client()
data = await client.place_order(
coin=coin,
is_buy=is_buy,
size=size,
price=price,
order_type=order_type,
is_spot=True,
)
return ToolResult(success=True, output=data)
except ValueError as e:
return ToolResult(success=False, error=str(e))
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLTPSLOrderTool(BaseTool):
"""Place a stop loss or take profit order."""
@property
def name(self) -> str:
return "hl_tpsl_order"
@property
def description(self) -> str:
return """Place a stop loss or take profit order on Hyperliquid.
**Stop Loss**: Automatically sell when price drops to a trigger level to limit losses.
**Take Profit**: Automatically sell when price rises to a trigger level to lock in gains.
**Crypto**: Use plain names — "BTC", "ETH", "SOL"
**Stocks/RWA**: Use "xyz:TICKER" — "xyz:NVDA", "xyz:TSLA", "xyz:GOLD"
Parameters:
- coin: Asset name (required, e.g. "BTC", "ETH", "xyz:NVDA")
- side: Direction to close the position. **Use "buy" or "sell"** — these are
the documented values. For a long position, use "sell" to close; for a
short, use "buy". Aliases accepted (B/A, long/short, 做多/做空) but
"buy"/"sell" is preferred. Unknown values FAIL rather than default.
- size: Order size in base asset (required, e.g. 0.01 for 0.01 BTC)
- trigger_px: Price that triggers the order (required)
- tpsl: "tp" for take profit, "sl" for stop loss (required)
- is_market: If true, execute as market order when triggered. If false, use limit_px. (default: true)
- limit_px: Limit price for the order when it triggers (optional, only used if is_market=false)
- reduce_only: If true, only reduces existing position (default: true)
**How it works:**
1. Order sits dormant until market price reaches trigger_px
2. When triggered, executes immediately as market order (or limit if is_market=false)
3. Use reduce_only=true to ensure it only closes positions (recommended for TP/SL)
**Examples:**
- Stop loss: If you're long BTC at $95k and want to exit if it drops to $90k:
`hl_tpsl_order(coin="BTC", side="sell", size=0.1, trigger_px=90000, tpsl="sl")`
- Take profit: If you're long ETH and want to take profit at $3500:
`hl_tpsl_order(coin="ETH", side="sell", size=1.0, trigger_px=3500, tpsl="tp")`
Returns: order status with oid, trigger details"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Asset name (e.g. 'BTC', 'xyz:NVDA')",
},
"side": {
"type": "string",
"enum": ["buy", "sell"],
"description": "Order side (usually opposite of your position)",
},
"size": {
"type": "number",
"description": "Order size in base asset",
},
"trigger_px": {
"type": "number",
"description": "Price that triggers the order",
},
"tpsl": {
"type": "string",
"enum": ["tp", "sl"],
"description": "Order type: 'tp' for take profit, 'sl' for stop loss",
},
"is_market": {
"type": "boolean",
"description": "Execute as market order when triggered (default: true)",
},
"limit_px": {
"type": "number",
"description": "Limit price when triggered (only if is_market=false)",
},
"reduce_only": {
"type": "boolean",
"description": "Only reduce position, don't open new (default: true)",
},
},
"required": ["coin", "side", "size", "trigger_px", "tpsl"],
}
async def execute(
self,
ctx: ToolContext,
coin: str = "",
side: str = "",
size: float = 0,
trigger_px: float = 0,
tpsl: str = "",
is_market: bool = True,
limit_px: float = None,
reduce_only: bool = True,
**kwargs,
) -> ToolResult:
try:
if not coin or not side or not tpsl:
return ToolResult(
success=False,
error="'coin', 'side', and 'tpsl' are required",
)
size = _coerce_float(size, "size")
trigger_px = _coerce_float(trigger_px, "trigger_px")
if size <= 0:
return ToolResult(success=False, error="'size' must be positive")
if trigger_px <= 0:
return ToolResult(success=False, error="'trigger_px' must be positive")
is_market = _coerce_bool(is_market, "is_market")
reduce_only = _coerce_bool(reduce_only, "reduce_only")
if isinstance(tpsl, str):
tpsl = tpsl.strip().lower()
if tpsl not in ("tp", "sl"):
return ToolResult(
success=False,
error="'tpsl' must be either 'tp' (take profit) or 'sl' (stop loss)",
)
if limit_px is not None:
limit_px = _coerce_float(limit_px, "limit_px")
if limit_px <= 0:
return ToolResult(success=False, error="'limit_px' must be positive when provided")
is_buy = _coerce_side(side)
# For trigger orders: always pass a limit price
# - For market triggers: use the trigger price as limit (matches SDK)
# - For limit triggers: use the specified limit price
price = trigger_px if is_market else (limit_px or trigger_px)
logger.info(
"hl_tpsl_order: coin=%s side_raw=%r → is_buy=%s tpsl=%s "
"size=%s trigger_px=%s is_market=%s reduce_only=%s",
coin, side, is_buy, tpsl, size, trigger_px, is_market, reduce_only,
)
client = _get_client()
data = await client.place_order(
coin=coin,
is_buy=is_buy,
size=size,
price=price,
reduce_only=reduce_only,
trigger_px=trigger_px,
tpsl=tpsl,
)
return ToolResult(success=True, output=data)
except ValueError as e:
return ToolResult(success=False, error=str(e))
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLCancelTool(BaseTool):
"""Cancel an order (perp or spot)."""
@property
def name(self) -> str:
return "hl_cancel"
@property
def description(self) -> str:
return """Cancel an open order on Hyperliquid by order ID.
Parameters:
- coin: Asset name (required, e.g. "BTC", "xyz:NVDA")
- order_id: Order ID to cancel (required — get from hl_open_orders)
Returns: cancel confirmation"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Asset name (e.g. 'BTC', 'xyz:NVDA')",
},
"order_id": {
"type": "integer",
"description": "Order ID (oid) to cancel",
},
},
"required": ["coin", "order_id"],
}
async def execute(
self, ctx: ToolContext, coin: str = "", order_id: int = 0, **kwargs
) -> ToolResult:
try:
if not coin:
return ToolResult(success=False, error="'coin' is required")
order_id = _coerce_int(order_id, "order_id")
if order_id <= 0:
return ToolResult(success=False, error="'order_id' must be positive")
client = _get_client()
data = await client.cancel_order(coin, order_id)
return ToolResult(success=True, output=data)
except ValueError as e:
return ToolResult(success=False, error=str(e))
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLCancelAllTool(BaseTool):
"""Cancel all open orders."""
@property
def name(self) -> str:
return "hl_cancel_all"
@property
def description(self) -> str:
return """Cancel all open orders on Hyperliquid.
Parameters:
- coin: (optional) Asset name to cancel orders for. Omit to cancel ALL orders.
Returns: array of cancel results"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Asset name (optional — omit for all)",
},
},
}
async def execute(self, ctx: ToolContext, coin: str = "", **kwargs) -> ToolResult:
try:
client = _get_client()
results = await client.cancel_all(coin or None)
return ToolResult(
success=True,
output={
"cancelled": len(results),
"results": results,
},
)
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLModifyTool(BaseTool):
"""Modify an existing order."""
@property
def name(self) -> str:
return "hl_modify"
@property
def description(self) -> str:
return """Modify an existing order on Hyperliquid (change price or size).
Parameters:
- order_id: Order ID to modify (required)
- coin: Asset name (required, e.g. "BTC", "xyz:NVDA")
- side: Direction. **Use "buy" or "sell"** — these are the documented values.
Aliases accepted (B/A, long/short, 做多/做空) but "buy"/"sell" is
preferred. Unknown values FAIL rather than default.
- size: New size (required)
- price: New price (required)
Returns: modified order confirmation"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"order_id": {
"type": "integer",
"description": "Order ID to modify",
},
"coin": {
"type": "string",
"description": "Asset name (e.g. 'BTC', 'xyz:NVDA')",
},
"side": {
"type": "string",
"enum": ["buy", "sell"],
"description": "Order side",
},
"size": {
"type": "number",
"description": "New order size",
},
"price": {
"type": "number",
"description": "New limit price",
},
},
"required": ["order_id", "coin", "side", "size", "price"],
}
async def execute(
self,
ctx: ToolContext,
order_id: int = 0,
coin: str = "",
side: str = "",
size: float = 0,
price: float = 0,
**kwargs,
) -> ToolResult:
try:
if not coin or not side:
return ToolResult(
success=False,
error="'coin' and 'side' are required",
)
order_id = _coerce_int(order_id, "order_id")
size = _coerce_float(size, "size")
price = _coerce_float(price, "price")
if order_id <= 0:
return ToolResult(success=False, error="'order_id' must be positive")
if size <= 0:
return ToolResult(success=False, error="'size' must be positive")
if price <= 0:
return ToolResult(success=False, error="'price' must be positive")
is_buy = _coerce_side(side)
logger.info(
"hl_modify: order_id=%s coin=%s side_raw=%r → is_buy=%s "
"size=%s price=%s",
order_id, coin, side, is_buy, size, price,
)
client = _get_client()
data = await client.modify_order(
oid=order_id,
coin=coin,
is_buy=is_buy,
size=size,
price=price,
)
return ToolResult(success=True, output=data)
except ValueError as e:
return ToolResult(success=False, error=str(e))
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLLeverageTool(BaseTool):
"""Set leverage for a perp."""
@property
def name(self) -> str:
return "hl_leverage"
@property
def description(self) -> str:
return """Set leverage for a Hyperliquid perpetual asset.
Parameters:
- coin: Asset name (required, e.g. "BTC", "xyz:NVDA")
- leverage: Leverage multiplier (required, e.g. 5 for 5x)
- cross: If true, use cross margin. If false, use isolated margin. (default: true)
Returns: leverage update confirmation"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"coin": {
"type": "string",
"description": "Asset name (e.g. 'BTC', 'xyz:NVDA')",
},
"leverage": {
"type": "integer",
"description": "Leverage multiplier (e.g. 5)",
},
"cross": {
"type": "boolean",
"description": "Cross margin (default: true)",
},
},
"required": ["coin", "leverage"],
}
async def execute(
self,
ctx: ToolContext,
coin: str = "",
leverage: int = 0,
cross: bool = True,
**kwargs,
) -> ToolResult:
try:
if not coin:
return ToolResult(success=False, error="'coin' is required")
leverage = _coerce_int(leverage, "leverage")
cross = _coerce_bool(cross, "cross")
if leverage <= 0:
return ToolResult(success=False, error="'leverage' must be positive")
client = _get_client()
# Builder perps (HIP-3) require isolated margin
if ":" in coin:
cross = False
data = await client.update_leverage(coin, leverage, is_cross=cross)
return ToolResult(success=True, output=data)
except ValueError as e:
return ToolResult(success=False, error=str(e))
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLTransferUsdTool(BaseTool):
"""Transfer USDC between spot and perp."""
@property
def name(self) -> str:
return "hl_transfer_usd"
@property
def description(self) -> str:
return """Transfer USDC between Hyperliquid spot and perp accounts.
**⚠️ IMPORTANT: This will FAIL if unified account mode is active!**
Unified account mode (default) shares funds automatically - manual transfers are disabled.
If you get "Action disabled when unified account is active", this is expected behavior.
**When to use:**
- Only when unified account is DISABLED
- To manually move USDC between spot ↔ perp
- Not needed when unified account is active (funds are already shared!)
**To check your mode:** Use `hl_total_balance` - it shows the current abstraction mode
Parameters:
- amount: USDC amount to transfer (required, e.g. 100.0)
- to_perp: If true, transfer from spot to perp. If false, from perp to spot. (default: true)
Returns: transfer confirmation"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"amount": {
"type": "number",
"description": "USDC amount to transfer",
},
"to_perp": {
"type": "boolean",
"description": "True = spot→perp, False = perp→spot (default: true)",
},
},
"required": ["amount"],
}
async def execute(
self, ctx: ToolContext, amount: float = 0, to_perp: bool = True, **kwargs
) -> ToolResult:
try:
amount = _coerce_float(amount, "amount")
to_perp = _coerce_bool(to_perp, "to_perp")
if amount <= 0:
return ToolResult(success=False, error="'amount' must be positive")
client = _get_client()
data = await client.transfer_usd(amount, to_perp=to_perp)
return ToolResult(success=True, output=data)
except ValueError as e:
return ToolResult(success=False, error=str(e))
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLWithdrawTool(BaseTool):
"""Withdraw USDC from Hyperliquid to Arbitrum wallet."""
@property
def name(self) -> str:
return "hl_withdraw"
@property
def description(self) -> str:
return """Withdraw USDC from Hyperliquid to an Arbitrum wallet (L1 bridge withdrawal).
Fee: 1 USDC (deducted by Hyperliquid). Processing time: ~5 minutes.
Parameters:
- amount: USDC amount to withdraw (required, e.g. 100.0)
- destination: Target wallet address (optional — defaults to this agent's own wallet)
Returns: withdrawal confirmation"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"amount": {
"type": "number",
"description": "USDC amount to withdraw",
},
"destination": {
"type": "string",
"description": "Target Arbitrum wallet address (default: own wallet)",
},
},
"required": ["amount"],
}
async def execute(
self, ctx: ToolContext, amount: float = 0, destination: str = "", **kwargs
) -> ToolResult:
try:
amount = _coerce_float(amount, "amount")
if amount <= 0:
return ToolResult(success=False, error="'amount' must be positive")
client = _get_client()
data = await client.withdraw_from_bridge(
amount, destination=destination or None
)
return ToolResult(success=True, output=data)
except ValueError as e:
return ToolResult(success=False, error=str(e))
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLDepositTool(BaseTool):
"""Deposit USDC from Arbitrum wallet into Hyperliquid."""
@property
def name(self) -> str:
return "hl_deposit"
@property
def description(self) -> str:
return """Deposit USDC from this agent's Arbitrum wallet into Hyperliquid.
Sends an on-chain ERC-20 transfer of USDC to the Hyperliquid bridge contract.
Minimum deposit: 5 USDC. Requires USDC balance on Arbitrum.
Parameters:
- amount: USDC amount to deposit (required, minimum 5.0)
Returns: approve_tx_hash, transfer_tx_hash, amount_deposited"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"amount": {
"type": "number",
"description": "USDC amount to deposit (minimum 5)",
},
},
"required": ["amount"],
}
async def execute(
self, ctx: ToolContext, amount: float = 0, **kwargs
) -> ToolResult:
try:
amount = _coerce_float(amount, "amount")
if amount <= 0:
return ToolResult(success=False, error="'amount' must be positive")
if amount < 5:
return ToolResult(
success=False,
error="Minimum Hyperliquid deposit is 5 USDC",
)
client = _get_client()
data = await client.deposit_usdc(amount)
return ToolResult(success=True, output=data)
except ValueError as e:
return ToolResult(success=False, error=str(e))
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLApproveBuilderTool(BaseTool):
"""Approve Starchild builder to collect a small fee on fills (one-time)."""
@property
def name(self) -> str:
return "hl_approve_builder"
@property
def description(self) -> str:
return """Approve the Starchild builder to collect a small trading fee on your fills.
This is a ONE-TIME action. Once approved, a 2 bps (0.02%) builder fee is added to each
order, which goes to support Starchild platform operations. This fee is separate from
Hyperliquid's own trading fees.
You can revoke this approval at any time on app.hyperliquid.xyz.
No parameters required — uses the Starchild builder address and 2 bps fee by default.
Returns: approval confirmation from Hyperliquid"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {},
"required": [],
}
async def execute(self, ctx: ToolContext, **kwargs) -> ToolResult:
try:
client = _get_client()
data = await client.approve_builder_fee()
return ToolResult(success=True, output=data)
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLBuilderStatusTool(BaseTool):
"""Check builder approval status and collected rewards."""
@property
def name(self) -> str:
return "hl_builder_status"
@property
def description(self) -> str:
return """Check Starchild builder approval status and reward info.
Shows whether you have approved the Starchild builder, the max fee rate approved,
and any unclaimed builder/referral rewards.
No parameters required.
Returns: {approved: bool, maxFeeRate: str, referralInfo: {...}}"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {},
"required": [],
}
async def execute(self, ctx: ToolContext, **kwargs) -> ToolResult:
try:
client = _get_client()
address = await _get_address()
# Check approval status
max_fee = await client.get_max_builder_fee(address)
# Get referral/builder reward info
referral_info = await client.get_referral_info(address)
approved = bool(max_fee and str(max_fee) not in ("0", "None", ""))
return ToolResult(success=True, output={
"approved": approved,
"maxFeeRate": max_fee,
"referralInfo": referral_info,
})
except Exception as e:
return ToolResult(success=False, error=str(e))
class HLSetAbstractionTool(BaseTool):
"""Enable or disable unified account (DEX abstraction)."""
@property
def name(self) -> str:
return "hl_set_abstraction"
@property
def description(self) -> str:
return """Set Hyperliquid account abstraction mode.
**Abstraction modes:**
- "unifiedAccount": Unified margin across spot and perp (auto-transfers, can't manually transfer)
- "disabled": Separate spot/perp accounts (can manually transfer between them)
- "portfolioMargin": Advanced portfolio margin (if eligible)
**When to use:**
- Disable unified account to manually transfer funds and trade builder perps (xyz:NVDA, etc.)
- Enable unified account for automatic fund management across spot and perp
Parameters:
- mode: Abstraction mode (required: "unifiedAccount", "disabled", or "portfolioMargin")
Returns: abstraction update confirmation"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": ["unifiedAccount", "disabled", "portfolioMargin"],
"description": "Abstraction mode to set",
},
},
"required": ["mode"],
}
async def execute(
self, ctx: ToolContext, mode: str = "", **kwargs
) -> ToolResult:
if mode not in ("unifiedAccount", "disabled", "portfolioMargin"):
return ToolResult(
success=False,
error="'mode' must be 'unifiedAccount', 'disabled', or 'portfolioMargin'",
)
try:
client = _get_client()
address = await _get_address()
# Call the private method directly for setting abstraction
data = await client._user_set_abstraction(address, mode)
return ToolResult(success=True, output=data)
except Exception as e:
return ToolResult(success=False, error=str(e))