Skip to main content

df_hyperliquid_core/markets/
candle.rs

1//! Candles and their intervals, the same shape from the `candleSnapshot` read and from the `candle`
2//! feed.
3
4use std::{borrow::Cow, fmt, str::FromStr};
5
6use serde::{Deserialize, Deserializer, de};
7
8use crate::client::{ApiError, Transport, info, info_request};
9use crate::utils::Json;
10use crate::utils::dec::Dec;
11
12/// `{"type":"candleSnapshot","req":{"coin","interval","startTime","endTime"}}`,
13/// the times unix milliseconds. Only the 5000 most recent candles are kept.
14#[must_use]
15pub fn candle_snapshot_request(coin: &str, interval: Interval, start: u64, end: u64) -> String {
16    let req = Json::Object(vec![
17        ("coin".to_owned(), Json::String(coin.to_owned())),
18        ("interval".to_owned(), Json::String(interval.wire().to_owned())),
19        ("startTime".to_owned(), Json::Number(start.to_string())),
20        ("endTime".to_owned(), Json::Number(end.to_string())),
21    ]);
22    info_request("candleSnapshot", &[("req", req)])
23}
24
25/// The candles in the window, oldest first; none when the venue answers `null`.
26pub async fn candle_snapshot(
27    transport: &impl Transport,
28    coin: &str,
29    interval: Interval,
30    start: u64,
31    end: u64,
32) -> Result<Vec<Candle>, ApiError> {
33    let candles: Option<Vec<Candle>> = info(transport, candle_snapshot_request(coin, interval, start, end)).await?;
34    Ok(candles.unwrap_or_default())
35}
36
37/// A candle's width; every interval the venue accepts.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub enum Interval {
40    /// `1m`: one minute.
41    OneMinute,
42    /// `3m`: three minutes.
43    ThreeMinutes,
44    /// `5m`: five minutes.
45    FiveMinutes,
46    /// `15m`: fifteen minutes.
47    FifteenMinutes,
48    /// `30m`: thirty minutes.
49    ThirtyMinutes,
50    /// `1h`: one hour.
51    OneHour,
52    /// `2h`: two hours.
53    TwoHours,
54    /// `4h`: four hours.
55    FourHours,
56    /// `8h`: eight hours.
57    EightHours,
58    /// `12h`: twelve hours.
59    TwelveHours,
60    /// `1d`: one day.
61    OneDay,
62    /// `3d`: three days.
63    ThreeDays,
64    /// `1w`: one week.
65    OneWeek,
66    /// `1M`: one month.
67    OneMonth,
68}
69
70const MINUTE_MS: u64 = 60_000;
71
72impl Interval {
73    /// Every interval the venue accepts, finest first.
74    pub const ALL: [Interval; 14] = [
75        Interval::OneMinute,
76        Interval::ThreeMinutes,
77        Interval::FiveMinutes,
78        Interval::FifteenMinutes,
79        Interval::ThirtyMinutes,
80        Interval::OneHour,
81        Interval::TwoHours,
82        Interval::FourHours,
83        Interval::EightHours,
84        Interval::TwelveHours,
85        Interval::OneDay,
86        Interval::ThreeDays,
87        Interval::OneWeek,
88        Interval::OneMonth,
89    ];
90
91    /// As the venue spells it: `1m` is a minute, `1M` a month.
92    #[must_use]
93    pub const fn wire(self) -> &'static str {
94        match self {
95            Interval::OneMinute => "1m",
96            Interval::ThreeMinutes => "3m",
97            Interval::FiveMinutes => "5m",
98            Interval::FifteenMinutes => "15m",
99            Interval::ThirtyMinutes => "30m",
100            Interval::OneHour => "1h",
101            Interval::TwoHours => "2h",
102            Interval::FourHours => "4h",
103            Interval::EightHours => "8h",
104            Interval::TwelveHours => "12h",
105            Interval::OneDay => "1d",
106            Interval::ThreeDays => "3d",
107            Interval::OneWeek => "1w",
108            Interval::OneMonth => "1M",
109        }
110    }
111
112    /// Accepts only the venue's exact spellings.
113    #[must_use]
114    pub fn parse(text: &str) -> Option<Interval> {
115        Interval::ALL.into_iter().find(|interval| interval.wire() == text)
116    }
117
118    /// Its width in milliseconds; a month counts thirty days.
119    #[must_use]
120    pub const fn ms(self) -> u64 {
121        let minutes = match self {
122            Interval::OneMinute => 1,
123            Interval::ThreeMinutes => 3,
124            Interval::FiveMinutes => 5,
125            Interval::FifteenMinutes => 15,
126            Interval::ThirtyMinutes => 30,
127            Interval::OneHour => 60,
128            Interval::TwoHours => 120,
129            Interval::FourHours => 240,
130            Interval::EightHours => 480,
131            Interval::TwelveHours => 720,
132            Interval::OneDay => 1_440,
133            Interval::ThreeDays => 4_320,
134            Interval::OneWeek => 10_080,
135            Interval::OneMonth => 43_200,
136        };
137        minutes * MINUTE_MS
138    }
139}
140
141/// A text that is none of the venue's interval spellings; holds the text.
142#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
143#[error("`{0}` is not an interval; the venue takes 1m 3m 5m 15m 30m 1h 2h 4h 8h 12h 1d 3d 1w 1M")]
144pub struct UnknownInterval(pub String);
145
146impl FromStr for Interval {
147    type Err = UnknownInterval;
148
149    fn from_str(text: &str) -> Result<Self, Self::Err> {
150        Interval::parse(text).ok_or_else(|| UnknownInterval(text.to_owned()))
151    }
152}
153
154impl fmt::Display for Interval {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        f.write_str(self.wire())
157    }
158}
159
160impl<'de> Deserialize<'de> for Interval {
161    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
162        let text = <Cow<'de, str>>::deserialize(deserializer)?;
163        text.parse().map_err(de::Error::custom)
164    }
165}
166
167/// One candle, `t` to `T` inclusive. The feed resends it as it forms.
168#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
169pub struct Candle {
170    /// Open time, milliseconds.
171    #[serde(rename = "t")]
172    pub open_time: u64,
173    /// The last millisecond inside it, not the next one's open.
174    #[serde(rename = "T")]
175    pub close_time: u64,
176    /// The coin (`s`).
177    #[serde(rename = "s")]
178    pub coin: String,
179    /// The candle's width (`i`).
180    #[serde(rename = "i")]
181    pub interval: Interval,
182    /// The first trade price (`o`).
183    #[serde(rename = "o")]
184    pub open: Dec,
185    /// The last trade price (`c`).
186    #[serde(rename = "c")]
187    pub close: Dec,
188    /// The highest trade price (`h`).
189    #[serde(rename = "h")]
190    pub high: Dec,
191    /// The lowest trade price (`l`).
192    #[serde(rename = "l")]
193    pub low: Dec,
194    /// In the base asset.
195    #[serde(rename = "v")]
196    pub volume: Dec,
197    /// Number of trades in the bar.
198    #[serde(rename = "n")]
199    pub trades: u64,
200}
201
202#[cfg(test)]
203#[path = "tests/candle.rs"]
204mod tests;