Programmatic Trading with the Hyperliquid SDK
- Hyperliquid SDK
- Hyperliquid programmatic trading
- Hyperliquid Python SDK
- Hyperliquid API automated trading
- On-chain perpetuals trading bots
Programmatic trading is no longer only for institutions. If you can write basic code, you can now build scripts that place orders, monitor positions, and react to market events on-chain. Hyperliquid, an on-chain perpetuals exchange, provides REST and WebSocket APIs, and both official and community SDKs make it possible to handle core workflows with relatively little code.
This guide walks through the practical flow: setting up a Python or JavaScript environment, connecting to Hyperliquid, querying market and account data, placing and managing orders, handling errors, and listening to fills in real time. It also explains why using a OneKey hardware wallet as the signing layer is an important security upgrade when moving from a local script to a production trading bot.
Why use Hyperliquid for programmatic trading?
Compared with centralized exchanges, Hyperliquid offers several advantages for developers and quantitative traders:
- Trade settlement happens on-chain, so users do not need to custody funds with a centralized third party.
- Its hybrid architecture combines off-chain order matching with on-chain settlement, aiming to balance speed and transparency.
- The API design is relatively straightforward, documentation is actively maintained, and the developer community is active.
For traders, this means you can keep self-custody while still getting a trading experience closer to a centralized exchange.
Environment setup and SDK installation
Python environment
At the time of writing, the community-maintained Python SDK can be installed with pip. Use a virtual environment to avoid dependency conflicts:
python -m venv hl_env
source hl_env/bin/activate
pip install hyperliquid-python-sdk
The SDK source is maintained across ecosystem repositories, including OneKey’s GitHub ecosystem collaboration repos and Hyperliquid’s official organization. Check the official documentation for the latest repository and package information.
JavaScript / TypeScript environment
For Node.js developers:
npm install @nktkas/hyperliquid
You can also use the official maintained package where applicable. Always verify the latest package name and version on npm before production use.
TypeScript users can import type definitions directly, which improves IDE autocomplete and reduces implementation mistakes.
Connecting to the API and initializing a client
Authentication
Hyperliquid authenticates trading requests through private-key signatures. Each order must be signed by a wallet private key using EIP-712 structured signing, making the request verifiable and resistant to forgery.
Python example, simplified:
import os
from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from eth_account import Account
# Read the private key from an environment variable. Never hard-code it.
private_key = os.environ["HL_PRIVATE_KEY"]
account = Account.from_key(private_key)
info = Info(base_url="https://api.hyperliquid.xyz")
exchange = Exchange(account, base_url="https://api.hyperliquid.xyz")
For production systems, avoid relying on a software private key stored on disk or in memory. A OneKey hardware wallet can be used as a signing layer so the private key never leaves the hardware secure element. Even if the trading server is compromised, the attacker cannot directly export the key.
Querying market data and account state
Get a market snapshot
# Get perpetual market metadata and current market context.
meta_and_asset_ctx = info.meta_and_asset_ctxs()
# The response includes fields such as markPx and funding.
Query positions and balances
user_state = info.user_state(account.address)
# user_state includes marginSummary and assetPositions.
for pos in user_state["assetPositions"]:
print(pos["position"]["coin"], pos["position"]["szi"])
Placing orders
Market order
order_result = exchange.market_open(
coin="BTC",
is_buy=True,
sz=0.001, # Order size
slippage=0.01 # Maximum allowed slippage: 1%
)
print(order_result)
Limit order
order_result = exchange.order(
coin="ETH",
is_buy=False,
sz=0.1,
limit_px=3200.0,
order_type={"limit": {"tif": "Gtc"}}
)
The tif field supports options such as:
Gtc: Good Till CancelIoc: Immediate or CancelAlo: Add Liquidity Only
Choose the time-in-force mode based on the strategy’s execution requirements.
Batch orders
Market-making and grid strategies often need to submit multiple orders at once. SDK batch endpoints can reduce network round trips:
orders = [
{
"coin": "BTC",
"is_buy": True,
"sz": 0.001,
"limit_px": 60000,
"order_type": {"limit": {"tif": "Gtc"}}
},
{
"coin": "BTC",
"is_buy": False,
"sz": 0.001,
"limit_px": 61000,
"order_type": {"limit": {"tif": "Gtc"}}
},
]
result = exchange.bulk_orders(orders)
Canceling and modifying orders
# Canceling requires the coin and order ID.
cancel_result = exchange.cancel(coin="BTC", oid=123456789)
# Modify order: effectively cancel + replace.
modify_result = exchange.modify_order(
oid=123456789,
coin="BTC",
is_buy=True,
sz=0.002,
limit_px=59500,
order_type={"limit": {"tif": "Gtc"}}
)
Error handling best practices
In programmatic trading, robust error handling is just as important as the strategy itself. Common issues include network timeouts, rate limits, rejected orders, insufficient margin, stale prices, and temporary API errors.
A simple retry pattern:
import time
def place_with_retry(exchange, kwargs, max_retries=3):
for attempt in range(max_retries):
try:
return exchange.order(**kwargs)
except Exception:
if attempt == max_retries - 1:
raise
# Exponential backoff: 1s, 2s, 4s...
wait = 2 ** attempt
time.sleep(wait)
In production, do not blindly retry every error. For example, an insufficient-margin error should not be retried indefinitely. Classify errors and handle each category explicitly.
Listening to fills with WebSocket
REST polling is fine for low-frequency strategies. For faster execution and position tracking, use WebSocket subscriptions:
from hyperliquid.websocket_manager import WebsocketManager
def on_fill(data):
print("Fill callback:", data)
ws = WebsocketManager(base_url="wss://api.hyperliquid.xyz")
ws.subscribe(
{"type": "userFills", "user": account.address},
callback=on_fill
)
ws.start()
Refer to Hyperliquid’s official documentation for the latest WebSocket subscription formats.
Protecting production bots with a OneKey hardware wallet
A hot wallet stores its private key in software, typically in memory, on disk, or inside a server environment variable. If that server is compromised, funds may be at immediate risk.
For a production bot managing real funds, a safer architecture is:
- Connect a OneKey hardware wallet to a dedicated signing service.
- Let the trading bot generate the transaction or order message to be signed.
- Send the signing request to OneKey.
- Complete the signature inside the hardware secure element.
- Return the signed payload to the bot and submit it to Hyperliquid.
With this setup, the private key stays inside the hardware wallet and cannot be exported through software. EIP-712 structured signing also allows the signing content to be displayed for review on the OneKey device screen, helping users verify what is being signed.
It is also worth using a dedicated API Agent wallet where supported by Hyperliquid. This can limit the agent’s permissions to a specific account and reduce operational risk.
Useful tools and resources
- Hyperliquid official documentation: API specs, field definitions, WebSocket formats, and rate limits.
- OneKey official site: hardware wallet product information and security model.
- WalletConnect documentation: useful if your signing flow needs to bridge through WalletConnect.
FAQ
Q1: What is the difference between using an SDK and calling the REST API directly?
An SDK wraps signing logic, request formatting, and common workflow details, reducing boilerplate. Calling the REST API directly gives you more control, but you must implement EIP-712 signing and request handling yourself. Most developers should start with the SDK and move closer to raw HTTP only if the strategy requires it.
Q2: Does programmatic trading on Hyperliquid require KYC?
Hyperliquid is a decentralized protocol and, at the time of writing, trading is available through a wallet address without KYC. Regulations vary by jurisdiction, and users are responsible for understanding and following the rules that apply to them.
Q3: How can I reduce the risk of large losses during extreme market moves?
Common risk controls include:
- Set a maximum loss threshold and pause the bot when it is reached.
- Monitor unrealized PnL relative to account equity.
- Use stop-loss orders where appropriate.
- Regularly verify that actual positions match the strategy’s expected state.
- Add circuit breakers for abnormal volatility, API errors, or repeated failed orders.
These controls do not eliminate risk, but they can help prevent small implementation issues from becoming catastrophic failures.
Q4: How can a OneKey hardware wallet integrate with automation scripts?
A common approach is to separate signing from trading logic. The bot prepares the message, sends it to a signing service connected to OneKey, receives the signature, and then submits the signed request. Depending on the integration path, this can be implemented through OneKey’s official SDK, USB/Bluetooth connectivity, or signing interfaces such as eth_sign where applicable.
For production deployments, keeping the signing service isolated from the strategy engine reduces the attack surface.
Q5: Do batch order endpoints have rate limits?
Check Hyperliquid’s official documentation for the latest rate-limit rules. In general, add reasonable delays between requests and implement a token bucket or sliding-window limiter to avoid triggering limits that could cause order failures.
Conclusion: from script to production system
The Hyperliquid SDK lowers the barrier to building on-chain perpetuals trading bots. But moving from a script that “works on my machine” to a reliable production system requires serious work on key management, signing security, error handling, monitoring, and risk controls.
If you want to trade on-chain perpetuals without writing code, OneKey Perps provides a practical interface for perpetuals trading while keeping wallet security central to the workflow. For developers and teams building bots, using OneKey as the signing backend is a stronger key-management approach than storing private keys in a hot server environment.
Try OneKey and explore OneKey Perps if you want a more secure, practical way to access on-chain perpetuals. Use small size first, understand the mechanics, and only trade with risk you can afford to take.
Risk warning: Programmatic trading involves significant technical and market risk. Perpetual contracts are leveraged products and may lead to losses exceeding the initial amount committed. This article is for technical reference only and is not investment, legal, or financial advice. Crypto markets are highly volatile, and past performance does not indicate future results.



