Skip to main content

df_hyperliquid_core/trade/
ticket.rs

1//! What every order ticket shares: the market's rules ([`Market`]), how much ([`Amount`]), why
2//! nothing is sent ([`Refusal`]), and the checks each order type runs. A price never rounds
3//! against the trader and a size rounds toward zero.
4
5use crate::trade::builder::BuilderSetting;
6use crate::trade::error::TradeError;
7use crate::trade::orders::scale::{LEAST_LEVELS, MOST_LEVELS};
8use crate::trade::orders::{Order, PlaceOrder, Tif, Tpsl};
9use crate::utils::rounding::Grid;
10use crate::utils::{Asset, AssetKind, Dec, Round};
11
12/// What the ticket knows of one market, from the meta the caller read: its asset id, its grid,
13/// and for a perp its leverage ceiling and whether it takes cross margin. HIP-4 outcomes have
14/// orders of their own in [`crate::markets::outcomes`].
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct Market {
17    asset: Asset,
18    grid: Grid,
19    max_leverage: Option<u32>,
20    allows_cross: bool,
21}
22
23impl Market {
24    /// A perp, main dex or HIP-3: its `szDecimals` and `maxLeverage` in
25    /// `meta`, and whether it takes cross (not `onlyIsolated`, and no
26    /// `marginMode` that forbids it). `None` for an id that names no perp.
27    #[must_use]
28    pub const fn perp(asset: Asset, sz_decimals: u32, max_leverage: u32, allows_cross: bool) -> Option<Market> {
29        match asset.kind() {
30            AssetKind::Perp | AssetKind::Hip3Perp => {
31                Some(Market { asset, grid: Grid::perp(sz_decimals), max_leverage: Some(max_leverage), allows_cross })
32            }
33            AssetKind::Spot | AssetKind::Outcome => None,
34        }
35    }
36
37    /// A spot pair, by its base token's `szDecimals` in `spotMeta`. `None`
38    /// for an id that names no pair.
39    #[must_use]
40    pub const fn spot(asset: Asset, sz_decimals: u32) -> Option<Market> {
41        match asset.kind() {
42            AssetKind::Spot => {
43                Some(Market { asset, grid: Grid::spot(sz_decimals), max_leverage: None, allows_cross: false })
44            }
45            AssetKind::Perp | AssetKind::Hip3Perp | AssetKind::Outcome => None,
46        }
47    }
48
49    /// The asset id orders name.
50    #[must_use]
51    pub const fn asset(&self) -> Asset {
52        self.asset
53    }
54
55    /// The price and size grid orders are put on.
56    #[must_use]
57    pub const fn grid(&self) -> Grid {
58        self.grid
59    }
60
61    /// `None` on spot, which takes no leverage.
62    #[must_use]
63    pub const fn max_leverage(&self) -> Option<u32> {
64        self.max_leverage
65    }
66
67    /// Whether the perp takes cross margin; false on spot.
68    #[must_use]
69    pub const fn allows_cross(&self) -> bool {
70        self.allows_cross
71    }
72
73    /// Spot has balances, not positions: nothing that closes, protects or
74    /// funds one.
75    #[must_use]
76    pub const fn is_spot(&self) -> bool {
77        self.max_leverage.is_none()
78    }
79}
80
81/// How much: a size in the base, or a notional in the quote that is cut to
82/// a size at the order's price.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum Amount {
85    /// A size in the base asset.
86    Size(Dec),
87    /// A notional in the quote asset, cut to a size at the order's price.
88    Notional(Dec),
89}
90
91impl Amount {
92    /// The size on `grid` at `price`, cut toward zero.
93    pub(crate) fn size_on(self, grid: Grid, price: Dec) -> Result<Dec, Refusal> {
94        let raw = match self {
95            Amount::Size(size) => positive(size, "a size")?,
96            Amount::Notional(notional) => positive(notional, "a notional")?
97                .checked_div(price, 12, Round::Down)
98                .ok_or(Refusal::Trade(TradeError::NoPrice(price)))?,
99        };
100        grid.size(raw).ok_or(Refusal::Trade(TradeError::NoSize(raw)))
101    }
102}
103
104/// Why the ticket sends nothing.
105#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
106pub enum Refusal {
107    /// A check on the action itself failed.
108    #[error(transparent)]
109    Trade(#[from] TradeError),
110    /// A value that has to be above zero is not.
111    #[error("{what} above zero is needed, not {value}")]
112    NotPositive {
113        /// What the value is, in words: `a size`, `a price` and so on.
114        what: &'static str,
115        /// The value given.
116        value: Dec,
117    },
118    /// The order is worth less than the venue's minimum.
119    #[error("{size} at {price} is worth {}, under the venue's minimum of {minimum}", worth(.size, .price))]
120    UnderMinimum {
121        /// The order's size, in the base asset.
122        size: Dec,
123        /// The price it is valued at.
124        price: Dec,
125        /// The venue's minimum order value, in the quote asset.
126        minimum: Dec,
127    },
128    /// A limit order was given `FrontendMarket`; a market order is [`crate::trade::Price::Market`].
129    #[error("a limit is never FrontendMarket: a market order is Price::Market, bounded from the mid")]
130    MarketTif,
131    /// A scale was given a time in force other than `Gtc` or `Alo`; the one given.
132    #[error("a scale rests on the book, so Gtc or Alo, not {}", .0.wire())]
133    ScaleTif(Tif),
134    /// A scale's levels are outside [`LEAST_LEVELS`] to [`MOST_LEVELS`]; the levels given.
135    #[error("a scale has {LEAST_LEVELS} to {MOST_LEVELS} levels, not {0}")]
136    Levels(u32),
137    /// A limit modify that does not always place was given a time in force other than `Alo` or `Gtc`; the one given.
138    #[error("a modify that does not always place is Alo or Gtc, not {}", .0.wire())]
139    ModifyTif(Tif),
140    /// Spot has no positions, so this does not apply to it: reduce only, a take profit or stop
141    /// loss, a position, margin or leverage. The thing named, in words.
142    #[error("spot takes no {0}")]
143    Spot(&'static str),
144    /// A TWAP given as a notional has no reference price to size it at.
145    #[error("a notional needs a reference price to be sized at")]
146    NoReference,
147    /// A take profit or stop loss would fire on the wrong side of its entry.
148    #[error("a {} at {trigger} is on the wrong side of an entry at {entry}", tpsl_words(.tpsl))]
149    ExitSide {
150        /// Take profit or stop loss.
151        tpsl: Tpsl,
152        /// Its trigger price.
153        trigger: Dec,
154        /// The entry's price.
155        entry: Dec,
156    },
157    /// There is no position to close or to move margin on.
158    #[error("there is no position here")]
159    NoPosition,
160    /// The close is larger than the position.
161    #[error("closing {size} is more than the position of {position}")]
162    CloseTooLarge {
163        /// The size asked to close.
164        size: Dec,
165        /// The position's size.
166        position: Dec,
167    },
168    /// The leverage is 0 or over what the perp allows.
169    #[error("leverage is a whole number from 1 to {most}, not {asked}")]
170    Leverage {
171        /// The leverage asked for.
172        asked: u32,
173        /// The most the perp allows.
174        most: u32,
175    },
176    /// The perp is isolated only, and cross was asked for.
177    #[error("this market is isolated only")]
178    IsolatedOnly,
179    /// Margin was to move on a cross position; it moves only on isolated ones.
180    #[error("this position is cross; margin moves on isolated ones")]
181    CrossPosition,
182    /// A limit change was asked for on a trigger order; the order's oid.
183    #[error("order {0} is a trigger: change its trigger instead")]
184    NotALimit(u64),
185    /// A trigger change was asked for on an order that is not a take profit or stop loss; the order's oid.
186    #[error("order {0} is not a take profit or stop loss")]
187    NotATrigger(u64),
188    /// The order is a trigger of a kind this build cannot modify.
189    #[error("order {oid} is a {kind} trigger, which this build cannot modify")]
190    UnknownTrigger {
191        /// The order's oid.
192        oid: u64,
193        /// Its order type as `frontendOpenOrders` lists it, in lowercase.
194        kind: String,
195    },
196    /// A whole-position take profit or stop loss was asked for on an order with a size of its own; the order's oid.
197    #[error("order {0} has a size of its own; only a position's take profit or stop loss covers the whole position")]
198    NotWholePosition(u64),
199}
200
201fn worth(size: &Dec, price: &Dec) -> String {
202    size.checked_mul(*price).map_or_else(|| "too much to count".to_owned(), Dec::to_wire)
203}
204
205const fn tpsl_words(tpsl: &Tpsl) -> &'static str {
206    match tpsl {
207        Tpsl::TakeProfit => "take profit",
208        Tpsl::StopLoss => "stop loss",
209    }
210}
211
212pub(crate) fn positive(value: Dec, what: &'static str) -> Result<Dec, Refusal> {
213    match value.is_positive() {
214        true => Ok(value),
215        false => Err(Refusal::NotPositive { what, value }),
216    }
217}
218
219pub(crate) fn at_least(size: Dec, price: Dec, minimum: Dec) -> Result<(), Refusal> {
220    match price.checked_mul(size).is_some_and(|worth| worth >= minimum) {
221        true => Ok(()),
222        false => Err(Refusal::UnderMinimum { size, price, minimum }),
223    }
224}
225
226/// `orders` through the builder, held to their strictest cap.
227pub(crate) fn routed(place: PlaceOrder, builder: Option<&BuilderSetting>) -> Result<PlaceOrder, Refusal> {
228    let Some(setting) = builder else { return Ok(place) };
229    match setting.on_assets(place.orders().iter().map(Order::asset)).map_err(TradeError::from)? {
230        Some(builder) => Ok(place.through(builder)),
231        None => Ok(place),
232    }
233}
234
235#[cfg(test)]
236#[path = "tests/ticket.rs"]
237mod tests;