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    /// An order of any type: what [`Order::limit`] and [`Order::trigger`] build, from an
56    /// [`OrderType`] already chosen, such as one read back from [`Order::order_type`].
57    #[must_use]
58    pub const fn new(asset: Asset, side: Side, price: Dec, size: Dec, order_type: OrderType) -> Order {
59        Order { asset, side, price, size, reduce_only: false, order_type, cloid: None }
60    }
61
62    /// A market order: `FrontendMarket`, always, at `bound`, the worst price
63    /// the trader takes (the reference moved by the slippage, on the grid; on
64    /// an outcome, the edge of the range). Never `Gtc`: a `Gtc` at the bound
65    /// would rest on the book for whatever did not fill.
66    #[must_use]
67    pub const fn market(asset: Asset, side: Side, bound: Dec, size: Dec) -> Order {
68        Order::limit(asset, side, bound, size, Tif::FrontendMarket)
69    }
70
71    /// A take profit or stop loss: fires when the mark crosses `trigger`, as
72    /// a market order bounded by `price` or as a limit at it. A size of zero
73    /// on a reduce-only trigger means the whole position.
74    #[must_use]
75    pub const fn trigger(
76        asset: Asset,
77        side: Side,
78        price: Dec,
79        size: Dec,
80        trigger: Dec,
81        tpsl: Tpsl,
82        is_market: bool,
83    ) -> Order {
84        Order {
85            asset,
86            side,
87            price,
88            size,
89            reduce_only: false,
90            order_type: OrderType::Trigger { is_market, trigger, tpsl },
91            cloid: None,
92        }
93    }
94
95    /// Only ever shrinks the position.
96    #[must_use]
97    pub const fn reduce_only(mut self) -> Order {
98        self.reduce_only = true;
99        self
100    }
101
102    /// Sent with this client order id.
103    #[must_use]
104    pub const fn with_cloid(mut self, cloid: Cloid) -> Order {
105        self.cloid = Some(cloid);
106        self
107    }
108
109    /// `a`: the asset id.
110    #[must_use]
111    pub const fn asset(&self) -> Asset {
112        self.asset
113    }
114
115    /// `b`: buy or sell.
116    #[must_use]
117    pub const fn side(&self) -> Side {
118        self.side
119    }
120
121    /// `p`: the limit price, a market order's bound, or a trigger's fill price.
122    #[must_use]
123    pub const fn price(&self) -> Dec {
124        self.price
125    }
126
127    /// `s`: the size in the base asset; 0 on a whole-position take profit or stop loss.
128    #[must_use]
129    pub const fn size(&self) -> Dec {
130        self.size
131    }
132
133    /// `r`: whether it may only reduce a position.
134    #[must_use]
135    pub const fn is_reduce_only(&self) -> bool {
136        self.reduce_only
137    }
138
139    /// `t`: a limit's time in force, or a trigger.
140    #[must_use]
141    pub const fn order_type(&self) -> OrderType {
142        self.order_type
143    }
144
145    /// `c`: the client order id; `None` when there is none.
146    #[must_use]
147    pub const fn cloid(&self) -> Option<Cloid> {
148        self.cloid
149    }
150
151    /// A limit order's TIF; `None` for a trigger.
152    #[must_use]
153    pub const fn tif(&self) -> Option<Tif> {
154        match self.order_type {
155            OrderType::Limit(tif) => Some(tif),
156            OrderType::Trigger { .. } => None,
157        }
158    }
159
160    /// Whether it is a market order: a `FrontendMarket` limit.
161    #[must_use]
162    pub const fn is_market(&self) -> bool {
163        matches!(self.order_type, OrderType::Limit(Tif::FrontendMarket))
164    }
165
166    /// Whether it is a trigger order: a take profit or stop loss.
167    #[must_use]
168    pub const fn is_trigger(&self) -> bool {
169        matches!(self.order_type, OrderType::Trigger { .. })
170    }
171
172    /// `a b p s r t c`, in the order the venue hashes; `c` only when there is one.
173    #[must_use]
174    pub fn wire(&self) -> Map {
175        Map::new()
176            .put("a", self.asset)
177            .put("b", self.side.is_buy())
178            .put("p", self.price.to_wire())
179            .put("s", self.size.to_wire())
180            .put("r", self.reduce_only)
181            .put("t", self.order_type.wire())
182            .put_some("c", self.cloid.map(Cloid::to_hex))
183    }
184}
185
186/// `order`: one or more orders, grouped, optionally through a builder.
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub struct PlaceOrder {
189    orders: Vec<Order>,
190    grouping: Grouping,
191    builder: Option<Builder>,
192}
193
194impl PlaceOrder {
195    /// A scale is one action with an order a level.
196    #[must_use]
197    pub fn new(orders: Vec<Order>) -> PlaceOrder {
198        PlaceOrder { orders, grouping: Grouping::Na, builder: None }
199    }
200
201    /// One order, grouped `na`.
202    #[must_use]
203    pub fn one(order: Order) -> PlaceOrder {
204        PlaceOrder::new(vec![order])
205    }
206
207    /// With this grouping.
208    #[must_use]
209    pub fn grouped(mut self, grouping: Grouping) -> PlaceOrder {
210        self.grouping = grouping;
211        self
212    }
213
214    /// Routed through `builder`, which the action names last.
215    #[must_use]
216    pub fn through(mut self, builder: Builder) -> PlaceOrder {
217        self.builder = Some(builder);
218        self
219    }
220
221    /// The orders, in the order sent.
222    #[must_use]
223    pub fn orders(&self) -> &[Order] {
224        &self.orders
225    }
226
227    /// How the orders relate.
228    #[must_use]
229    pub const fn grouping(&self) -> Grouping {
230        self.grouping
231    }
232
233    /// The builder it is routed through; `None` for none.
234    #[must_use]
235    pub const fn builder(&self) -> Option<Builder> {
236        self.builder
237    }
238
239    /// The builder's fee, when it is more than the venue lets a builder take
240    /// on these orders. One perp order holds the whole action to the perp cap.
241    #[must_use]
242    pub fn over_builder_cap(&self) -> Option<OverCap> {
243        let fee = self.builder?.fee();
244        let kind = AssetKind::strictest(self.orders.iter().map(Order::asset))?;
245        let cap = kind.builder_cap();
246        (fee > cap).then_some(OverCap { fee, cap, kind })
247    }
248}
249
250impl L1Action for PlaceOrder {
251    fn action(&self) -> Map {
252        Map::new()
253            .put("type", "order")
254            .put("orders", Value::array(self.orders.iter().map(Order::wire)))
255            .put("grouping", self.grouping.wire())
256            .put_some("builder", self.builder.as_ref().map(Builder::wire))
257    }
258}
259
260#[cfg(test)]
261#[path = "tests/order/mod.rs"]
262mod tests;