Skip to main content

df_hyperliquid_core/trade/orders/
mod.rs

1//! Orders: the wire every order type ends in ([`Order`], [`PlaceOrder`]), what an order's `t`
2//! says, its client id, and one module per type. A trailing stop is an action of its own
3//! ([`TrailingStop`]). Keys go in the order the venue hashes:
4//! `a b p s r t c` for an order, then `grouping`, then `builder` last.
5
6pub mod cloid;
7pub mod close;
8pub mod entry;
9pub mod limit;
10pub mod market;
11pub mod order_type;
12pub mod scale;
13pub mod tpsl;
14pub mod trailing;
15pub mod trigger;
16pub mod twap;
17
18pub use cloid::Cloid;
19pub use close::{Close, close};
20pub use entry::{OrderIntent, Price, order};
21pub use order_type::{Grouping, OrderType, Tif, Tpsl};
22pub use scale::{LEAST_LEVELS, MOST_LEVELS, Scale, scale};
23pub use tpsl::{Covers, TriggerIntent, trigger};
24pub use trailing::{BadTrailingStop, Retracement, TrailingStop};
25pub use trigger::{Exit, ExitPrice, TRIGGER_SLIPPAGE};
26pub use twap::{MINIMUM_TWAP_VALUE, Twap, TwapCancel, TwapIntent, twap};
27
28use crate::trade::builder::{Builder, OverCap};
29use crate::utils::sign::{L1Action, Map, Value};
30use crate::utils::{Asset, AssetKind, Dec};
31
32/// Which way an order trades, the same `B` and `A` the reads and the socket carry.
33pub use crate::markets::Side;
34
35/// One order on any market. Price and size go on the wire exactly as given,
36/// so put them on the asset's grid first ([`crate::utils::Grid`]).
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct Order {
39    asset: Asset,
40    side: Side,
41    price: Dec,
42    size: Dec,
43    reduce_only: bool,
44    order_type: OrderType,
45    cloid: Option<Cloid>,
46}
47
48impl Order {
49    /// A limit order that rests or crosses as `tif` says.
50    #[must_use]
51    pub const fn limit(asset: Asset, side: Side, price: Dec, size: Dec, tif: Tif) -> Order {
52        Order { asset, side, price, size, reduce_only: false, order_type: OrderType::Limit(tif), cloid: None }
53    }
54
55    /// A market order: `FrontendMarket`, always, at `bound`, the worst price
56    /// the trader takes (the reference moved by the slippage, on the grid; on
57    /// an outcome, the edge of the range). Never `Gtc`: a `Gtc` at the bound
58    /// would rest on the book for whatever did not fill.
59    #[must_use]
60    pub const fn market(asset: Asset, side: Side, bound: Dec, size: Dec) -> Order {
61        Order::limit(asset, side, bound, size, Tif::FrontendMarket)
62    }
63
64    /// A take profit or stop loss: fires when the mark crosses `trigger`, as
65    /// a market order bounded by `price` or as a limit at it. A size of zero
66    /// on a reduce-only trigger means the whole position.
67    #[must_use]
68    pub const fn trigger(
69        asset: Asset,
70        side: Side,
71        price: Dec,
72        size: Dec,
73        trigger: Dec,
74        tpsl: Tpsl,
75        is_market: bool,
76    ) -> Order {
77        Order {
78            asset,
79            side,
80            price,
81            size,
82            reduce_only: false,
83            order_type: OrderType::Trigger { is_market, trigger, tpsl },
84            cloid: None,
85        }
86    }
87
88    /// Only ever shrinks the position.
89    #[must_use]
90    pub const fn reduce_only(mut self) -> Order {
91        self.reduce_only = true;
92        self
93    }
94
95    /// Sent with this client order id.
96    #[must_use]
97    pub const fn with_cloid(mut self, cloid: Cloid) -> Order {
98        self.cloid = Some(cloid);
99        self
100    }
101
102    /// `a`: the asset id.
103    #[must_use]
104    pub const fn asset(&self) -> Asset {
105        self.asset
106    }
107
108    /// `b`: buy or sell.
109    #[must_use]
110    pub const fn side(&self) -> Side {
111        self.side
112    }
113
114    /// `p`: the limit price, a market order's bound, or a trigger's fill price.
115    #[must_use]
116    pub const fn price(&self) -> Dec {
117        self.price
118    }
119
120    /// `s`: the size in the base asset; 0 on a whole-position take profit or stop loss.
121    #[must_use]
122    pub const fn size(&self) -> Dec {
123        self.size
124    }
125
126    /// `r`: whether it may only reduce a position.
127    #[must_use]
128    pub const fn is_reduce_only(&self) -> bool {
129        self.reduce_only
130    }
131
132    /// `t`: a limit's time in force, or a trigger.
133    #[must_use]
134    pub const fn order_type(&self) -> OrderType {
135        self.order_type
136    }
137
138    /// `c`: the client order id; `None` when there is none.
139    #[must_use]
140    pub const fn cloid(&self) -> Option<Cloid> {
141        self.cloid
142    }
143
144    /// A limit order's TIF; `None` for a trigger.
145    #[must_use]
146    pub const fn tif(&self) -> Option<Tif> {
147        match self.order_type {
148            OrderType::Limit(tif) => Some(tif),
149            OrderType::Trigger { .. } => None,
150        }
151    }
152
153    /// Whether it is a market order: a `FrontendMarket` limit.
154    #[must_use]
155    pub const fn is_market(&self) -> bool {
156        matches!(self.order_type, OrderType::Limit(Tif::FrontendMarket))
157    }
158
159    /// Whether it is a trigger order: a take profit or stop loss.
160    #[must_use]
161    pub const fn is_trigger(&self) -> bool {
162        matches!(self.order_type, OrderType::Trigger { .. })
163    }
164
165    /// `a b p s r t c`, in the order the venue hashes; `c` only when there is one.
166    #[must_use]
167    pub fn wire(&self) -> Map {
168        Map::new()
169            .put("a", self.asset)
170            .put("b", self.side.is_buy())
171            .put("p", self.price.to_wire())
172            .put("s", self.size.to_wire())
173            .put("r", self.reduce_only)
174            .put("t", self.order_type.wire())
175            .put_some("c", self.cloid.map(Cloid::to_hex))
176    }
177}
178
179/// `order`: one or more orders, grouped, optionally through a builder.
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct PlaceOrder {
182    orders: Vec<Order>,
183    grouping: Grouping,
184    builder: Option<Builder>,
185}
186
187impl PlaceOrder {
188    /// A scale is one action with an order a level.
189    #[must_use]
190    pub fn new(orders: Vec<Order>) -> PlaceOrder {
191        PlaceOrder { orders, grouping: Grouping::Na, builder: None }
192    }
193
194    /// One order, grouped `na`.
195    #[must_use]
196    pub fn one(order: Order) -> PlaceOrder {
197        PlaceOrder::new(vec![order])
198    }
199
200    /// With this grouping.
201    #[must_use]
202    pub fn grouped(mut self, grouping: Grouping) -> PlaceOrder {
203        self.grouping = grouping;
204        self
205    }
206
207    /// Routed through `builder`, which the action names last.
208    #[must_use]
209    pub fn through(mut self, builder: Builder) -> PlaceOrder {
210        self.builder = Some(builder);
211        self
212    }
213
214    /// The orders, in the order sent.
215    #[must_use]
216    pub fn orders(&self) -> &[Order] {
217        &self.orders
218    }
219
220    /// How the orders relate.
221    #[must_use]
222    pub const fn grouping(&self) -> Grouping {
223        self.grouping
224    }
225
226    /// The builder it is routed through; `None` for none.
227    #[must_use]
228    pub const fn builder(&self) -> Option<Builder> {
229        self.builder
230    }
231
232    /// The builder's fee, when it is more than the venue lets a builder take
233    /// on these orders. One perp order holds the whole action to the perp cap.
234    #[must_use]
235    pub fn over_builder_cap(&self) -> Option<OverCap> {
236        let fee = self.builder?.fee();
237        let kind = AssetKind::strictest(self.orders.iter().map(Order::asset))?;
238        let cap = kind.builder_cap();
239        (fee > cap).then_some(OverCap { fee, cap, kind })
240    }
241}
242
243impl L1Action for PlaceOrder {
244    fn action(&self) -> Map {
245        Map::new()
246            .put("type", "order")
247            .put("orders", Value::array(self.orders.iter().map(Order::wire)))
248            .put("grouping", self.grouping.wire())
249            .put_some("builder", self.builder.as_ref().map(Builder::wire))
250    }
251}
252
253#[cfg(test)]
254#[path = "tests/order/mod.rs"]
255mod tests;