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