Crypto strategies
Crypto strategies on Hyperliquid are written in Rust against rq_sdk::crypto.
Every price, quantity and balance is an exact decimal (Fixed), so there is no
floating-point rounding in your orders.
Perpetual paper bots run ordinary impl Strategy code, not CryptoStrategy;
spot paper bots run a CryptoStrategy (rq_sdk::crypto).
The trait
Your strategy is a struct that implements CryptoStrategy and Default.
pub trait CryptoStrategy: Default {
fn on_event(&mut self, input: &Callback) -> Vec<Command>;
fn checkpoint(&self) -> Vec<u8>;
fn restore(&mut self, state: &[u8]) -> Result<(), String>;
fn configure(&mut self, parameters: &str) -> Result<(), String>; // optional
fn param_schema() -> &'static str; // optional
}
on_eventruns once per event and returns the orders you want to send.checkpointandrestoresave and reload your state. A bot that restarts must make the same decisions, so save every field you use.configurereceives your parameters as JSON before the first event. Without parameters you can leave it out.
You do not need to export anything yourself; Roboquant adds the export when it compiles your strategy.
Callback
Each call gets a Callback:
input.envelope.event: what happened. One ofBar(a closed bar: open, high, low, close, volume,close_ns),Trade,Book,Mark,Funding,FundingIncome,Fill,Order,StatusorTimer.input.account: your account after the event (AccountView).input.rules: the instrument rules (InstrumentRules), orNone.
Times are Unix nanoseconds. Time::from_us(ns / 1_000) gives a Time with the
strategy-timezone helpers.
AccountView
balances: free assets by name, for exampleUSDCand, on spot, the coin.position_quantity: signed perpetual position (positive is long). On spot, your coins are inbalances.entry_cost,isolated_collateral,realized_pnl,funding_received.
InstrumentRules
price_step,quantity_step,min_notional,max_sig_figs.rules.round_price(price, Rounding::Floor)puts a price on the venue's grid. Hyperliquid allows at most 5 significant figures on a non-integer price.
An order that breaks a rule (price grid, quantity step, minimum size or the 10 USDC minimum order) is skipped with a warning and the run continues.
Fixed
Fixed is a checked decimal with 18 decimal places. Build one with
"0.001".parse().unwrap() or Fixed::from_integer(5). Arithmetic is checked:
checked_add, checked_sub, checked_mul, checked_div return a Result.
quantize(step, Rounding::Floor) rounds a quantity down to a step.
Commands
Command::Submit { side, quantity, limit_price, time_in_force, reduce_only }:limit_price: Noneis a market order.time_in_forceisGtc,IocorFok.submit_stop(side, quantity, trigger_price, reduce_only): a stop-market order.Command::Cancel { client_id }: cancel one of your orders.
reduce_only is for perpetuals only; spot refuses it. Spot is long-only.
Example: perpetual
Buys 0.001 BTC when a bar closes above the previous close, and closes the position when a bar closes below it.
use rq_sdk::crypto::*;
#[derive(Default)]
pub struct Momentum {
last_close: Option<Fixed>,
}
impl CryptoStrategy for Momentum {
fn on_event(&mut self, input: &Callback) -> Vec<Command> {
let Event::Bar { close, .. } = &input.envelope.event else { return vec![] };
let close = *close;
let mut orders = vec![];
if let Some(previous) = self.last_close {
let position = input.account.position_quantity;
if close > previous && position == Fixed::ZERO {
orders.push(Command::Submit {
side: Side::Buy,
quantity: "0.001".parse().unwrap(),
limit_price: None,
time_in_force: TimeInForce::Ioc,
reduce_only: false,
});
} else if close < previous && position > Fixed::ZERO {
orders.push(Command::Submit {
side: Side::Sell,
quantity: position,
limit_price: None,
time_in_force: TimeInForce::Ioc,
reduce_only: true,
});
}
}
self.last_close = Some(close);
orders
}
fn checkpoint(&self) -> Vec<u8> {
serde_json::to_vec(&self.last_close.map(|value| value.to_string())).unwrap()
}
fn restore(&mut self, state: &[u8]) -> Result<(), String> {
let saved: Option<String> = serde_json::from_slice(state).map_err(|e| e.to_string())?;
self.last_close = match saved {
Some(text) => Some(text.parse().map_err(|_| "bad checkpoint".to_string())?),
None => None,
};
Ok(())
}
}
Example: spot
Buys 50 USDC of the coin when a bar closes above the previous close, and sells the whole coin balance when it closes below. Spot has no leverage and no shorting.
use rq_sdk::crypto::*;
#[derive(Default)]
pub struct SpotTrend {
last_close: Option<Fixed>,
}
impl CryptoStrategy for SpotTrend {
fn on_event(&mut self, input: &Callback) -> Vec<Command> {
let Event::Bar { close, .. } = &input.envelope.event else { return vec![] };
let close = *close;
let Some(rules) = &input.rules else { return vec![] };
let coin = input.account.instrument_id.rsplit('.').next().unwrap_or("")
.trim_end_matches("USDC").to_string();
let held = input.account.balances.get(&coin).copied().unwrap_or(Fixed::ZERO);
let mut orders = vec![];
if let Some(previous) = self.last_close {
if close > previous && held == Fixed::ZERO {
let budget: Fixed = "50".parse().unwrap();
if let Ok(quantity) = budget.checked_div(close)
.and_then(|q| q.quantize(rules.quantity_step, Rounding::Floor))
{
orders.push(Command::Submit {
side: Side::Buy,
quantity,
limit_price: None,
time_in_force: TimeInForce::Ioc,
reduce_only: false,
});
}
} else if close < previous && held > Fixed::ZERO {
if let Ok(quantity) = held.quantize(rules.quantity_step, Rounding::Floor) {
orders.push(Command::Submit {
side: Side::Sell,
quantity,
limit_price: None,
time_in_force: TimeInForce::Ioc,
reduce_only: false,
});
}
}
}
self.last_close = Some(close);
orders
}
fn checkpoint(&self) -> Vec<u8> {
serde_json::to_vec(&self.last_close.map(|value| value.to_string())).unwrap()
}
fn restore(&mut self, state: &[u8]) -> Result<(), String> {
let saved: Option<String> = serde_json::from_slice(state).map_err(|e| e.to_string())?;
self.last_close = match saved {
Some(text) => Some(text.parse().map_err(|_| "bad checkpoint".to_string())?),
None => None,
};
Ok(())
}
}
Spot pair ids look like HYPERLIQUID.SPOT.<BASE>USDC, so the coin's balance key
is the base name. Buy fees on spot are paid in the coin you buy, so a full sell
uses the balance you actually hold.