BlogDeveloper

How to Build a Hyperliquid Trading Bot

Learn how to build a Hyperliquid trading bot: a signal from market data, signed orders through Hyperliquid's API, risk limits and a kill switch, with examples.

HydromancerTeam
How to Build a Hyperliquid Trading Bot

Trading by hand means watching the screen all day and night. If you have an idea you want to run on Hyperliquid, such as buying when buyers rush in or cutting a position the moment it moves against you, a trading bot can do the watching and the clicking for you.

Why build a trading bot on Hyperliquid?

Many traders build their first bot on a centralized exchange (CEX) such as Binance or Bybit. Hyperliquid works differently, and for a bot those differences matter:

Hyperliquid A centralized exchange
Order bookFully on-chain: every
order, cancel, trade and
liquidation is public
Runs on the exchange's
private servers
What your bot can seeAny wallet's trades
and open positions
Market data and
your own account
Your accountYour wallet, with
balances on-chain
An account the exchange
holds your funds in
How a bot gets accessAn API wallet signs
orders for your
account, one per bot
API keys issued
by the exchange

For a bot builder, those differences add up to four advantages:

  • Hyperliquid's speed supports diverse capabilities for any builder. Hyperliquid's docs put its capacity at about 200,000 orders a second. A co-located client sees a median of 0.2 seconds end to end, allowing anyone to port automated strategies "from other crypto venues with minimal changes".
  • Strategies a CEX can't support. Every wallet's fills and positions are public, so a bot can react to what other traders actually do. It can follow a wallet, watch liquidations as they happen, or track the biggest positions in a market.
  • More than crypto, on one API. Builder-deployed markets (HIP-3) list assets such as the S&P 500 and gold next to crypto perps. Your bot trades them with the same orders.
  • A bot can become a business. With builder codes, an app that places orders for other users can earn a fee of up to 0.1% on their perp fills.

Below, we build a mini example: a small bot that streams live trades, turns them into a buy or sell decision, places signed orders, and stops itself when something goes wrong. It runs on Hyperliquid's own API first, then we show where Hydromancer's fits. The code is Python, but the structure is the same in any language. Treat it as a starting point to adapt, not a production template; prices shown are from our test runs.

How the mini example works

Part What it does
SignalOrder flow from Hyperliquid's live BTC trades
feed; later, top wallets' fills from Hydromancer
DecisionA toy rule: follow the side that traded
more aggressively in the last 30 seconds
OrdersImmediate-or-cancel orders, priced off the live order book
PositionAlways read back from the exchange, never counted locally
SafetySize caps, a loss limit, a stale-data
stop, a kill file, then cancel and flatten
Diagram of a trading bot on Hyperliquid in four steps: stream live trades, apply your rule to decide buy or sell, place a signed order through Hyperliquid's exchange API, and guard with risk limits that cancel, flatten and check.

