Skip to main content

df_hyperliquid_core/trade/orders/
trailing.rs

1//! `trailingStop`: `{type, asset, isBuy, sz, reduceOnly, retracement, activationPx}`, keys in the
2//! order the exchange endpoint docs write them. The stop follows the best price the market reaches
3//! and fires when the price falls back from it by the retracement, a percent or a fixed amount.
4//! With an activation price it starts to follow only once the market reaches that price.
5//! `activationPx` is `null` when there is none. The venue answers with the order's id.
6
7use crate::account::{ActionKind, Signers};
8use crate::trade::orders::Side;
9use crate::utils::sign::{L1Action, Map, Value};
10use crate::utils::{Asset, Dec};
11
12/// How far the price may fall back from its best before the stop fires.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum Retracement {
16    /// A percent of the best price: `1.5` is 1.5%, posted as `{"pct":"1.5%"}`.
17    Percent(Dec),
18    /// A fixed amount in the quote, posted as `{"px":"2.5"}`.
19    Price(Dec),
20}
21
22impl Retracement {
23    /// `{"pct":"1.5%"}` or `{"px":"2.5"}`.
24    #[must_use]
25    pub fn wire(self) -> Map {
26        match self {
27            Retracement::Percent(percent) => Map::new().put("pct", format!("{}%", percent.to_wire())),
28            Retracement::Price(px) => Map::new().put("px", px.to_wire()),
29        }
30    }
31
32    const fn figure(self) -> Dec {
33        match self {
34            Retracement::Percent(figure) | Retracement::Price(figure) => figure,
35        }
36    }
37}
38
39/// Why a trailing stop is not one the venue would take.
40#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
41#[non_exhaustive]
42pub enum BadTrailingStop {
43    /// The size is not positive; the size given.
44    #[error("a trailing stop's size is positive, not {0}")]
45    Size(Dec),
46    /// The retracement is not positive, or a percent is 100 or more; the figure given.
47    #[error("a retracement is positive, and a percent is under 100: {0}")]
48    Retracement(Dec),
49    /// The activation price is not positive; the price given.
50    #[error("an activation price is positive, not {0}")]
51    Activation(Dec),
52}
53
54/// A stop that trails the best price by its [`Retracement`]. Size and prices go on the wire
55/// exactly as given, so put them on the asset's grid first ([`crate::utils::Grid`]).
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct TrailingStop {
58    asset: Asset,
59    side: Side,
60    size: Dec,
61    reduce_only: bool,
62    retracement: Retracement,
63    activation: Option<Dec>,
64}
65
66impl TrailingStop {
67    /// L1: an agent may sign it for its master.
68    pub const KEY: Signers = ActionKind::TrailingStop.signers();
69
70    /// `size` of `asset`, trading `side` when the price falls back from its best by `retracement`.
71    pub fn new(asset: Asset, side: Side, size: Dec, retracement: Retracement) -> Result<TrailingStop, BadTrailingStop> {
72        if !size.is_positive() {
73            return Err(BadTrailingStop::Size(size));
74        }
75        let figure = retracement.figure();
76        let too_far = matches!(retracement, Retracement::Percent(_)) && figure >= Dec::from_int(100);
77        if !figure.is_positive() || too_far {
78            return Err(BadTrailingStop::Retracement(figure));
79        }
80        Ok(TrailingStop { asset, side, size, reduce_only: false, retracement, activation: None })
81    }
82
83    /// Starts to trail only once the market reaches `px`.
84    pub fn activated_at(mut self, px: Dec) -> Result<TrailingStop, BadTrailingStop> {
85        if !px.is_positive() {
86            return Err(BadTrailingStop::Activation(px));
87        }
88        self.activation = Some(px);
89        Ok(self)
90    }
91
92    /// Only ever shrinks the position.
93    #[must_use]
94    pub const fn reduce_only(mut self) -> TrailingStop {
95        self.reduce_only = true;
96        self
97    }
98
99    /// The asset it trades.
100    #[must_use]
101    pub const fn asset(&self) -> Asset {
102        self.asset
103    }
104
105    /// Which way it trades when it fires.
106    #[must_use]
107    pub const fn side(&self) -> Side {
108        self.side
109    }
110
111    /// How much it trades when it fires.
112    #[must_use]
113    pub const fn size(&self) -> Dec {
114        self.size
115    }
116
117    /// Whether it only ever shrinks the position.
118    #[must_use]
119    pub const fn is_reduce_only(&self) -> bool {
120        self.reduce_only
121    }
122
123    /// How far the price may fall back from its best before it fires.
124    #[must_use]
125    pub const fn retracement(&self) -> Retracement {
126        self.retracement
127    }
128
129    /// The price the market must reach before it starts to trail; `None` to trail at once.
130    #[must_use]
131    pub const fn activation(&self) -> Option<Dec> {
132        self.activation
133    }
134}
135
136impl L1Action for TrailingStop {
137    fn action(&self) -> Map {
138        let activation = match self.activation {
139            Some(px) => Value::from(px.to_wire()),
140            None => Value::Nil,
141        };
142        Map::new()
143            .put("type", "trailingStop")
144            .put("asset", self.asset)
145            .put("isBuy", self.side.is_buy())
146            .put("sz", self.size.to_wire())
147            .put("reduceOnly", self.reduce_only)
148            .put("retracement", self.retracement.wire())
149            .put("activationPx", activation)
150    }
151}
152
153#[cfg(test)]
154#[path = "tests/trailing.rs"]
155mod tests;