Skip to main content

df_hyperliquid_core/markets/
trades.rs

1//! A print: one trade on a market's tape, the same shape from the `recentTrades` read and from the
2//! `trades` feed.
3
4use serde::Deserialize;
5
6use crate::client::{ApiError, Transport, info, info_request};
7use crate::markets::side::Side;
8use crate::utils::Json;
9use crate::utils::address::Address;
10use crate::utils::dec::Dec;
11
12/// `{"type":"recentTrades","coin":..}`.
13#[must_use]
14pub fn recent_trades_request(coin: &str) -> String {
15    info_request("recentTrades", &[("coin", Json::String(coin.to_owned()))])
16}
17
18pub async fn recent_trades(transport: &impl Transport, coin: &str) -> Result<Vec<Trade>, ApiError> {
19    info(transport, recent_trades_request(coin)).await
20}
21
22/// One trade on a market's tape.
23#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
24#[serde(from = "Raw")]
25pub struct Trade {
26    pub coin: String,
27    /// The aggressor's side.
28    pub side: Side,
29    pub px: Dec,
30    pub sz: Dec,
31    /// Milliseconds.
32    pub time: u64,
33    /// The L1 transaction hash; all zeros for a TWAP slice.
34    pub hash: String,
35    /// A hash of the two order ids; unique only together with `time` and `coin`.
36    pub tid: u64,
37    pub buyer: Address,
38    pub seller: Address,
39}
40
41impl Trade {
42    /// `users` as the venue writes them: the buyer, then the seller.
43    #[must_use]
44    pub const fn users(&self) -> [Address; 2] {
45        [self.buyer, self.seller]
46    }
47}
48
49#[derive(Deserialize)]
50struct Raw {
51    coin: String,
52    side: Side,
53    px: Dec,
54    sz: Dec,
55    time: u64,
56    hash: String,
57    tid: u64,
58    users: [Address; 2],
59}
60
61impl From<Raw> for Trade {
62    fn from(raw: Raw) -> Self {
63        let [buyer, seller] = raw.users;
64        Trade {
65            coin: raw.coin,
66            side: raw.side,
67            px: raw.px,
68            sz: raw.sz,
69            time: raw.time,
70            hash: raw.hash,
71            tid: raw.tid,
72            buyer,
73            seller,
74        }
75    }
76}
77
78#[cfg(test)]
79#[path = "tests/trades.rs"]
80mod tests;