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