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
18/// The coin's most recent trades.
19pub async fn recent_trades(transport: &impl Transport, coin: &str) -> Result<Vec<Trade>, ApiError> {
20    info(transport, recent_trades_request(coin)).await
21}
22
23/// One trade on a market's tape.
24#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
25#[serde(from = "Raw")]
26#[non_exhaustive]
27pub struct Trade {
28    /// The coin traded.
29    pub coin: String,
30    /// The aggressor's side.
31    pub side: Side,
32    /// The trade price.
33    pub px: Dec,
34    /// The size traded, in the base asset.
35    pub sz: Dec,
36    /// Milliseconds.
37    pub time: u64,
38    /// The L1 transaction hash; all zeros for a TWAP slice.
39    pub hash: String,
40    /// A hash of the two order ids; unique only together with `time` and `coin`.
41    pub tid: u64,
42    /// The buying account, first in `users`.
43    pub buyer: Address,
44    /// The selling account, second in `users`.
45    pub seller: Address,
46}
47
48impl Trade {
49    /// `users` as the venue writes them: the buyer, then the seller.
50    #[must_use]
51    pub const fn users(&self) -> [Address; 2] {
52        [self.buyer, self.seller]
53    }
54}
55
56#[derive(Deserialize)]
57struct Raw {
58    coin: String,
59    side: Side,
60    px: Dec,
61    sz: Dec,
62    time: u64,
63    hash: String,
64    tid: u64,
65    users: [Address; 2],
66}
67
68impl From<Raw> for Trade {
69    fn from(raw: Raw) -> Self {
70        let [buyer, seller] = raw.users;
71        Trade {
72            coin: raw.coin,
73            side: raw.side,
74            px: raw.px,
75            sz: raw.sz,
76            time: raw.time,
77            hash: raw.hash,
78            tid: raw.tid,
79            buyer,
80            seller,
81        }
82    }
83}
84
85#[cfg(test)]
86#[path = "tests/trades.rs"]
87mod tests;