Skip to main content

df_hyperliquid_core/trade/
answer.rs

1//! What `/exchange` answers to a trading action, read per item. A count of statuses that does not
2//! match what was sent is unreadable, never a partial success, except an error decided by the
3//! payload alone, which comes back once and stands for every item.
4
5use crate::client::http::transport::EXCHANGE;
6use crate::client::{Accepted, ApiError, ExchangeResponse, Status, Transport, exchange};
7use crate::trade::orders::Cloid;
8use crate::utils::Dec;
9use serde::Deserialize;
10use serde_json::Value;
11
12/// What the venue said of one order.
13#[derive(Debug, Clone, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum OrderAnswer {
16    /// On the book.
17    Resting {
18        /// The venue's id for the order.
19        oid: u64,
20        /// The client order id, when the order was sent with one.
21        cloid: Option<Cloid>,
22    },
23    /// Filled `total_sz` at `avg_px` on average: all of it, or as much as
24    /// crossed for an IOC or a market order.
25    Filled {
26        /// The venue's id for the order.
27        oid: u64,
28        /// `totalSz`: the size filled, in the base asset.
29        total_sz: Dec,
30        /// `avgPx`: the average fill price.
31        avg_px: Dec,
32        /// The client order id, when the order was sent with one.
33        cloid: Option<Cloid>,
34    },
35    /// A take profit or stop loss, placed and waiting for its trigger.
36    WaitingForTrigger,
37    /// A take profit or stop loss grouped with an entry that has not filled.
38    WaitingForFill,
39    /// Refused, in the venue's words.
40    Refused(String),
41    /// A status this build does not know, kept as written. Never read as placed.
42    Unknown(String),
43}
44
45#[derive(Deserialize)]
46#[serde(rename_all = "camelCase")]
47struct Rested {
48    oid: u64,
49    #[serde(default)]
50    cloid: Option<Cloid>,
51}
52
53#[derive(Deserialize)]
54#[serde(rename_all = "camelCase")]
55struct Filled {
56    oid: u64,
57    total_sz: Dec,
58    avg_px: Dec,
59    #[serde(default)]
60    cloid: Option<Cloid>,
61}
62
63impl OrderAnswer {
64    /// One order's status. An object this build knows but cannot read (a
65    /// resting order with no `oid`) is an error, not a guess.
66    pub fn read(status: &Status) -> Result<OrderAnswer, String> {
67        let value = match status {
68            Status::Error(reason) => return Ok(OrderAnswer::Refused(reason.clone())),
69            Status::Ok(value) => value,
70        };
71        let shape = |error: serde_json::Error| format!("{error} in {value}");
72        match value {
73            Value::String(word) => Ok(match word.as_str() {
74                "waitingForTrigger" => OrderAnswer::WaitingForTrigger,
75                "waitingForFill" => OrderAnswer::WaitingForFill,
76                other => OrderAnswer::Unknown(other.to_owned()),
77            }),
78            Value::Object(entry) => {
79                if let Some(resting) = entry.get("resting") {
80                    let Rested { oid, cloid } = Rested::deserialize(resting).map_err(shape)?;
81                    return Ok(OrderAnswer::Resting { oid, cloid });
82                }
83                if let Some(filled) = entry.get("filled") {
84                    let Filled { oid, total_sz, avg_px, cloid } = Filled::deserialize(filled).map_err(shape)?;
85                    return Ok(OrderAnswer::Filled { oid, total_sz, avg_px, cloid });
86                }
87                Ok(OrderAnswer::Unknown(value.to_string()))
88            }
89            other => Err(format!("a status that is neither a word nor an object: {other}")),
90        }
91    }
92
93    /// The venue's id for the order, once it has one.
94    #[must_use]
95    pub const fn oid(&self) -> Option<u64> {
96        match self {
97            OrderAnswer::Resting { oid, .. } | OrderAnswer::Filled { oid, .. } => Some(*oid),
98            _ => None,
99        }
100    }
101
102    /// Taken by the venue: resting, filled, or waiting.
103    #[must_use]
104    pub const fn is_placed(&self) -> bool {
105        matches!(
106            self,
107            OrderAnswer::Resting { .. }
108                | OrderAnswer::Filled { .. }
109                | OrderAnswer::WaitingForTrigger
110                | OrderAnswer::WaitingForFill
111        )
112    }
113
114    /// The venue's words when it refused the order; `None` otherwise.
115    #[must_use]
116    pub fn refusal(&self) -> Option<&str> {
117        match self {
118            OrderAnswer::Refused(reason) => Some(reason),
119            _ => None,
120        }
121    }
122}
123
124/// What the venue said of one cancel, or of a TWAP's cancel.
125#[derive(Debug, Clone, PartialEq, Eq)]
126#[non_exhaustive]
127pub enum CancelAnswer {
128    /// `success`: the order or TWAP is cancelled.
129    Cancelled,
130    /// In the venue's words; any word but `success` is a refusal.
131    Refused(String),
132}
133
134impl CancelAnswer {
135    /// One cancel's status: `success` is cancelled, anything else a refusal.
136    #[must_use]
137    pub fn read(status: &Status) -> CancelAnswer {
138        match status {
139            Status::Error(reason) => CancelAnswer::Refused(reason.clone()),
140            Status::Ok(Value::String(word)) if word == "success" => CancelAnswer::Cancelled,
141            Status::Ok(Value::String(word)) => CancelAnswer::Refused(word.clone()),
142            Status::Ok(other) => CancelAnswer::Refused(other.to_string()),
143        }
144    }
145}
146
147/// What the venue said of a TWAP.
148#[derive(Debug, Clone, PartialEq, Eq)]
149#[non_exhaustive]
150pub enum TwapAnswer {
151    /// Running under this id, which `twapCancel` names.
152    Running {
153        /// `twapId`: the venue's id for the TWAP.
154        twap_id: u64,
155    },
156    /// Refused, in the venue's words.
157    Refused(String),
158}
159
160fn unreadable(detail: String) -> ApiError {
161    ApiError::Unreadable { path: EXCHANGE, detail }
162}
163
164/// One answer per item sent, the lone error of a whole batch repeated.
165fn per_item<T>(
166    accepted: &Accepted,
167    sent: usize,
168    read: impl Fn(&Status) -> Result<T, String>,
169) -> Result<Vec<T>, ApiError> {
170    let statuses = accepted.statuses.as_slice();
171    if let [lone @ Status::Error(_)] = statuses
172        && sent > 1
173    {
174        return (0..sent).map(|_| read(lone).map_err(unreadable)).collect();
175    }
176    if statuses.len() != sent {
177        return Err(unreadable(format!("{sent} were sent and {} statuses came back", statuses.len())));
178    }
179    statuses.iter().map(|status| read(status).map_err(unreadable)).collect()
180}
181
182/// The one status a TWAP or its cancel answers.
183fn lone(accepted: &Accepted) -> Result<&Status, ApiError> {
184    match accepted.statuses.as_slice() {
185        [status] => Ok(status),
186        many => Err(unreadable(format!("one status was expected and {} came back", many.len()))),
187    }
188}
189
190/// An `order` or `batchModify` answer, `sent` orders in it.
191pub fn orders(accepted: &Accepted, sent: usize) -> Result<Vec<OrderAnswer>, ApiError> {
192    per_item(accepted, sent, OrderAnswer::read)
193}
194
195/// A `cancel` or `cancelByCloid` answer, `sent` cancels in it.
196pub fn cancels(accepted: &Accepted, sent: usize) -> Result<Vec<CancelAnswer>, ApiError> {
197    per_item(accepted, sent, |status| Ok(CancelAnswer::read(status)))
198}
199
200/// A `twapOrder` answer.
201pub fn twap(accepted: &Accepted) -> Result<TwapAnswer, ApiError> {
202    match lone(accepted)? {
203        Status::Error(reason) => Ok(TwapAnswer::Refused(reason.clone())),
204        Status::Ok(value) => value
205            .get("running")
206            .and_then(|running| running.get("twapId"))
207            .and_then(Value::as_u64)
208            .map(|twap_id| TwapAnswer::Running { twap_id })
209            .ok_or_else(|| unreadable(format!("a TWAP status this build cannot read: {value}"))),
210    }
211}
212
213/// A `twapCancel` answer.
214pub fn twap_cancel(accepted: &Accepted) -> Result<CancelAnswer, ApiError> {
215    lone(accepted).map(CancelAnswer::read)
216}
217
218/// An answer that says only that it was taken: a single `modify`, leverage,
219/// margin, `scheduleCancel`, `noop`. A status that is an error refuses it.
220pub fn taken(accepted: &Accepted) -> Result<(), ApiError> {
221    match accepted.errors().next() {
222        Some(reason) => Err(ApiError::Refused(reason.to_owned())),
223        None => Ok(()),
224    }
225}
226
227/// The answer's text, read: `ok`, or the venue's refusal of the whole action.
228pub fn read(text: &str) -> Result<Accepted, ApiError> {
229    match ExchangeResponse::parse(text)? {
230        ExchangeResponse::Ok(accepted) => Ok(accepted),
231        ExchangeResponse::Err(reason) => Err(ApiError::Refused(reason)),
232    }
233}
234
235/// Posts a signed `order` or `batchModify` body once and reads its answer.
236pub async fn send_orders(transport: &impl Transport, body: String, sent: usize) -> Result<Vec<OrderAnswer>, ApiError> {
237    orders(&exchange(transport, body).await?, sent)
238}
239
240/// Posts a signed `cancel` or `cancelByCloid` body once and reads its answer.
241pub async fn send_cancels(
242    transport: &impl Transport,
243    body: String,
244    sent: usize,
245) -> Result<Vec<CancelAnswer>, ApiError> {
246    cancels(&exchange(transport, body).await?, sent)
247}
248
249/// Posts a signed `twapOrder` body once and reads its answer.
250pub async fn send_twap(transport: &impl Transport, body: String) -> Result<TwapAnswer, ApiError> {
251    twap(&exchange(transport, body).await?)
252}
253
254/// Posts a signed `twapCancel` body once and reads its answer.
255pub async fn send_twap_cancel(transport: &impl Transport, body: String) -> Result<CancelAnswer, ApiError> {
256    twap_cancel(&exchange(transport, body).await?)
257}
258
259/// Posts any other signed trading body once: taken, or refused.
260pub async fn send_taken(transport: &impl Transport, body: String) -> Result<(), ApiError> {
261    taken(&exchange(transport, body).await?)
262}
263
264#[cfg(test)]
265#[path = "tests/answer.rs"]
266mod tests;