Skip to main content

df_hyperliquid_core/markets/
mids.rs

1//! `allMids`: every coin's mid on one perp dex, the same map from `/info` and from the socket.
2
3use std::fmt;
4
5use serde::{Deserialize, Deserializer, de};
6
7use crate::client::{ApiError, Transport, info, info_request};
8use crate::markets::dex::Dex;
9use crate::utils::dec::Dec;
10
11/// `{"type":"allMids","dex"?}`: the main dex, spot and outcomes with it, unless a HIP-3 dex is
12/// named.
13#[must_use]
14pub fn all_mids_request(dex: Dex<'_>) -> String {
15    info_request("allMids", dex.field().as_slice())
16}
17
18/// Every coin's mid on `dex`.
19pub async fn all_mids(transport: &impl Transport, dex: Dex<'_>) -> Result<Mids, ApiError> {
20    info(transport, all_mids_request(dex)).await
21}
22
23/// Every coin's mid on one dex, in the venue's order. The main dex's also carries spot pairs
24/// (`@107`, `PURR/USDC`) and outcome sides (`#14730`). Where a book is empty the venue prints its
25/// last trade instead, and a mid can sit between two ticks.
26#[derive(Debug, Clone, PartialEq, Eq, Default)]
27pub struct Mids(Vec<(String, Dec)>);
28
29impl Mids {
30    /// A coin's mid, the coin spelled as the venue spells it (`BTC`, `@107`, `#14730`).
31    #[must_use]
32    pub fn get(&self, coin: &str) -> Option<Dec> {
33        self.0.iter().find(|(name, _)| name == coin).map(|(_, mid)| *mid)
34    }
35
36    /// How many coins have a mid.
37    #[must_use]
38    pub fn len(&self) -> usize {
39        self.0.len()
40    }
41
42    /// Whether no coin has a mid.
43    #[must_use]
44    pub fn is_empty(&self) -> bool {
45        self.0.is_empty()
46    }
47
48    /// In the order written.
49    pub fn iter(&self) -> impl Iterator<Item = (&str, Dec)> {
50        self.0.iter().map(|(coin, mid)| (coin.as_str(), *mid))
51    }
52}
53
54impl FromIterator<(String, Dec)> for Mids {
55    fn from_iter<I: IntoIterator<Item = (String, Dec)>>(pairs: I) -> Self {
56        Mids(pairs.into_iter().collect())
57    }
58}
59
60/// Reads the JSON map into pairs to keep the order written, which a map type would lose.
61impl<'de> Deserialize<'de> for Mids {
62    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
63        struct Pairs;
64
65        impl<'de> de::Visitor<'de> for Pairs {
66            type Value = Mids;
67
68            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69                f.write_str("a map of coin to price")
70            }
71
72            fn visit_map<A: de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
73                let mut out = Vec::with_capacity(map.size_hint().unwrap_or(0));
74                while let Some(pair) = map.next_entry::<String, Dec>()? {
75                    out.push(pair);
76                }
77                Ok(Mids(out))
78            }
79        }
80
81        deserializer.deserialize_map(Pairs)
82    }
83}
84
85#[cfg(test)]
86#[path = "tests/mids.rs"]
87mod tests;