df_hyperliquid_core/trade/
ticket.rs1use 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#[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 #[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 #[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 #[must_use]
51 pub const fn asset(&self) -> Asset {
52 self.asset
53 }
54
55 #[must_use]
57 pub const fn grid(&self) -> Grid {
58 self.grid
59 }
60
61 #[must_use]
63 pub const fn max_leverage(&self) -> Option<u32> {
64 self.max_leverage
65 }
66
67 #[must_use]
69 pub const fn allows_cross(&self) -> bool {
70 self.allows_cross
71 }
72
73 #[must_use]
76 pub const fn is_spot(&self) -> bool {
77 self.max_leverage.is_none()
78 }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum Amount {
86 Size(Dec),
88 Notional(Dec),
90}
91
92impl Amount {
93 pub(crate) fn size_on(self, grid: Grid, price: Dec) -> Result<Dec, Refusal> {
95 let raw = match self {
96 Amount::Size(size) => positive(size, "a size")?,
97 Amount::Notional(notional) => positive(notional, "a notional")?
98 .checked_div(price, 12, Round::Down)
99 .ok_or(Refusal::Trade(TradeError::NoPrice(price)))?,
100 };
101 grid.size(raw).ok_or(Refusal::Trade(TradeError::NoSize(raw)))
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
107#[non_exhaustive]
108pub enum Refusal {
109 #[error(transparent)]
111 Trade(#[from] TradeError),
112 #[error("{what} above zero is needed, not {value}")]
114 NotPositive {
115 what: &'static str,
117 value: Dec,
119 },
120 #[error("{size} at {price} is worth {}, under the venue's minimum of {minimum}", worth(.size, .price))]
122 UnderMinimum {
123 size: Dec,
125 price: Dec,
127 minimum: Dec,
129 },
130 #[error("a limit is never FrontendMarket: a market order is Price::Market, bounded from the mid")]
132 MarketTif,
133 #[error("a scale rests on the book, so Gtc or Alo, not {}", .0.wire())]
135 ScaleTif(Tif),
136 #[error("a scale has {LEAST_LEVELS} to {MOST_LEVELS} levels, not {0}")]
138 Levels(u32),
139 #[error("a modify that does not always place is Alo or Gtc, not {}", .0.wire())]
141 ModifyTif(Tif),
142 #[error("spot takes no {0}")]
145 Spot(&'static str),
146 #[error("a notional needs a reference price to be sized at")]
148 NoReference,
149 #[error("a {} at {trigger} is on the wrong side of an entry at {entry}", tpsl_words(.tpsl))]
151 ExitSide {
152 tpsl: Tpsl,
154 trigger: Dec,
156 entry: Dec,
158 },
159 #[error("there is no position here")]
161 NoPosition,
162 #[error("closing {size} is more than the position of {position}")]
164 CloseTooLarge {
165 size: Dec,
167 position: Dec,
169 },
170 #[error("leverage is a whole number from 1 to {most}, not {asked}")]
172 Leverage {
173 asked: u32,
175 most: u32,
177 },
178 #[error("this market is isolated only")]
180 IsolatedOnly,
181 #[error("this position is cross; margin moves on isolated ones")]
183 CrossPosition,
184 #[error("order {0} is a trigger: change its trigger instead")]
186 NotALimit(u64),
187 #[error("order {0} is not a take profit or stop loss")]
189 NotATrigger(u64),
190 #[error("order {oid} is a {kind} trigger, which this build cannot modify")]
192 UnknownTrigger {
193 oid: u64,
195 kind: String,
197 },
198 #[error("order {0} has a size of its own; only a position's take profit or stop loss covers the whole position")]
200 NotWholePosition(u64),
201}
202
203fn worth(size: &Dec, price: &Dec) -> String {
204 size.checked_mul(*price).map_or_else(|| "too much to count".to_owned(), Dec::to_wire)
205}
206
207const fn tpsl_words(tpsl: &Tpsl) -> &'static str {
208 match tpsl {
209 Tpsl::TakeProfit => "take profit",
210 Tpsl::StopLoss => "stop loss",
211 }
212}
213
214pub(crate) fn positive(value: Dec, what: &'static str) -> Result<Dec, Refusal> {
215 match value.is_positive() {
216 true => Ok(value),
217 false => Err(Refusal::NotPositive { what, value }),
218 }
219}
220
221pub(crate) fn at_least(size: Dec, price: Dec, minimum: Dec) -> Result<(), Refusal> {
222 match price.checked_mul(size).is_some_and(|worth| worth >= minimum) {
223 true => Ok(()),
224 false => Err(Refusal::UnderMinimum { size, price, minimum }),
225 }
226}
227
228pub(crate) fn routed(place: PlaceOrder, builder: Option<&BuilderSetting>) -> Result<PlaceOrder, Refusal> {
230 let Some(setting) = builder else { return Ok(place) };
231 match setting.on_assets(place.orders().iter().map(Order::asset)).map_err(TradeError::from)? {
232 Some(builder) => Ok(place.through(builder)),
233 None => Ok(place),
234 }
235}
236
237#[cfg(test)]
238#[path = "tests/ticket.rs"]
239mod tests;