Before you start

  • An SDK for your language (see below).
  • A Hyperliquid account and an API wallet approved to trade for it.
  • A Hydromancer API key, only for the upgrade at the end.
  • Environment variables: HYDROMANCER_API_KEY, HL_SECRET_KEY (the API wallet's key) and HL_ACCOUNT_ADDRESS (your main account).

Our Hyperliquid API guide explains API wallets and signing.

Choose your language

Reading data is plain HTTP requests and live streams, so any language works. Placing orders is harder, because each one must be signed exactly as Hyperliquid expects. Hyperliquid's signing docs recommend an existing SDK rather than writing your own.

Language SDK
PythonOfficial SDK ( pip install hyperliquid-python-sdk )
TypeScriptCommunity SDKs, listed in Hyperliquid's API docs
RustA community SDK, listed in the same docs

The examples below use Python with the official SDK. The requests behind them are the same in any language.

Step 1: Stream live trades from the market

Every bot needs a reason to trade, usually called a signal. In this example, the signal is order flow: over the last 30 seconds, did traders who crossed the spread buy more BTC than they sold? Those traders are called takers, and heavy taker buying suggests buyers are in a hurry.

To measure that, the bot needs every BTC trade the moment it happens. Hyperliquid's live feed pushes each trade to you, so you don't have to keep asking. Subscribe to BTC trades and read the first one (pip install websocket-client):

code
import json
import websocket

ws = websocket.create_connection("wss://api.hyperliquid.xyz/ws")
sub = {"type": "trades", "coin": "BTC"}
ws.send(json.dumps({"method": "subscribe", "subscription": sub}))

ws.recv()  # the subscription confirmation
trade = json.loads(ws.recv())["data"][0]
print(trade["side"], trade["sz"], "BTC @", trade["px"])
code
A 0.006 BTC @ 80334.0

Each trade has a side: B when the taker bought, A when they sold, plus a size (sz) and price (px). The bot keeps reading and adds up 30 seconds of them. Our data feeds guide covers the feed in depth.

Step 2: Turn the trades into a buy or sell decision

The decision rule is where your strategy lives. The mini example uses a deliberately simple one, only to exercise the rest of the bot:

  1. Add up the size of every taker buy and subtract every taker sell over the last 30 seconds.
  2. If the result is positive, buy. If it's negative, sell.
  3. Hold for 20 seconds, then close, and stop.

This rule isn't a strategy, and you shouldn't trade it. Swap in your own logic here, using whatever data it needs. The steps around it stay the same.

Step 3: Place the order on Hyperliquid

Once the rule decides, the bot sends a signed order to Hyperliquid's exchange API. The SDK handles the signing: you give it the coin, side, size, price and order type.

There's no plain market order in Hyperliquid's API. To trade "at market", send a limit order with time-in-force Ioc (immediate or cancel) at a price that crosses the book. It fills what it can right away and cancels the rest. Here's the call:

code
from hyperliquid.exchange import Exchange
from hyperliquid.utils import constants

exchange = Exchange(wallet, constants.TESTNET_API_URL, account_address=ACCOUNT)
# sell 0.0002 BTC, immediate-or-cancel, at a price that crosses the book
order = exchange.order("BTC", False, 0.0002, price, {"limit": {"tif": "Ioc"}})
print(order["response"]["data"]["statuses"][0] if order["status"] == "ok"
      else order["response"])  # a rejection's reason is text
json
{'filled': {'totalSz': '0.0002', 'avgPx': '80951.2', 'oid': 63658735343}}

Here wallet is your API wallet (eth_account.Account.from_key(os.environ["HL_SECRET_KEY"])), ACCOUNT is your main account's address (HL_ACCOUNT_ADDRESS), and price is the best bid, read just before the order with Hyperliquid's l2Book request (Info(URL).l2_snapshot("BTC")["levels"][0][0]["px"] in the SDK), minus 0.1% and rounded to Hyperliquid's tick rules, so the sell crosses the book. The code points at testnet; switch to constants.MAINNET_API_URL only when you go live. To close the position later, exchange.market_close("BTC") sends a reduce-only order the same way.

Three things to get right:

  • Price off a fresh book read. Read the best bid or ask right before each order, not a price from earlier in the loop.
  • Check every order's status. A response can say "ok" at the top while the order itself was rejected.
  • Respect the order rules. Orders must be worth at least $10, and prices and sizes must be rounded. See Hyperliquid's tick size docs.

Step 4: Add risk limits and a kill switch

A bot runs unattended, so it needs rules that override the trading logic when something goes wrong. The full mini example runs Steps 1 to 3 in a loop, and checks these limits before every order. The trading rule can ask for anything, but the limits have the final say:

Limit Setting in the mini example
Order size and position0.0002 BTC, one position at a time
Loss limitStop if the open loss passes $2
Stale dataStop if the newest trade is over 20 seconds old
Kill fileStop when a file named STOP appears
Run timeStop after 120 seconds

Every stop goes through one shutdown routine: cancel open orders (info.open_orders(ACCOUNT), then exchange.cancel(coin, oid) for each), close the position with a reduce-only order (exchange.market_close("BTC")), then read the account again (info.user_state(ACCOUNT)). If anything is left, the bot prints a warning and exits with an error code.

What one run did

Here's a test run of the full mini example (the loop, limits and shutdown), from its log. In this run, the trades came from Hydromancer's trades stream of the same Hyperliquid data (send {"type": "subscribe", "subscription": {"type": "trades", "coin": "BTC"}} to wss://api.hydromancer.xyz/ws?token= plus your key; each message has a trades list with the same fields as Hyperliquid's), and the orders went to Hyperliquid's testnet:

Time (UTC) Event
12:03:42Subscribed to live BTC trades
12:04:13Signal: takers sold 0.072 BTC more than they bought in 30 seconds
12:04:14Sold 0.0002 BTC, filled at 80,809
12:04:37Closed with a reduce-only buy at 80,798
12:04:37Final check: no open orders, no position

We also stopped a second run with the kill file right after its entry. It closed the position and ended flat.

What to know before going live

  • Test your code before you go live, but not your strategy. Passing constants.TESTNET_API_URL (https://api.hyperliquid-testnet.xyz) checks that the bot connects, signs, places orders and shuts down cleanly. The run above did that. Testnet has its own markets, prices and liquidity, though, so it can't tell you whether a strategy makes money.
  • Don't trade the toy rule. It only proves the plumbing works. Replace it with your own logic, but keep the fresh reads and the stop check right before each order.
  • Read your position from the exchange. Use clearinghouseState with your main account's address; the API wallet's own address holds nothing.
  • Give each bot its own API wallet and coins if one account runs several bots.
  • Check the account from outside the bot after every run, with openOrders and clearinghouseState.
  • Mind the rate limits. Hyperliquid gives each IP 1,200 request weight a minute. See Hyperliquid rate limits.

Follow top Hyperliquid wallets from your bot

The steps above use Hyperliquid's own API, and orders always go there. Hydromancer comes in on the data side: what your bot can see, how many wallets it can follow, and how it recovers when a connection drops.

With vs without Hydromancer

What the bot needs Without Hydromancer (Hyperliquid's API only) With Hydromancer's API
Follow wallets liveOne subscription per
wallet; the docs allow
10 users per IP
(15 in our test)
One userFills subscribe
request for up to 1,000
addresses; each counts
toward your plan's
subscription total (500
on Starter)
Read many accountsclearinghouseState ,
one wallet per
request, from 1,200
weight a minute per IP
batchClearinghouseStates
: up to 1,000 wallets
on one DEX in one request
See the order bookPrice levels only
(L2), 20 a side
Every resting order with
its ID and address (L4)
Network-wide signalsThe trades stream, one
subscription per market,
with both wallets on
every trade
Streams of every fill (
allFills , an add-on) and
every leverage change
Recover after a dropResubscribe, then
backfill over REST
Reconnect with a session ID
to replay up to 30 seconds
History for backtestsA wallet's recent fills,
or Hyperliquid's S3 fill
files, which you parse
yourself
Fills from 28 July
2025, plus the free
Reservoir archive
Placing ordersHyperliquid's exchange APIThe same: orders always
go to Hyperliquid

batchClearinghouseStates is a Hydromancer endpoint, not part of Hyperliquid's own API. Orders still go to Hyperliquid.

Example: trade on what the top 100 wallets do

The bot above reacts to anonymous order flow. On Hyperliquid, it can do something a CEX can't: react to what specific traders do, because every wallet's fills are public. For example, "buy when the most profitable wallets buy".

Without Hydromancer: your bot sends Hyperliquid's live feed one userFills subscription per wallet, and the docs allow 10 wallets per IP (15 in our test). So you can follow the top 15 that way, not the top 100. Subscribing to every market's trades and filtering by address reaches all 100, but in our tests it delivered about 90% of fills.

With Hydromancer: one subscription for all 100 wallets, on one connection. Take the 100 addresses (each row's ethAddress) from Hyperliquid's leaderboard file, https://stats-data.hyperliquid.xyz/Mainnet/leaderboard; our leaderboard guide shows how to rank it. Connect to wss://api.hydromancer.xyz/ws?token= followed by your API key, then send:

json
{"type": "subscribe",
 "subscription": {"type": "userFills", "addresses": ["0x…", "0x…", …]}}
json
{"type": "userFills", "seq": 1, "cursor": "…", "fills": [
  ["0x5c9b…ce01", {"coin": "xyz:ORCL", "sz": "3.166", "dir": "Close Long", …}]]}

Each fill arrives paired with the wallet that made it, in the message's fills list. The first two messages confirm the connection (connected) and the subscription (subscriptionUpdate). The server sends {"type": "ping"} soon after you connect and then every 60 seconds; reply with {"type": "pong"} to stay connected. The address list is the 100 wallets with the highest month PnL on Hyperliquid's leaderboard. Our leaderboard guide shows how to get it. To use them in Step 2's rule, keep the fills for the market you trade and add up buys minus sells by size, just as with the BTC order flow. Steps 3 and 4 stay the same.

To copy one trader's every move instead, see our copy trading bot guide.

FAQ

Do trading bots work on Hyperliquid?

A bot reliably does what you tell it: it watches the market around the clock and acts in moments. Whether it makes money depends on the strategy, fees and risk limits, not the bot. Hyperliquid is built for automated trading, with a public API, API wallets and an official SDK.

Is it allowed to run a trading bot on Hyperliquid?

Hyperliquid provides a public API, API wallets and an official SDK for trading programmatically, so bots use the same order path as the app. Rules on automated trading can differ by country, and this isn't legal advice.

Is there a free Hyperliquid trading bot on GitHub?

Hyperliquid's official Python SDK is free and open source, with example scripts for placing and cancelling orders. Hyperliquid's docs also list community SDKs for TypeScript and Rust. Start from those, then add your own strategy and risk limits.

Can I build a Hyperliquid trading bot without coding?

Yes, with no-code bot platforms that connect to Hyperliquid through an API wallet. They're quicker to start, but you're limited to the strategies and data they offer. Code lets you use any signal, such as the top-wallet fills shown above.

Does Hyperliquid have market orders in the API?

No plain market order. Send a limit order with time-in-force Ioc at a price that crosses the book. The SDK's market_open and market_close do this for you.

Can I test a Hyperliquid bot without real money?

You can test the code, using Hyperliquid's testnet and test USDC. Its markets, prices and liquidity aren't the same as mainnet's, so it won't show how a strategy would really perform. Our testnet guide covers setup.

What is the minimum order size?

Orders must be worth at least $10, and sizes must be rounded to the market's szDecimals.

Next steps

  • Stream trades: run the Step 1 snippet. It needs no key.
  • Place an order: try the Step 3 call with a small size.
  • Upgrade the signal: follow the top wallets with the Hydromancer subscribe request.
  • Round orders correctly: Hyperliquid's tick size docs.
  • Need more market data for your rule? See Hydromancer's data streaming.
Continue