HIP-4 Outcome Trading Bot (Rust template)
A latency-first starter bot for HIP-4 outcome markets on Hyperliquid, the prediction markets traded on outcome.xyz.
Use it as a base for your own strategies. Venue, execution, risk and strategy code live in separate layers, and every trading parameter is set in .env.
Out of the box it can:
| Mode | What it does |
|---|---|
markets |
List live outcome markets that match your filters (venue, type, underlying, ...) |
watch |
Stream the selected market's top of book, with exchange-to-local lag |
account |
Show balances (USDC and +<enc> outcome tokens) and open orders |
buy / sell |
Send one order: market (IOC + slippage) or limit (Gtc / Ioc / Alo) |
cancel |
Cancel open orders on the selected market, or on every outcome market |
strategy |
Event-driven threshold strategy (entry, take-profit, stop-loss, pre-expiry exit) that rolls to the next market automatically |
⚠️ Trading is risky and this is a template, not financial advice. Start withDRY_RUN=true, then test onHL_NETWORK=testnet, then go live with small sizes.
How HIP-4 maps to the code
The official asset-id encoding is implemented in venue/meta.rs:
encoding = 10 * outcome + side side 0 = YES, side 1 = NO
coin = "#<encoding>" l2Book / bbo / orders e.g. #464730
token = "+<encoding>" spot balances e.g. +464730
asset = 100_000_000 + encoding order "a" field e.g. 100464730
- Markets come from
POST /info {"type":"outcomeMeta"}. outcome.xyz's markets have"venue":"out". Native recurring markets (BTC/ETH/SOL/HYPE daily) have no venue. Recurring markets get a new outcome id every instance, so by default the bot selects by filter at runtime and doesn't hard-code an id. - Orders use the standard Hyperliquid
orderaction: L1-signed with EIP-712Agent, priced as a probability, with whole-share sizes and a $10 minimum value. - Selling requires holding the side token. To bet against an outcome, buy its NO side (
OUTCOME_SIDE=no). - Settlement is automatic. When a market expires, the bot leaves it and, with
AUTO_ROLL=true, picks the next match.
How a trade flows
WS bbo feed ──► watch<Book> (latest only) ──► Engine wakes on every top-of-book change
│
Strategy::on_book(ctx) ───┘──► Intent { side, size, price, reason }
│
Executor: price (ask+slippage / limit) ─► round (5 sig figs) ─► size (floor) ─► RiskManager.check
│
msgpack ─► keccak ─► EIP-712 ─► secp256k1 (pure CPU, ~0.1 ms)
│
ws "post" on a pre-warmed socket ──(fail)──► HTTP POST with the identical signed body
│
statuses ─► Filled / Resting / NoFill / Rejected / Unknown ─► Report + latency breakdown
Project layout
src/
├── main.rs wiring + modes
├── config.rs typed .env loading + validation (all parameters)
├── types.rs Side, OutcomeSide, Tif, Intent, Book, OrderStatus, Report, Timings
├── util.rs clocks, UTC calendar math (no chrono)
├── signing.rs L1 action signing (msgpack + keccak + EIP-712 + k256)
├── risk.rs pre-trade limits + circuit breaker
├── execution.rs intent -> price/size -> risk -> sign -> send -> parse
├── engine.rs event-driven strategy loop, position reconcile, expiry/roll
├── strategy/
│ ├── mod.rs Strategy trait + Ctx
│ └── threshold.rs reference strategy
└── venue/ everything Hyperliquid-specific
├── meta.rs outcomeMeta, Instrument encoding, market selection
├── info.rs /info: meta, balances, open orders, l2Book
├── exchange.rs /exchange: nonces, signing, transport, status parsing
├── wire.rs action wire structs, float_to_wire, price/size rounding
├── ws.rs ws connect + order-post transport (reconnect, ping)
└── feed.rs streaming top of book (bbo / l2Book)
Latency choices
| Area | What the template does |
|---|---|
| Market data | Uses a dedicated websocket on bbo, the smallest frames. It publishes into a watch channel, so the strategy always sees the latest book and never a backlog. Consumers wake only when the top of book actually changes. |
| Decision loop | Event-driven. It reacts to each book change immediately, with no polling interval. A signal that appears during the cooldown fires the moment the cooldown ends. |
| No I/O on the loop | The only network call on the strategy loop is the order. Position reconciliation runs in a background task, so a slow /info call can never delay a stop-loss. |
| Logging | Log lines go to a background writer thread (tracing-appender), and nothing is logged between the decision and the send. |
| Order transport | Orders go out as {"method":"post"} on a separate, pre-warmed websocket: one frame on an open TCP connection, never stuck behind market data. |
| Safe fallback | If the websocket fails or times out, the same signed body is re-sent over HTTP. Hyperliquid rejects a reused nonce, so a fallback can never double-execute. |
| Signing | Constants (domain separator, type hash, source hash) are computed once at startup. Each order costs one msgpack encode, two keccaks and one ECDSA sign, with no ethers/alloy dependency. |
| Sockets | Both use TCP_NODELAY. HTTP uses a keep-alive pool with HTTP/2 pings. Websockets ping every 15 s and reconnect with backoff. |
| Hot path | Config is parsed once, metadata is fetched only at startup and on roll, and the exchange calls nothing else while trading. |
| Staleness guards | When the feed disconnects it publishes None, so the strategy can't trade on a frozen book. FEED_STALE_MS and optionally ORDER_EXPIRES_AFTER_MS (expiresAfter) also stop decisions that arrive late. |
| Build | lto = "fat", codegen-units = 1, panic = "abort". |
| Observability | Every order logs book_age / build+sign / send / total. BOT_MODE=watch shows feed lag. |
For production, run on a VPS close to Hyperliquid's API servers (Tokyo, AWS ap-northeast-1, is the usual choice) and keep the clock NTP-synced.
Setup
cp .env.example .env # then edit
cargo build --release
./target/release/hip4-bot # mode comes from BOT_MODE in .envAny setting can be overridden for one run: BOT_MODE=watch ./target/release/hip4-bot.
Build requirements: Rust 1.82 or newer. ring (TLS crypto) needs a C compiler:
- Linux:
build-essential(apt install build-essential pkg-config) - Windows: the MSVC toolchain (Visual Studio Build Tools, "Desktop development with C++") with
rustup default stable-msvc. The GNU toolchain also needs a full MinGW-w64 (gcc + binutils) onPATH.
Recommended first run
BOT_MODE=marketslists live markets. AdjustMARKET_VENUE/MARKET_CLASS/MARKET_UNDERLYING, or pinOUTCOME_ID.BOT_MODE=watchchecks that the book streams and shows your lag.BOT_MODE=accountwithHL_ACCOUNT_ADDRESSchecks balances.BOT_MODE=buywithDRY_RUN=trueshows the exact order, signature timings and a simulated fill.- Switch to
HL_NETWORK=testnetwith a funded testnet account andDRY_RUN=false. - Go live with small sizes.
Keys
Use an API wallet (app.hyperliquid.xyz → API). It can trade but not withdraw.
Set its key as HL_PRIVATE_KEY and your main address as HL_ACCOUNT_ADDRESS. Balances and orders belong to the main account, and the bot reads positions from it.
Use one API wallet per running bot process, because nonces are tracked per signer.
Writing a strategy
Implement the trait in src/strategy/your_strategy.rs:
pub trait Strategy: Send {
fn name(&self) -> &'static str;
fn on_book(&mut self, ctx: &Ctx) -> Option<Intent>; // book, position, instrument, time to expiry
fn on_report(&mut self, _report: &Report) {} // fills / rejections
fn on_new_market(&mut self, _instrument: &Instrument) {} // after a roll
}Return an Intent:
Intent {
side: Side::Buy,
size: SizeSpec::Notional(12.0), // or Shares(n) / All
price: PriceSpec::Market { slippage: 0.02 }, // or Limit { price, tif }
reason: "my_signal",
}Then select it in build_strategy() in main.rs. Strategies never touch signing, rounding or the network, so they can be unit-tested with a hand-built Book (see strategy/threshold.rs).
Parameters
Every parameter is documented inline in .env.example. The groups:
- Mode / safety:
BOT_MODE,DRY_RUN - Network:
HL_NETWORK,HL_API_URL,HL_WS_URL,HTTP_TIMEOUT_MS - Account:
HL_PRIVATE_KEY,HL_ACCOUNT_ADDRESS,HL_VAULT_ADDRESS - Market:
OUTCOME_ID,OUTCOME_SIDE,MARKET_VENUE,MARKET_CLASS,MARKET_UNDERLYING,MARKET_PERIOD,MARKET_SEARCH,MIN_TIME_TO_EXPIRY_SECS,AUTO_ROLL - Orders:
ORDER_TYPE,ORDER_SIZE_USD,ORDER_SHARES,SELL_SHARES,LIMIT_PRICE,TIME_IN_FORCE,SLIPPAGE,SZ_DECIMALS,PRICE_TICK,CANCEL_SCOPE,BUILDER_ADDRESS,BUILDER_FEE_TENTHS_BP - Latency:
ORDER_TRANSPORT,WS_POST_TIMEOUT_MS,ORDER_EXPIRES_AFTER_MS,FEED_CHANNEL,WS_PING_INTERVAL_MS,FEED_STALE_MS - Strategy:
ENTRY_PRICE,TAKE_PROFIT_PRICE,STOP_LOSS_PRICE,EXIT_BEFORE_EXPIRY_SECS,MIN_ENTRY_TIME_TO_EXPIRY_SECS,MAX_ENTRIES_PER_MARKET,MIN_POSITION_SHARES,COOLDOWN_MS,POSITION_REFRESH_MS - Risk:
MAX_ORDER_USD,MAX_POSITION_USD,MIN_ORDER_USD,MAX_BUY_PRICE,MIN_SELL_PRICE,MAX_TRADES_PER_DAY,MAX_CONSECUTIVE_FAILURES
Risk notes:
- Buys are checked against size, price, position and daily-trade caps.
- Sells are only checked against
MIN_SELL_PRICEand your holdings, so an entry rule can never block a stop-loss or take-profit. - An IOC order that finds no liquidity doesn't count as a failure. Rejections and unanswered orders do, and trip the circuit breaker.
- If an order gets no answer (a timeout or a dropped connection), it may still have executed. The report says
UNKNOWN, and the bot re-reads the position immediately. It places no new orders until that read confirms the holding, so it can't double-buy.
Tests
cargo testThe signing tests use the official vectors from hyperliquid-python-sdk (tests/signing_test.py): mainnet, testnet, vault, cloid, and the raw connection-id hash. Any change that breaks msgpack field order or number formatting fails them right away.
There are also tests for wire formatting and price rounding, outcomeMeta parsing (including real mainnet shapes), market selection and roll, risk limits, the circuit breaker, websocket frame parsing, exchange status parsing and the strategy's decisions.
Known limits
- HIP-4 is new and its documentation is still moving. Tick size, minimum value and fees are taken from the docs and live books as of 2026-11.
PRICE_TICKandMIN_ORDER_USDlet you adjust without a rebuild. - The dry-run fill model only crosses the top level, so it's conservative.
- Split / merge / negate (
userOutcome) actions aren't wired yet. The signer already handles any L1 action, so adding one is a small struct invenue/wire.rs.