Skip to main content

df_hyperliquid_core/trade/manage/
modify.rs

1//! `modify` and `batchModify`: a resting order replaced in place.
2
3use crate::account::FrontendOrder;
4use crate::trade::orders::Tif;
5use crate::trade::orders::limit::limit_on;
6use crate::trade::orders::tpsl::Covers;
7use crate::trade::orders::trigger::{ExitPrice, fill_price, trigger_on};
8use crate::trade::orders::{Cloid, Order};
9use crate::trade::ticket::{Amount, Market, Refusal, at_least};
10use crate::utils::Dec;
11use crate::utils::rounding::MINIMUM_ORDER_VALUE;
12use crate::utils::sign::{L1Action, Map, Value};
13
14/// The order a modify replaces: the venue's id, or the client's.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum OrderRef {
17    /// The venue's order id.
18    Oid(u64),
19    /// The client order id.
20    Cloid(Cloid),
21}
22
23impl OrderRef {
24    /// An oid as a number, a cloid as its hex.
25    #[must_use]
26    pub fn wire(self) -> Value {
27        match self {
28            OrderRef::Oid(oid) => Value::Uint(oid),
29            OrderRef::Cloid(cloid) => Value::from(cloid.to_hex()),
30        }
31    }
32}
33
34/// `modify`: `{type, oid, order, a?}`, one order. `a` (always place) is written last and only
35/// when set, and set whenever the new order is a trigger: the venue refuses a trigger without it
36/// and an action hashed with `a: false`. A `batchModify` entry never carries it; the batch does.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct Modify {
39    target: OrderRef,
40    order: Order,
41    always_place: bool,
42}
43
44impl Modify {
45    /// Replaces `target` with `order`; always places when `order` is a trigger.
46    #[must_use]
47    pub const fn new(target: OrderRef, order: Order) -> Modify {
48        Modify { target, order, always_place: order.is_trigger() }
49    }
50
51    /// Places the new order even where the old one is gone.
52    #[must_use]
53    pub const fn always_place(mut self) -> Modify {
54        self.always_place = true;
55        self
56    }
57
58    /// Whether `a` is set: the new order goes on even where the old one is gone.
59    #[must_use]
60    pub const fn is_always_place(&self) -> bool {
61        self.always_place
62    }
63
64    /// The order it replaces.
65    #[must_use]
66    pub const fn target(&self) -> OrderRef {
67        self.target
68    }
69
70    /// The new order.
71    #[must_use]
72    pub const fn order(&self) -> &Order {
73        &self.order
74    }
75
76    /// `{oid, order}`, one entry of a `batchModify`.
77    #[must_use]
78    pub fn entry(&self) -> Map {
79        Map::new().put("oid", self.target.wire()).put("order", self.order.wire())
80    }
81}
82
83impl L1Action for Modify {
84    fn action(&self) -> Map {
85        Map::new()
86            .put("type", "modify")
87            .put("oid", self.target.wire())
88            .put("order", self.order.wire())
89            .put_some("a", self.always_place.then_some(true))
90    }
91}
92
93/// `batchModify`: `{type, modifies: [{oid, order}], a?}`. `a` (always place: the new order goes on
94/// whether or not the old one was still there) is written last and only when set, and set
95/// whenever a new order is a trigger, since the venue refuses a trigger without it.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct BatchModify {
98    modifies: Vec<Modify>,
99    always_place: bool,
100}
101
102impl BatchModify {
103    /// Each modify in one action; always places when any new order is a trigger.
104    #[must_use]
105    pub fn new(modifies: Vec<Modify>) -> BatchModify {
106        let always_place = modifies.iter().any(|modify| modify.order.is_trigger());
107        BatchModify { modifies, always_place }
108    }
109
110    /// Places the new orders even where the old ones are gone.
111    #[must_use]
112    pub fn always_place(mut self) -> BatchModify {
113        self.always_place = true;
114        self
115    }
116
117    /// The modifies, in the order sent.
118    #[must_use]
119    pub fn modifies(&self) -> &[Modify] {
120        &self.modifies
121    }
122
123    /// Whether `a` is set: the new orders go on even where the old ones are gone.
124    #[must_use]
125    pub const fn is_always_place(&self) -> bool {
126        self.always_place
127    }
128}
129
130impl L1Action for BatchModify {
131    fn action(&self) -> Map {
132        Map::new()
133            .put("type", "batchModify")
134            .put("modifies", Value::array(self.modifies.iter().map(Modify::entry)))
135            .put_some("a", self.always_place.then_some(true))
136    }
137}
138
139/// What a resting order becomes.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum Change {
142    /// A limit order's new price, size and time in force.
143    Limit {
144        /// The new limit price, brought onto the grid never against the trader.
145        price: Dec,
146        /// The new size, or a notional sized at the new price.
147        size: Amount,
148        /// The new time in force: `Alo` or `Gtc`.
149        tif: Tif,
150    },
151    /// A take profit's or stop loss's new trigger, price and size.
152    Trigger {
153        /// The new trigger price.
154        trigger: Dec,
155        /// How it fills once it fires.
156        price: ExitPrice,
157        /// A fixed size, or the whole position for an order that already covers it.
158        size: Covers,
159    },
160}
161
162/// A resting order replaced in place, as `frontendOpenOrders` lists it. Its
163/// side, reduce only and client order id stay; a take profit or stop loss
164/// always places, as the venue requires of a trigger.
165pub fn modify(market: &Market, order: &FrontendOrder, change: &Change) -> Result<BatchModify, Refusal> {
166    let grid = market.grid();
167    let side = order.side;
168    let new = match *change {
169        Change::Limit { .. } if order.is_trigger => return Err(Refusal::NotALimit(order.oid)),
170        Change::Limit { tif, .. } if !matches!(tif, Tif::Alo | Tif::Gtc) => return Err(Refusal::ModifyTif(tif)),
171        Change::Limit { price, size, tif } => {
172            let price = limit_on(grid, price, side, "a new price")?;
173            let size = size.size_on(grid, price)?;
174            at_least(size, price, MINIMUM_ORDER_VALUE)?;
175            Order::limit(market.asset(), side, price, size, tif)
176        }
177        Change::Trigger { .. } if !order.is_trigger => return Err(Refusal::NotATrigger(order.oid)),
178        Change::Trigger { trigger, price, size } => {
179            let Some(tpsl) = order.tpsl() else {
180                return Err(Refusal::UnknownTrigger { oid: order.oid, kind: order.order_type.word().to_lowercase() });
181            };
182            let trigger = trigger_on(grid, trigger)?;
183            let size = match size {
184                Covers::Position if order.sz.is_zero() => Dec::ZERO,
185                Covers::Position => return Err(Refusal::NotWholePosition(order.oid)),
186                Covers::Size(amount) => {
187                    let size = amount.size_on(grid, trigger)?;
188                    at_least(size, trigger, MINIMUM_ORDER_VALUE)?;
189                    size
190                }
191            };
192            let (price, is_market) = fill_price(grid, trigger, price, side)?;
193            Order::trigger(market.asset(), side, price, size, trigger, tpsl, is_market)
194        }
195    };
196    let new = match order.reduce_only {
197        true => new.reduce_only(),
198        false => new,
199    };
200    let new = match order.cloid {
201        Some(cloid) => new.with_cloid(cloid),
202        None => new,
203    };
204    Ok(BatchModify::new(vec![Modify::new(OrderRef::Oid(order.oid), new)]))
205}
206
207#[cfg(test)]
208#[path = "tests/modify.rs"]
209mod tests;