How to code a trading strategy on Hyperliquid: the Python SDK or Claude Code with Senpi
Updated Nov 16, 2026 · 10 min read
Two routes to an automated Hyperliquid strategy: the official Python SDK (API wallet, orders, TP/SL, websockets, HIP-3, rate limits) or Claude Code with Senpi connected over MCP.
- Two routes compared
- Route 1: the Python SDK
- 1. Install the SDK and get testnet funds
- 2. Create an API wallet and connect
- 3. Place, check and cancel an order
- 4. Attach take-profit and stop-loss
- 5. Stream data and fills over websockets
- 6. Trade HIP-3 stock and commodity perps
- 7. Stay inside the limits
- 8. Run it like production
- Route 2: Claude Code with Senpi
- 1. Connect Senpi to Claude Code
- 2. Describe the strategy
- 3. Review, approve and run
- 4. Start from a template, or write your own
How do you code a trading strategy on Hyperliquid? There are two routes. Write it yourself in Python with the official hyperliquid-python-sdk: create an API wallet that can trade but not withdraw, test on testnet, then point the same code at mainnet. Or describe it to Claude Code with Senpi connected: Senpi’s AI quant writes the strategy, shows you the rules and runs it on its own runtime, so there is no server or key for you to manage. On the SDK route, the SDK gives you two objects: Info for market and account data, and Exchange for signed actions such as orders, cancels and leverage. Prices allow 5 significant figures, actions are rate-limited per address, and the websocket closes after 60 seconds without a message.
Key takeaways
- Two routes: your own Python code with the official SDK, or Claude Code with Senpi connected, where Senpi writes and runs the strategy.
- Use the official SDK (
pip install hyperliquid-python-sdk, version 0.24.0, Python 3.9+) or CCXT if you also trade other venues. - Sign with an API wallet created at app.hyperliquid.xyz/API, and pass your main address as
account_address. - Testnet gives 1,000 mock USDC, but only to addresses that have deposited on mainnet.
- Send the entry and its take-profit and stop-loss in one action with
grouping="normalTpsl". - Plan for limits: 1,200 request weight a minute per IP, 1 action per 1 USDC traded per address after a 10,000 buffer, 1,000 open orders by default.
Two routes compared
| Python SDK | Claude Code with Senpi | |
|---|---|---|
| Who writes the code | You | Senpi’s AI quant, from your description; you review the rules |
| Where it runs | Your server | Senpi’s runtime, 24/7 |
| Keys | An API wallet key you store | None: each strategy trades from its own strategy wallet, and the agent holds no key |
| Stops and halts | Whatever you code | DSL from the first fill, plus optional daily-loss and drawdown halts per strategy |
| Backtests | Yours to build (5,000 candles via the API) | Senpi doesn’t run backtests; Simulations, paper trading with simulated money, are coming |
| Markets | Everything the API lists | Crypto perps plus HIP-3 stock, commodity and FX perps |
| Cost | Hyperliquid fees and your server | Hyperliquid fees; Senpi adds 0% on paid plans (from $50 a month), 0.03% on the free trial |
| Best for | Full control, custom execution, market making | Running rule-based strategies without maintaining infrastructure |
Route 1: the Python SDK
The read-only calls below (account state, order book, HIP-3 metadata, building an Exchange, the websocket) were run against mainnet with SDK 0.24.0 on Nov 16, 2026. The order, TP/SL, cancel and scheduled-cancel calls were built and signed with the same SDK but not sent for this guide: run them on testnet before mainnet.
1. Install the SDK and get testnet funds
pip install hyperliquid-python-sdk # 0.24.0, Python 3.9+Testnet runs at api.hyperliquid-testnet.xyz. The faucet at app.hyperliquid-testnet.xyz/drip gives 1,000 mock USDC to an address that has deposited on mainnet. If you sign in to Hyperliquid with email, Privy creates different addresses for mainnet and testnet, so export the mainnet wallet first.
2. Create an API wallet and connect
An API wallet, also called an agent wallet, signs orders for your account and cannot withdraw. Create it at app.hyperliquid.xyz/API, keep its private key out of your code, and pass your main address as account_address. If you pass the API wallet’s own address instead, the account shows no equity.
import eth_account
from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from hyperliquid.utils import constants
URL = constants.TESTNET_API_URL # constants.MAINNET_API_URL when you go live
MAIN_ADDRESS = "0x..." # your account, not the API wallet
api_wallet = eth_account.Account.from_key("0x...") # API wallet private key, from an env var in practice
info = Info(URL, skip_ws=True)
exchange = Exchange(api_wallet, URL, account_address=MAIN_ADDRESS)
print(info.user_state(MAIN_ADDRESS)["marginSummary"])
print(info.l2_snapshot("ETH")["levels"][0][:3]) # best three bids3. Place, check and cancel an order
exchange.order(coin, is_buy, size, limit_price, order_type) places one order. Time-in-force is Gtc (rests until filled or cancelled), Alo (post-only, never takes) or Ioc (fills now or cancels). Hyperliquid has no native market order: the SDK’s market helpers send an aggressive Ioc limit with a slippage bound.
# Limit buy 0.02 ETH 5% below the mid price, so it rests on the book (Gtc).
# Use "Alo" for post-only, "Ioc" for immediate-or-cancel.
mid = float(info.all_mids()["ETH"])
res = exchange.order("ETH", True, 0.02, round(mid * 0.95), {"limit": {"tif": "Gtc"}})
status = res["response"]["data"]["statuses"][0]
if "resting" in status:
oid = status["resting"]["oid"]
print(info.query_order_by_oid(MAIN_ADDRESS, oid))
exchange.cancel("ETH", oid)
4. Attach take-profit and stop-loss
Trigger orders carry tpsl: "tp" or "sl", a trigger price and isMarket, and should be reduce_only. Grouping them with the entry as normalTpsl sends all three in one action, so the exits exist as soon as the entry does. Hyperliquid order types explains how stop-market and stop-limit orders fill.
# Entry plus take-profit and stop-loss in one action (grouping="normalTpsl").
# Whole-dollar prices are always valid; the exits activate once the entry fills.
mid = float(info.all_mids()["ETH"])
entry, tp, sl = round(mid * 0.98), round(mid * 1.06), round(mid * 0.95)
orders = [
{"coin": "ETH", "is_buy": True, "sz": 0.02, "limit_px": entry,
"order_type": {"limit": {"tif": "Gtc"}}, "reduce_only": False},
{"coin": "ETH", "is_buy": False, "sz": 0.02, "limit_px": tp,
"order_type": {"trigger": {"isMarket": True, "triggerPx": tp, "tpsl": "tp"}}, "reduce_only": True},
{"coin": "ETH", "is_buy": False, "sz": 0.02, "limit_px": sl,
"order_type": {"trigger": {"isMarket": True, "triggerPx": sl, "tpsl": "sl"}}, "reduce_only": True},
]
print(exchange.bulk_orders(orders, grouping="normalTpsl"))
5. Stream data and fills over websockets
Polling the REST API burns rate limit, so subscribe instead. Useful channels are l2Book, bbo, trades, candle, orderUpdates, userFills and userFundings. The server closes a connection that has sent nothing for 60 seconds; the SDK pings for you, and a raw client should send {"method": "ping"}. One IP can hold 10 connections and 1,000 subscriptions, and reconnect logic is your job.
def on_book(msg): print("book", msg["data"]["levels"][0][0])
def on_order(msg): print("order", msg["data"])
def on_fill(msg): print("fill", msg["data"])
info_ws = Info(URL) # skip_ws defaults to False: opens a websocket
info_ws.subscribe({"type": "l2Book", "coin": "ETH"}, on_book)
info_ws.subscribe({"type": "orderUpdates", "user": MAIN_ADDRESS}, on_order)
info_ws.subscribe({"type": "userFills", "user": MAIN_ADDRESS}, on_fill)6. Trade HIP-3 stock and commodity perps
Markets deployed under HIP-3, such as the XYZ stock perps, live in their own dex. Name it with perp_dexs and use the prefixed coin, for example xyz:NVDA; account calls such as user_state take the dex too. Several open SDK issues are about calls that still miss the dex parameter, so check positions on the dex you trade. See What is HIP-3? and How to trade stocks on Hyperliquid.
# Builder-deployed (HIP-3) markets: name the dex, then use its prefixed coin names.
info = Info(URL, skip_ws=True, perp_dexs=["xyz"])
exchange = Exchange(api_wallet, URL, account_address=MAIN_ADDRESS, perp_dexs=["xyz"])
print(info.meta(dex="xyz")["universe"][0])
print(info.user_state(MAIN_ADDRESS, dex="xyz")["assetPositions"])7. Stay inside the limits
| Limit | Value | What it means for a bot |
|---|---|---|
| REST weight per IP | 1,200 a minute | Order actions weigh 1 (plus 1 per 40 orders in a batch); l2Book and clearinghouseState weigh 2; most other info calls weigh 20 |
| Actions per address | 1 per 1 USDC traded since creation, plus a 10,000 starting buffer | A bot that cancels and replaces often needs volume to keep quoting; when limited, one request every 10 seconds |
| Cancels | Higher limit than other actions | You can still cancel open orders after hitting the action limit |
| Open orders | 1,000, plus 1 per $5M volume, up to 5,000 | Above 1,000, new reduce-only and trigger orders are rejected |
| Price and size | 5 significant figures; 6 − szDecimals decimals on perps | Round before you send, or the order is rejected |
| Websocket | 10 connections, 1,000 subscriptions, 60-second timeout | Batch subscriptions on one connection and ping |
Batch orders and cancels where you can: a batch of n orders counts once against the IP limit and n times against the address limit, and batching lowers weight during congestion.
8. Run it like production
- 01Run on a server with a process supervisor, not a laptop.
- 02On every start, read open orders and positions before placing anything, so a restart doesn’t double an order.
- 03Use client order IDs so you can match fills to the orders that caused them.
- 04Set a dead man’s switch with
schedule_cancel, so open orders are cancelled if the bot stops. - 05Log every action and reply, and alert on rejected orders and disconnects.
from hyperliquid.utils.signing import get_timestamp_ms
# Dead man's switch: cancel all open orders in 60 s unless the bot pushes this forward again.
exchange.schedule_cancel(get_timestamp_ms() + 60_000)Route 2: Claude Code with Senpi
Everything in route 1 is yours to maintain: the server, the key, restarts, reconnects and alerts. In route 2, Claude Code talks to Senpi over MCP, and Senpi’s AI quant turns your description into a strategy that runs on Senpi’s runtime.
1. Connect Senpi to Claude Code
Add Senpi’s agent address, https://agents.senpi.ai/mcp, as a custom connector, then sign in to Senpi from /mcp. There are no API keys to paste. If you only want research (market pulse, signals, smart-money positioning, wallet analysis), the open-source Senpi — AI Quant plugin connects to a read-only server instead and cannot trade.
# The Senpi agent, which can build and run strategies (trades need your Allow)
claude mcp add --transport http --scope user senpi https://agents.senpi.ai/mcp
# then run /mcp inside Claude Code and sign in to Senpi
# Or the read-only research plugin, which cannot trade
claude plugin marketplace add Senpi-ai/senpi-plugin
claude plugin install senpi-agent@senpi2. Describe the strategy
Write it the way you would brief a quant: market, entry, exit, size, leverage and limits. Ask for the rules before anything runs.
Build a strategy on ETH: go long when the 4-hour close is above the 50-period moving average
and funding is below 0.01% an hour; exit on a 3% trailing stop. Risk 1% of the wallet per trade,
3x leverage, daily-loss halt at 3%. Show me the rules and the code before anything runs.3. Review, approve and run
Senpi replies with the rules it wrote. Before the assistant places or changes a trade through the connector, Senpi asks you to Allow once or Deny, and deposits and withdrawals stay in the Senpi app. On Senpi, a strategy you confirm runs as code on Senpi’s runtime, and by default no AI model makes live trading decisions. Strategies built from a rule or a template carry the Dynamic Stop-Loss (DSL) from the first fill, and each can have its own daily-loss halt, which lifts at the next UTC midnight, or a drawdown halt, which waits until you resume it. Copy strategies carry at most a flat stop. Each strategy trades from its own strategy wallet; the agent holds no key and cannot withdraw.
4. Start from a template, or write your own
Senpi’s strategy templates are open source in the senpi-skills repository. A strategy there is a scanner, scan(inputs, ctx), that reads market data and returns signals; it never places an order itself, and Senpi’s runtime owns sizing, risk limits and exits. Read a template such as Chameleon to see the pattern, or ask Claude Code to adapt one. Senpi doesn’t run backtests; Simulations, paper trading with simulated money, are coming. Hyperliquid charges 0.015% for maker orders and 0.045% for taker orders at the base tier on crypto perps. Senpi adds 0% on paid plans and 0.03% on the free trial or without a paid plan.
How do I code a trading strategy on Hyperliquid?
Either write it in Python with the official hyperliquid-python-sdk, sign with an API wallet and run it on your own server, or describe it to Claude Code with Senpi connected, review the rules Senpi writes and let it run on Senpi’s runtime.
Can Claude Code trade on Hyperliquid?
With Senpi connected at https://agents.senpi.ai/mcp, Claude Code can ask Senpi to build and run strategies on Hyperliquid. Senpi asks you to Allow once or Deny before the assistant places or changes a trade, and deposits and withdrawals stay in the Senpi app. The Senpi — AI Quant plugin on its own is read-only.
How do I connect Python to Hyperliquid?
Install hyperliquid-python-sdk, create an API wallet at app.hyperliquid.xyz/API, and build an Exchange with the API wallet’s key and your main address as account_address. Use Info for market data and account state.
Does Hyperliquid have a testnet?
Yes, at api.hyperliquid-testnet.xyz. The faucet gives 1,000 mock USDC to addresses that have deposited on mainnet.
What are Hyperliquid’s API rate limits?
1,200 request weight a minute per IP for REST, and per address 1 action per 1 USDC traded since the address was created, plus a 10,000 starting buffer. Websockets allow 10 connections and 1,000 subscriptions per IP.
How do I set a stop-loss and take-profit with the Hyperliquid API?
Send trigger orders with tpsl set to sl or tp, a triggerPx and reduce_only=True. To send them with the entry in one action, use bulk_orders(..., grouping="normalTpsl").
Why does my Hyperliquid order get rejected for its price?
Usually rounding. Prices allow 5 significant figures and, on perps, no more than 6 minus the market’s szDecimals decimal places; sizes round to szDecimals. Integer prices are always allowed.
Can an API wallet withdraw funds?
No. An API wallet can place and cancel orders for your account, but it cannot withdraw. Keep its key out of your code all the same.
This is educational material, not financial advice. The market readings are data, not trade signals, and leveraged perps can lose money quickly.
Code it in plain language
Connect Senpi to Claude Code, describe the rule, and Senpi runs it with a stop from the first fill.
Related articles
What does a trading agent do when it isn’t trading?
Most of a trading agent’s work happens between trades: refusing signals, re-checking open positions and moving stops one way. Senpi’s fleet telemetry from August 2026, and how often it checks today.
What does the model do in an AI trading agent, and what does the harness do?
In an AI trading agent the model understands, routes, explains and asks; tested programs compute, and a runtime places and protects the orders. Where the line sits, and how Senpi draws it.
QuantConnect, Freqtrade, Hummingbot or an AI agent: which for crypto quant trading?
QuantConnect, NautilusTrader, Freqtrade, Hummingbot, CCXT, backtrader, vectorbt and an AI agent compared for crypto quants: Hyperliquid support, backtesting, live trading, languages and licences, checked Nov 13, 2026.
How to automate a crypto trading strategy without coding
Three no-code ways to automate a crypto strategy: bot presets, TradingView alerts sent to a bot, or an AI agent that writes and runs it. What each costs on Hyperliquid, with a walkthrough from Claude or ChatGPT.