df_hyperliquid_core/trade/orders/
entry.rs1use crate::trade::builder::BuilderSetting;
5use crate::trade::orders::trigger::Exit;
6use crate::trade::orders::{Cloid, Grouping, Order, PlaceOrder, Side, Tif, limit, market, tpsl};
7use crate::trade::ticket::{Amount, Market, Refusal, at_least, routed};
8use crate::utils::Dec;
9use crate::utils::rounding::MINIMUM_ORDER_VALUE;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum Price {
15 Market {
18 reference: Dec,
20 slippage: Dec,
22 },
23 Limit {
25 price: Dec,
27 tif: Tif,
29 },
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct OrderIntent {
36 pub side: Side,
38 pub amount: Amount,
40 pub price: Price,
42 pub reduce_only: bool,
44 pub cloid: Option<Cloid>,
46 pub take_profit: Option<Exit>,
48 pub stop_loss: Option<Exit>,
50}
51
52impl OrderIntent {
53 pub(super) const fn at(side: Side, amount: Amount, price: Price) -> OrderIntent {
54 OrderIntent { side, amount, price, reduce_only: false, cloid: None, take_profit: None, stop_loss: None }
55 }
56
57 #[must_use]
59 pub const fn with_cloid(mut self, cloid: Cloid) -> OrderIntent {
60 self.cloid = Some(cloid);
61 self
62 }
63
64 #[must_use]
66 pub const fn take_profit(mut self, exit: Exit) -> OrderIntent {
67 self.take_profit = Some(exit);
68 self
69 }
70
71 #[must_use]
73 pub const fn stop_loss(mut self, exit: Exit) -> OrderIntent {
74 self.stop_loss = Some(exit);
75 self
76 }
77}
78
79pub fn order(market: &Market, intent: &OrderIntent, builder: Option<&BuilderSetting>) -> Result<PlaceOrder, Refusal> {
83 let has_exits = intent.take_profit.is_some() || intent.stop_loss.is_some();
84 if market.is_spot() && intent.reduce_only {
85 return Err(Refusal::Spot("reduce only"));
86 }
87 if market.is_spot() && has_exits {
88 return Err(Refusal::Spot("a take profit or stop loss"));
89 }
90 let grid = market.grid();
91 let side = intent.side;
92 let (price, valued_at, tif) = match intent.price {
93 Price::Market { reference, slippage } => market::bound(grid, reference, slippage, side)?,
94 Price::Limit { price, tif } => limit::resting(grid, price, tif, side)?,
95 };
96 let size = intent.amount.size_on(grid, valued_at)?;
97 at_least(size, valued_at, MINIMUM_ORDER_VALUE)?;
98 let mut entry = match tif {
99 Tif::FrontendMarket => Order::market(market.asset(), side, price, size),
100 tif => Order::limit(market.asset(), side, price, size, tif),
101 };
102 if intent.reduce_only {
103 entry = entry.reduce_only();
104 }
105 if let Some(cloid) = intent.cloid {
106 entry = entry.with_cloid(cloid);
107 }
108 let mut orders = vec![entry];
109 orders.extend(tpsl::attach(market, side, size, valued_at, intent.take_profit, intent.stop_loss)?);
110 let grouping = match has_exits {
111 true => Grouping::NormalTpsl,
112 false => Grouping::Na,
113 };
114 routed(PlaceOrder::new(orders).grouped(grouping), builder)
115}
116
117#[cfg(test)]
118#[path = "tests/entry.rs"]
119mod tests;