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