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)]
84pub enum Amount {
85 Size(Dec),
87 Notional(Dec),
89}
90
91impl Amount {
92 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
106pub enum Refusal {
107 #[error(transparent)]
109 Trade(#[from] TradeError),
110 #[error("{what} above zero is needed, not {value}")]
112 NotPositive {
113 what: &'static str,
115 value: Dec,
117 },
118 #[error("{size} at {price} is worth {}, under the venue's minimum of {minimum}", worth(.size, .price))]
120 UnderMinimum {
121 size: Dec,
123 price: Dec,
125 minimum: Dec,
127 },
128 #[error("a limit is never FrontendMarket: a market order is Price::Market, bounded from the mid")]
130 MarketTif,
131 #[error("a scale rests on the book, so Gtc or Alo, not {}", .0.wire())]
133 ScaleTif(Tif),
134 #[error("a scale has {LEAST_LEVELS} to {MOST_LEVELS} levels, not {0}")]
136 Levels(u32),
137 #[error("a modify that does not always place is Alo or Gtc, not {}", .0.wire())]
139 ModifyTif(Tif),
140 #[error("spot takes no {0}")]
143 Spot(&'static str),
144 #[error("a notional needs a reference price to be sized at")]
146 NoReference,
147 #[error("a {} at {trigger} is on the wrong side of an entry at {entry}", tpsl_words(.tpsl))]
149 ExitSide {
150 tpsl: Tpsl,
152 trigger: Dec,
154 entry: Dec,
156 },
157 #[error("there is no position here")]
159 NoPosition,
160 #[error("closing {size} is more than the position of {position}")]
162 CloseTooLarge {
163 size: Dec,
165 position: Dec,
167 },
168 #[error("leverage is a whole number from 1 to {most}, not {asked}")]
170 Leverage {
171 asked: u32,
173 most: u32,
175 },
176 #[error("this market is isolated only")]
178 IsolatedOnly,
179 #[error("this position is cross; margin moves on isolated ones")]
181 CrossPosition,
182 #[error("order {0} is a trigger: change its trigger instead")]
184 NotALimit(u64),
185 #[error("order {0} is not a take profit or stop loss")]
187 NotATrigger(u64),
188 #[error("order {oid} is a {kind} trigger, which this build cannot modify")]
190 UnknownTrigger {
191 oid: u64,
193 kind: String,
195 },
196 #[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
226pub(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;