More products
Build a hedged HXMR market-making bot
This page is a build spec. It describes, end to end, a bot that:
- Quotes HXMR/USDC on both sides.
- Hedges the XMR it accumulates with the XMR perpetual on Hyperliquid, so it earns the spread without betting on the Monero price.
- Moves USDC between the spot and perp balances on its own, so the bids always have USDC and the hedge always has margin.
- Optionally rebalances HXMR through the Wagyu bridge.
In the Wagyu app this market is shown as XMR/USDC. On Hyperliquid it is HXMR/USDC, spot market @1193. They are the same order book; this page calls it HXMR/USDC.
You can build it yourself from this page, or paste the prompt below into Claude Code and let it build the bot from this spec. The basics (what HXMR is, the economics, the fee waiver for market makers) are on Market making HXMR, and the words used here are explained in its glossary.
#Paste this into Claude Code
Build a hedged market-making bot for HXMR/USDC on Hyperliquid, following the spec at
https://docs.wagyu.xyz/market-making-bot.md exactly. Read it in full first, then
https://docs.wagyu.xyz/market-making.md and https://docs.wagyu.xyz/native-bridge.md, then Hyperliquid's API docs
(exchange endpoint, info endpoint, WebSocket, tick and lot size, rate limits, nonces, account abstraction modes).
Use Python 3.12 and the official hyperliquid-python-sdk. Build it in the order of the spec's "Build order" section,
with the tests it lists, and stop after each milestone to show me what works. Start in dry-run mode: no order is
signed until I set mode: live in the config.
The bot signs with one private key, read from a .env file as HL_PRIVATE_KEY. If the file is missing, tell me to
create it. Never ask me to paste the key, and never write it to code, config files or logs.
Before choosing sizes, spreads or limits, ask me how much USDC and HXMR the account holds, and derive the bid
budget from the spec's "How much USDC a hedged bid needs" formula.#One fill, start to finish
Before the details, here is what the bot does with a single trade. XMR is at $450.00 and the bot quotes 1% each side.
- A seller hits your bid. You buy 2 HXMR at $445.50 and pay $891.00 of spot USDC. You now hold 2 XMR more price exposure than you want.
- The hedger sells 2 XMR on the perp at about $449.90. The price risk is gone, and $8.80 is locked in: (449.90 − 445.50) × 2, before fees.
- The treasurer checks the margin. A 2 XMR short at 2× needs about $450 of margin, plus a buffer for price moves. If the perp balance is short of that, it moves USDC from spot to perps.
- The position is closed in one of two ways.
- A buyer lifts your ask: you sell the 2 HXMR at $454.50, the hedger buys back the perp, and you have earned both sides of the spread.
- Nobody buys: you redeem the 2 HXMR for 2 XMR through the bridge and sell the XMR elsewhere while closing the perp. With a fee waiver this keeps the $8.80. Without one, the 2% withdrawal fee (about $18 here at 2%) is more than you earned.
Everything else on this page exists to do those four steps safely: the quoter does step 1, the hedger step 2, the treasurer step 3, and the risk manager stops all of them when something is wrong.
#How the bot is built
One program. The quoter, hedger, treasurer and risk manager are four parts of one process. Each part has a pure decision function (inputs in, orders or transfers out) that you can test without a network. The treasurer runs every 30–60 s, not on every tick.
One key. The bot signs everything with the private key of its own Hyperliquid account: orders, hedges, transfers between spot and perps, and HXMR sends to the bridge. Put the key in a .env file on the machine that runs the bot:
HL_PRIVATE_KEY=0x…Never paste the key into a chat, a prompt, a config file or a log. If you build with an AI agent, create the .env file yourself; the agent only needs to know the variable's name.
Because that key can move funds, use a fresh account that holds only what the bot needs. If you later split the quoter into its own process, or want a key on the server that cannot withdraw, add a Hyperliquid API wallet for it then (one per process, since each signer has its own nonce set). It is not needed to start.
#Set up the account on app.wagyu.xyz
- Connect a wallet on app.wagyu.xyz. This is the bot's account. Use a fresh one that holds only the bot's funds: its key will be on the server.
- Deposit USDC with the app's deposit flow.
- Bridge XMR to HXMR with the deposit flow (choose XMR), or with the bridge API. The minimum is 0.005 XMR; HXMR arrives after 2–10 Monero confirmations.
- Turn Unified Account OFF in the account menu (standard mode). See why.
- Split USDC between spot (for bids) and perps (hedge margin) with the app's transfer between spot and perps. The treasurer keeps the split right from then on.
- Open both markets to watch the bot work: XMR/USDC spot (HXMR) and XMR-USDC perp. Your open orders, positions and balances show in the app like any manual trade, and you can cancel from there in an emergency.
- Put the account's private key in a
.envfile asHL_PRIVATE_KEYon the machine that will run the bot. Do not paste it anywhere else. - Ask for the bridge fee waiver for the bot account's address, if you will redeem HXMR (see Market making HXMR).
#Account mode: standard, not unified
Hyperliquid accounts have account modes:
| Standard (recommended for this bot) | Unified account | |
|---|---|---|
| Spot USDC and perp margin | Separate balances: the treasurer moves USDC between them. | One USDC balance backs spot and perps: no transfers needed. |
| Action limit | None beyond the normal rate limits. | 50,000 actions per day. A bot requoting several times a minute can hit it. |
| Hyperliquid's advice | Recommended for market makers and high-volume automated users. | Recommended for most manual users. |
| Reading balances | Perp state in clearinghouseState, spot in spotClearinghouseState. |
Everything in spotClearinghouseState; the perp user state is not meaningful. |
Build for standard mode. Support unified mode behind a config flag only if you want it: the treasurer then does nothing, and the risk manager computes the margin ratio the way Hyperliquid's account-modes page describes.
#Markets
Read every market property from Hyperliquid at start-up (spotMeta, meta). Never hard-code an index you can look up.
| HXMR/USDC spot | XMR perp | |
|---|---|---|
| Find it by | the pair whose base token has token ID 0x700beac50c950503f401d218e52014e7 (token index 1339). Today that is @1193. Match the token ID, not the name: other tokens carry XMR in their names. |
the entry named exactly XMR in meta of the main perp DEX (not flx:XMR or other builder-deployed DEXs) |
| Coin name (info, WebSocket) | @1193 |
XMR |
| Asset ID for orders | 10000 + spot index (11193) |
its index in meta.universe |
| Size decimals | szDecimals from spotMeta (5) |
szDecimals from meta |
| Price | ≤ 5 significant figures and ≤ 8 − szDecimals decimals |
≤ 5 significant figures and ≤ 6 − szDecimals decimals |
| Minimum order | 10 USDC of value | 10 USDC of value |
| Leverage | none | maxLeverage from meta; set yours with updateLeverage (cross) |
| Fees | userSpotAddRate (maker), userSpotCrossRate (taker) |
userAddRate (maker), userCrossRate (taker) |
Read your own fee rates from the userFees info request at start-up and every hour: they fall as your volume grows. Round prices and sizes with one tested function per market; an order with one decimal too many is rejected.
#Fair value
The bot needs one number: what HXMR is worth now.
- Reference: the XMR perp mid on Hyperliquid,
(best bid + best ask) / 2from theXMRbook. It is liquid, on the same venue and in the same WebSocket. Optionally blend in an external XMR/USD price (a centralized exchange's ticker) as a sanity check. The perp can trade a little above or below the spot price of XMR; in normal conditions that gap is small next to the spread, and the external price catches the times it is not. - Basis: HXMR is redeemable 1:1 for XMR through the bridge, so it should trade near XMR, but within a band set by the bridge fees and the transfer delay. Add a configurable
basis_bps(start at 0). Optionally track an exponential moving average ofhxmr_mid / perp_mid − 1, clamp it to±max_basis_bps, and use it as the basis. - Funding moves the perp away from the spot price of XMR. With hourly funding that is usually small; ignore it in fair value at first and record it in PnL.
- Staleness: if the perp book has not updated for
max_feed_age_s, the fair value is unknown. Cancel all quotes and stop until it recovers.
fair = perp_mid × (1 + basis_bps / 10000)#Quoting
Each cycle (on a book update, at most every min_requote_interval_ms):
inventory_dev = (hxmr_balance − hxmr_target) / hxmr_max_dev # −1 … +1, clamped
reservation = fair × (1 − skew_bps × inventory_dev / 10000) # hold too much HXMR → quote lower
half_spread = max(min_half_spread_bps,
spot_maker_fee_bps + perp_taker_fee_bps + expected_hedge_slippage_bps + edge_bps)
bid_i = reservation × (1 − (half_spread + i × level_step_bps) / 10000) # i = 0 … levels−1
ask_i = reservation × (1 + (half_spread + i × level_step_bps) / 10000)Example: hxmr_target: 1.0, hxmr_max_dev: 1.0, skew_bps: 30. Holding 2 HXMR gives inventory_dev = +1, so both quotes move 0.30% lower: the bid gets less attractive and the ask more attractive, and the balance drifts back toward 1.
expected_hedge_slippage_bps is what the hedge loses against fair value. Start with a guess, then replace it with the average the PnL report measures (the hedge's fill price against fair value at the time of the spot fill).
- Post-only (
Alo) on every quote, so each fill pays the maker rate, never the taker rate. - Sizes from config, per level. Skip a level whose value is under 10 USDC, a bid the spot USDC cannot pay, or an ask the HXMR balance cannot cover.
- Inventory skew keeps the HXMR balance near
hxmr_target, so the bot can always quote both sides. With the hedge, the price risk is already covered; skew is about keeping both sides funded. - Do not cancel and replace on every tick. Keep each resting order unless its ideal price has moved more than
requote_threshold_bpsor its size changed. Send all changes of one cycle in a singlebatchModify, and give every order a client order ID (cloid) so you can match fills and updates to levels. - Never cross: drop a bid at or above the best ask (and the reverse) instead of sending it;
Alorejects it anyway and the rejection still costs a request.
#Rate limits shape the design
Hyperliquid limits each address to 1 action per 1 USDC traded since the account opened, plus a starting buffer of 10,000. A batch of n orders counts as n. A new bot that cancels and replaces two orders every 5 seconds spends about 69,000 actions a day and runs out of buffer within hours; after that the address may send one action every 10 seconds.
- Requote only on real moves (
requote_threshold_bps), usebatchModify, and keep the number of levels small at first. - Read
userRateLimit(nRequestsUsed,nRequestsCap) every minute. When the remaining budget falls underrate_reserve, widenrequote_threshold_bpsautomatically and stop adding levels. Hyperliquid keeps a separate, larger allowance for cancels, so the bot can always pull its quotes. - Hedge volume on the perp counts as traded volume too, and raises the allowance.
- Batch quotes (
Alo) separately from hedges (Ioc): Hyperliquid gives priority to batches that contain onlyAloorders.
Hyperliquid also limits requests per IP address, separately from the per-address budget: a weight of 1,200 per minute across REST calls. Book, mid and balance reads (l2Book, allMids, clearinghouseState, spotClearinghouseState) weigh 2, most other info requests 20, and an exchange action 1 plus 1 per 40 orders in a batch. WebSockets allow 10 connections and 1,000 subscriptions per IP. Take prices and fills from the WebSocket, poll balances no more often than the treasurer needs, and back off on an HTTP 429 instead of retrying at once. Check Hyperliquid's rate-limit page for changes.
#Hedging with the XMR perp
The bot's XMR exposure is everything that moves with the Monero price:
net_delta = hxmr_total # spot HXMR, including what rests in asks
+ perp_position # signed size of the XMR perp (short is negative)
+ xmr_in_flight # XMR or HXMR inside open bridge orders (from the treasurer)
+ xmr_held # native XMR you count as the bot's inventory (config or wallet RPC)
− target_delta # 0 for a fully hedged bookYour starting HXMR is hedged too. net_delta counts every HXMR in the account, including what you bridged in before the first quote. With target_delta: 0 the bot shorts the perp against all of it at start-up. Bridge in 10 HXMR at $450 and the bot opens a 10 XMR short straight away, which at 2× with a 25% buffer needs about $3,375 of USDC on the perp side.
If you would rather keep that exposure, set target_delta to the XMR you want left unhedged. With target_delta: 10 the bot starts with no perp position and only hedges changes from there; you then carry the price risk on those 10 XMR yourself.
- When
abs(net_delta) × fair ≥ hedge_threshold_usd(and at least 10 USDC), trade−net_deltaon the perp, rounded down to itsszDecimals. Carry the remainder to the next check. - Order type:
Ioclimit at the best opposite price plus at mosthedge_max_slippage_bps. An optional passive mode postsAloat the best price on its own side first and falls back toIocafterpassive_hedge_timeout_s. - Mark the order reduce-only when it only shrinks the existing perp position.
- Hedge on fills (from
userFills) and also on a timer everyhedge_check_s, from fresh balances, so a missed fill message cannot leave the book unhedged. - Set cross margin and
leveragefrom config (at mostmaxLeverage) withupdateLeverageat start-up. Low leverage, such as 2×, keeps the liquidation price far away; the treasurer keeps enough margin behind it. - Funding: a short perp pays funding when the rate is negative and receives it when positive, every hour. Record it from
userFunding. Ifabs(predicted funding)stays abovemax_funding_bps_per_hour, alert: holding the hedge has become expensive.
#Moving USDC between spot and perps
In standard mode the USDC is in two places. The treasurer keeps each one at its target, every treasury_interval_s:
spot_usdc_free = spot USDC total − hold # hold = USDC locked in resting bids
spot_target = bid_budget_usdc × (1 + spot_buffer)
perp_notional = abs(perp_position) × perp_mark
perp_target = perp_notional / leverage + perp_notional × stress_move # margin + room for a move
perp_equity = clearinghouseState.marginSummary.accountValue
perp_free = clearinghouseState.withdrawableExample: a 2 XMR short at $450, leverage: 2, stress_move: 0.25. perp_notional is $900, so perp_target is $450 + $225 = $675. With low_band: 0.8 the treasurer tops the perp balance up once it falls under $540. With high_band: 1.5 it sends USDC back to spot once more than $1,012 is free there and the bids are short of USDC.
Decide in this order, and move at most one transfer per interval:
- Hedge first. If
perp_equity < perp_target × low_band, movemin(perp_target − perp_equity, spot_usdc_free − spot_floor)from spot to perps. If spot does not have it, the risk manager cancels the bids (which releases their hold) and the treasurer moves it next interval. If it is still short, stop quoting bids: no new XMR exposure until the hedge is safe. - Then the bids. If
perp_free > perp_target × high_bandandspot_usdc_free < spot_target, move the excess from perps to spot, never taking perps underperp_target. - Never move less than
min_transfer_usdc, more thanmax_transfer_usdc, or more thanmax_daily_transfer_usdcin a day; and waittransfer_cooldown_safter each transfer. - Read balances again after each transfer before deciding anything else. Never assume a transfer succeeded.
The transfer is the usdClassTransfer action (toPerp: true to perps, false to spot), signed by the bot's key. The risk manager caps the bid ladder at max_bid_budget (see How much USDC a hedged bid needs), so a full sweep of the bids can always be hedged.
#When the USDC runs out
One-sided selling can use up the whole bid budget. The bot handles that as a normal state, not an error:
- Keep the asks on the book. They are how USDC comes back.
- Stop quoting bids while
max_bid_budgetis under one minimum-size order, and start again by itself when USDC returns. - Send an alert, because a human may want to add USDC or redeem HXMR.
- Do not close the hedge to free margin. That turns a hedged book into a bet on the XMR price.
#Bridge rebalancing (optional)
With the hedge, a large HXMR balance carries no price risk, but it ties up capital and leaves the bid side short of USDC. The treasurer can turn it back into XMR, or top HXMR up, through the Wagyu bridge:
- Too much HXMR (above
hxmr_max): create a withdrawal (POST /v2/bridgeswith"direction": "withdraw"and"senderAddress"set to the bot's account), wait for itsxmr1DepositAddressto be set (the field keeps its older name; it is the HXMR deposit address), thenspotSendthe HXMR to it from the bot's account (tokenHXMR:0x700beac50c950503f401d218e52014e7). Send each order's HXMR in one transfer from that one address, or a fee waiver does not apply. While the order is open its amount counts inxmr_in_flight, so the hedge does not change. When the XMR lands it counts inxmr_heldand stays hedged; if you sell it elsewhere instead, the hedger closes the matching perp. Without a fee waiver a withdrawal costs 2% (read the live figure fromGET /v2/bridges/terms), more than the spread the bot earned on that HXMR: leavebridge.enabled: falseuntil the waiver is confirmed for the bot's account. - Too little HXMR (below
hxmr_min): create a deposit order and send XMR to itsdepositAddressfrom a Monero wallet, for example throughmonero-wallet-rpc, or alert a human to send it. - Before each order, read
GET /v2/bridges/terms: skip the direction if it is off, and skip amounts under the minimum. A409withcode: "paused"means the direction is switched off: stop trying until the terms say it is on again. - Count bridge orders that are still open in
xmr_in_flight, and track each one withGET /v2/bridges/{id}until it iscompleted. Store theirorderIdandsessionId. - Never retry a bridge order creation automatically: a retry after a timeout can create a second order.
#Risk limits and kill switch
The kill switch is one command that stops the bot safely: it cancels every open order on both markets, stops quoting, and exits. Give it two triggers: a signal (Ctrl-C, or kill from a supervisor) and a file named STOP in the bot's folder that the main loop checks every second. It leaves the hedge in place, so stopping the bot does not change your exposure. To restart, remove the file and start the bot; start-up reconciles balances and the hedge before the first quote.
| Limit | What happens |
|---|---|
Feed older than max_feed_age_s (perp book, HXMR book, or user updates) |
Cancel all quotes; resume when fresh. |
abs(net_delta) × fair above max_unhedged_usd |
Stop quoting the side that adds to it; alert. |
abs(perp_position) × mark above max_perp_notional_usd |
Cancel the quotes that would grow the position (bids when short, asks when long); alert. |
Margin ratio (crossMaintenanceMarginUsed / accountValue) above max_margin_ratio |
Cancel bids, treasurer moves USDC to perps, alert. |
HXMR mid away from fair by more than max_gap_bps for gap_window_s |
Widen to gap_half_spread_bps; alert. |
Loss today above max_daily_loss_usd |
Cancel everything and stop until a human restarts. |
Rate-limit budget under rate_reserve |
Requote less (see rate limits). |
| Any unhandled error in the main loop | Cancel all quotes, then exit; a supervisor restarts the bot. |
Hyperliquid's dead man's switch (scheduleCancel) cancels all open orders at a time you set if you do not push it back. Use it as a second line, but note Hyperliquid caps how many times a day it can trigger; the bot's own watchdog is the first line.
On start-up, before quoting: cancel every open order of the account on both markets, read all balances and positions, recompute net_delta and hedge it, and load open bridge orders from storage.
#PnL accounting
Record everything in a local database (SQLite is enough) and report it every few minutes and once a day:
| Part | Source |
|---|---|
| Spot fills (price, size, fee) | userFills for @1193 |
| Perp fills, realised PnL, fees | userFills for XMR (closedPnl, fee) |
| Funding | userFunding |
| Bridge fees | each bridge order's bridgeSettlement |
| Mark-to-market | hxmr_total × hxmr_mid + perp unrealised PnL + USDC (spot + perps) + XMR in flight × fair |
Report the spread captured and the hedge cost separately: if the hedge costs more than the spread earns, widen the spread.
#How much USDC a hedged bid needs
A bid that fills costs more than its own value, because the hedge needs margin as well:
usdc_per_1_usd_of_bids = 1 + 1 / leverage + stress_move| Leverage | stress_move |
USDC needed per $1 of bids |
|---|---|---|
| 2 | 0.25 | $1.75 |
| 3 | 0.25 | $1.58 |
| 5 | 0.25 | $1.45 |
So the example bid_budget_usdc: 500 needs about $875 of USDC in the account, not $500. Size the bids from the whole account, not from the spot balance alone:
max_bid_budget = (spot_usdc + perp_equity − perp_target) / (1 + 1 / leverage + stress_move)If the bids are sized from spot USDC only, a sweep of the whole ladder spends the spot balance on HXMR and leaves nothing to send to perps. The hedge orders are then rejected for margin and the bot is unhedged at the worst moment. The risk manager caps the ladder with this formula on every cycle.
#Configuration
One file, with every number the bot uses. The values below are placeholders to show the shape, not advice.
mode: dry_run # dry_run | live
account:
main_address: "0x…" # the key comes from .env: HL_PRIVATE_KEY
account_mode: standard # standard | unified
fair_value:
basis_bps: 0
basis_ema: { enabled: false, half_life_s: 600, max_basis_bps: 150 }
max_feed_age_s: 5
quoting:
levels: 2
size_hxmr: [0.1, 0.2]
min_half_spread_bps: 40
edge_bps: 10
expected_hedge_slippage_bps: 5
level_step_bps: 25
skew_bps: 30
hxmr_target: 1.0
hxmr_max_dev: 1.0
requote_threshold_bps: 8
min_requote_interval_ms: 1000
rate_reserve: 2000
hedge:
target_delta: 0 # XMR of exposure to leave unhedged
leverage: 2
hedge_threshold_usd: 25
hedge_max_slippage_bps: 15
passive_hedge_timeout_s: 0 # 0 = always IOC
hedge_check_s: 10
max_funding_bps_per_hour: 2
treasury:
interval_s: 45
bid_budget_usdc: 500
spot_buffer: 0.2
spot_floor: 20
stress_move: 0.25
low_band: 0.8
high_band: 1.5
min_transfer_usdc: 20
max_transfer_usdc: 2000
max_daily_transfer_usdc: 10000
transfer_cooldown_s: 120
bridge:
enabled: false
hxmr_min: 0.5
hxmr_max: 3.0
risk:
max_unhedged_usd: 100
max_perp_notional_usd: 5000
max_margin_ratio: 0.5
max_gap_bps: 300
gap_window_s: 120
gap_half_spread_bps: 150
max_daily_loss_usd: 100#Build order
Build and test in this order. Each milestone runs on its own before the next starts.
- Market data and rounding. Load both markets from
spotMeta/meta(HXMR by token ID), subscribe to both books and the user streams, and print fair value. Unit tests: price and size rounding for both markets (significant figures, decimals, integer prices), market lookup by token ID. - Quote engine, pure. A function from (fair, balances, config, resting orders) to the batch of changes. Table tests: skew direction, levels under 10 USDC dropped, no crossed quotes, no change inside
requote_threshold_bps. - Dry run. Run 1 and 2 on live data, logging the orders it would place and the rate-limit budget it would spend per hour. Run it for a day.
- Live quoting, no hedge, tiny size, with the kill switch and start-up cancel. Watch it on app.wagyu.xyz. One process, one key: splitting parts into separate processes is an optional hardening step after everything works.
- Hedger. Pure
net_deltaand hedge-size functions with tests (rounding down, remainder carried, reduce-only), then live. - Treasurer. Pure decision function with table tests for every rule above (hedge first, bands, caps, cooldown), then live with small caps.
- PnL and reports.
- Bridge rebalancing, last, behind
bridge.enabled. Tests use recorded API answers; no real bridge order in tests.
Project layout that keeps each part testable:
| File | Does |
|---|---|
mm/config.py |
Loads and validates config.yaml (pydantic). |
mm/markets.py |
Market lookup by token ID, price and size rounding. |
mm/feeds.py |
WebSocket subscriptions and staleness. |
mm/fair.py |
Fair value and basis. |
mm/quoter.py |
Pure quote engine, then order sync (batchModify, cloids). |
mm/hedger.py |
Pure hedge sizing, then execution. |
mm/treasurer.py |
Pure rebalancing decisions, then usdClassTransfer and spotSend. |
mm/bridge.py |
Wagyu bridge client: terms, quote, create, get. |
mm/risk.py |
Limits, kill switch, watchdog. |
mm/pnl.py |
Fills, funding, bridge fees, mark-to-market (SQLite). |
mm/main.py |
Wiring, exit codes a supervisor can act on. |
tests/ |
One test file per module above. |
#Hyperliquid references
- Exchange endpoint:
order,batchModify,cancel,scheduleCancel,updateLeverage,usdClassTransfer,spotSend,approveAgent. - Info endpoint:
meta,spotMeta,clearinghouseState,spotClearinghouseState,openOrders,userFills,userFunding,userFees,userRateLimit. - WebSocket:
l2Book,userFills,orderUpdates. - Tick and lot size, rate limits, nonces and API wallets, account modes, fees.
- Python SDK: hyperliquid-python-sdk.
Questions, a fee waiver or a larger setup: t.me/wagyu_support.