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