Skip to main content

df_hyperliquid_core/trade/orders/
close.rs

1//! Closing a position at market: reduce only, the other way, `FrontendMarket`.
2
3use crate::trade::builder::BuilderSetting;
4use crate::trade::error::TradeError;
5use crate::trade::orders::{Cloid, Order, PlaceOrder, Side};
6use crate::trade::ticket::{Market, Refusal, at_least, positive, routed};
7use crate::utils::Dec;
8use crate::utils::rounding::MINIMUM_ORDER_VALUE;
9
10/// A position closed at market: all of it, or `size` of it.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct Close {
13    /// The position, signed as `clearinghouseState` writes `szi`: below
14    /// zero is short.
15    pub position: Dec,
16    /// How much to close, in the base asset; `None` closes the whole position.
17    pub size: Option<Dec>,
18    /// The price the bound is measured from: the mid, or else the mark.
19    pub reference: Dec,
20    /// How far past `reference` the close may fill, a fraction: 0.01 is 1%.
21    pub slippage: Dec,
22    /// The client order id; `None` for none.
23    pub cloid: Option<Cloid>,
24}
25
26impl Close {
27    /// The whole `position`, bounded `slippage` past `reference`.
28    #[must_use]
29    pub const fn new(position: Dec, reference: Dec, slippage: Dec) -> Close {
30        Close { position, size: None, reference, slippage, cloid: None }
31    }
32
33    /// Sent with this client order id.
34    #[must_use]
35    pub const fn with_cloid(mut self, cloid: Cloid) -> Close {
36        self.cloid = Some(cloid);
37        self
38    }
39}
40
41/// A position closed at market: reduce only, the other way, `FrontendMarket`.
42/// A whole position closes whatever it is worth; part of one is held to the
43/// minimum as any order is.
44pub fn close(market: &Market, intent: &Close, builder: Option<&BuilderSetting>) -> Result<PlaceOrder, Refusal> {
45    if market.is_spot() {
46        return Err(Refusal::Spot("a position"));
47    }
48    if intent.position.is_zero() {
49        return Err(Refusal::NoPosition);
50    }
51    let side = match intent.position.is_positive() {
52        true => Side::Sell,
53        false => Side::Buy,
54    };
55    let held = intent.position.abs();
56    let wanted = match intent.size {
57        None => held,
58        Some(size) if positive(size, "a size")? > held => {
59            return Err(Refusal::CloseTooLarge { size, position: held });
60        }
61        Some(size) => size,
62    };
63    let size = market.grid().size(wanted).ok_or(Refusal::Trade(TradeError::NoSize(wanted)))?;
64    let reference = positive(intent.reference, "a reference price")?;
65    let bound = market.grid().market_bound(reference, intent.slippage, side)?;
66    if size != held {
67        at_least(size, reference, MINIMUM_ORDER_VALUE)?;
68    }
69    let order = Order::market(market.asset(), side, bound, size).reduce_only();
70    let order = match intent.cloid {
71        Some(cloid) => order.with_cloid(cloid),
72        None => order,
73    };
74    routed(PlaceOrder::one(order), builder)
75}
76
77#[cfg(test)]
78#[path = "tests/close.rs"]
79mod tests;