df_hyperliquid_core/trade/
answer.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum OrderAnswer {
15 Resting {
17 oid: u64,
19 cloid: Option<Cloid>,
21 },
22 Filled {
25 oid: u64,
27 total_sz: Dec,
29 avg_px: Dec,
31 cloid: Option<Cloid>,
33 },
34 WaitingForTrigger,
36 WaitingForFill,
38 Refused(String),
40 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 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 #[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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
125pub enum CancelAnswer {
126 Cancelled,
128 Refused(String),
130}
131
132impl CancelAnswer {
133 #[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#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum TwapAnswer {
148 Running {
150 twap_id: u64,
152 },
153 Refused(String),
155}
156
157fn unreadable(detail: String) -> ApiError {
158 ApiError::Unreadable { path: EXCHANGE, detail }
159}
160
161fn 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
179fn 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
187pub fn orders(accepted: &Accepted, sent: usize) -> Result<Vec<OrderAnswer>, ApiError> {
189 per_item(accepted, sent, OrderAnswer::read)
190}
191
192pub fn cancels(accepted: &Accepted, sent: usize) -> Result<Vec<CancelAnswer>, ApiError> {
194 per_item(accepted, sent, |status| Ok(CancelAnswer::read(status)))
195}
196
197pub 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
210pub fn twap_cancel(accepted: &Accepted) -> Result<CancelAnswer, ApiError> {
212 lone(accepted).map(CancelAnswer::read)
213}
214
215pub 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
224pub 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
232pub async fn send_orders(transport: &impl Transport, body: String, sent: usize) -> Result<Vec<OrderAnswer>, ApiError> {
234 orders(&exchange(transport, body).await?, sent)
235}
236
237pub 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
246pub async fn send_twap(transport: &impl Transport, body: String) -> Result<TwapAnswer, ApiError> {
248 twap(&exchange(transport, body).await?)
249}
250
251pub async fn send_twap_cancel(transport: &impl Transport, body: String) -> Result<CancelAnswer, ApiError> {
253 twap_cancel(&exchange(transport, body).await?)
254}
255
256pub 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;