Skip to main content

df_hyperliquid_core/trade/orders/
tpsl.rs

1//! Take profit and stop loss: on their own for a fixed size (`na`) or the whole position
2//! (`positionTpsl`), or attached to an entry (`normalTpsl`).
3
4use crate::trade::builder::BuilderSetting;
5use crate::trade::orders::trigger::{Exit, exit_order, trigger_on};
6use crate::trade::orders::{Cloid, Grouping, Order, PlaceOrder, Side, Tpsl};
7use crate::trade::ticket::{Amount, Market, Refusal, at_least, routed};
8use crate::utils::Dec;
9use crate::utils::rounding::MINIMUM_ORDER_VALUE;
10
11/// How much of a position a take profit or stop loss closes.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum Covers {
15    /// A fixed size.
16    Size(Amount),
17    /// The whole position, whatever it is when the trigger fires: size 0,
18    /// grouped `positionTpsl`.
19    Position,
20}
21
22/// A take profit or stop loss on its own. `side` is the side that closes:
23/// a sell for a long.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct TriggerIntent {
26    /// The side that closes: a sell for a long.
27    pub side: Side,
28    /// How much of the position it closes.
29    pub size: Covers,
30    /// Take profit or stop loss.
31    pub tpsl: Tpsl,
32    /// Where it fires and how it fills.
33    pub exit: Exit,
34    /// The client order id; `None` for none.
35    pub cloid: Option<Cloid>,
36}
37
38impl TriggerIntent {
39    /// Without a client order id.
40    #[must_use]
41    pub const fn new(side: Side, size: Covers, tpsl: Tpsl, exit: Exit) -> TriggerIntent {
42        TriggerIntent { side, size, tpsl, exit, cloid: None }
43    }
44
45    /// Sent with this client order id.
46    #[must_use]
47    pub const fn with_cloid(mut self, cloid: Cloid) -> TriggerIntent {
48        self.cloid = Some(cloid);
49        self
50    }
51}
52
53/// Whether `exit` fires on the side of `entry` it should: above it for a
54/// long's take profit and a short's stop, below it otherwise.
55fn on_its_side(side: Side, tpsl: Tpsl, trigger: Dec, entry: Dec) -> bool {
56    match (side, tpsl) {
57        (Side::Buy, Tpsl::TakeProfit) | (Side::Sell, Tpsl::StopLoss) => trigger > entry,
58        (Side::Buy, Tpsl::StopLoss) | (Side::Sell, Tpsl::TakeProfit) => trigger < entry,
59    }
60}
61
62/// An entry's take profit and stop loss: each on its side of the entry, worth the minimum at its
63/// trigger, reduce only and the other way.
64pub(crate) fn attach(
65    market: &Market,
66    side: Side,
67    size: Dec,
68    entry: Dec,
69    take_profit: Option<Exit>,
70    stop_loss: Option<Exit>,
71) -> Result<Vec<Order>, Refusal> {
72    let mut exits = Vec::new();
73    for (tpsl, exit) in [(Tpsl::TakeProfit, take_profit), (Tpsl::StopLoss, stop_loss)] {
74        let Some(exit) = exit else { continue };
75        if !on_its_side(side, tpsl, exit.trigger, entry) {
76            return Err(Refusal::ExitSide { tpsl, trigger: exit.trigger, entry });
77        }
78        at_least(size, trigger_on(market.grid(), exit.trigger)?, MINIMUM_ORDER_VALUE)?;
79        exits.push(exit_order(market, side.other(), size, tpsl, exit)?);
80    }
81    Ok(exits)
82}
83
84/// A take profit or stop loss on its own: reduce only, a fixed size grouped
85/// `na`, or the whole position at size 0 grouped `positionTpsl`.
86pub fn trigger(
87    market: &Market,
88    intent: &TriggerIntent,
89    builder: Option<&BuilderSetting>,
90) -> Result<PlaceOrder, Refusal> {
91    if market.is_spot() {
92        return Err(Refusal::Spot("a take profit or stop loss"));
93    }
94    let (size, grouping) = match intent.size {
95        Covers::Position => (Dec::ZERO, Grouping::PositionTpsl),
96        Covers::Size(amount) => {
97            let trigger = trigger_on(market.grid(), intent.exit.trigger)?;
98            let size = amount.size_on(market.grid(), trigger)?;
99            at_least(size, trigger, MINIMUM_ORDER_VALUE)?;
100            (size, Grouping::Na)
101        }
102    };
103    let mut order = exit_order(market, intent.side, size, intent.tpsl, intent.exit)?;
104    if let Some(cloid) = intent.cloid {
105        order = order.with_cloid(cloid);
106    }
107    routed(PlaceOrder::one(order).grouped(grouping), builder)
108}
109
110#[cfg(test)]
111#[path = "tests/tpsl.rs"]
112mod tests;