Skip to main content

kestrel_chartkit/
timeframe.rs

1use crate::model::Bar;
2use std::fmt;
3
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6
7const SECONDS_PER_DAY: i64 = 86_400;
8
9/// Provider-neutral chart timeframe.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12pub enum Timeframe {
13    Second(u32),
14    Minute(u32),
15    Hour(u32),
16    Day(u32),
17    Week(u32),
18    Month(u32),
19}
20
21/// Invalid timeframe configuration.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct TimeframeError;
24
25impl fmt::Display for TimeframeError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.write_str("timeframe multiplier must be greater than zero")
28    }
29}
30
31impl std::error::Error for TimeframeError {}
32
33impl Timeframe {
34    pub fn validate(self) -> Result<Self, TimeframeError> {
35        let value = match self {
36            Self::Second(v)
37            | Self::Minute(v)
38            | Self::Hour(v)
39            | Self::Day(v)
40            | Self::Week(v)
41            | Self::Month(v) => v,
42        };
43        (value > 0).then_some(self).ok_or(TimeframeError)
44    }
45
46    /// The bucket's close timestamp (exclusive upper bound), given the bucket's open timestamp
47    /// (as returned in `Bar::timestamp` for a completed bar from [`BarResampler`]/
48    /// [`ConfirmedResampler`]). Calendar months have no fixed width — use `bucket_start` on the
49    /// next bar to find the following bucket's boundary instead.
50    pub fn bucket_close(self, bucket_open_ts: i64) -> Option<i64> {
51        self.fixed_seconds()
52            .map(|secs| bucket_open_ts + secs as i64)
53    }
54
55    /// Returns a fixed duration. Calendar months intentionally return `None`.
56    pub fn fixed_seconds(self) -> Option<u64> {
57        match self {
58            Self::Second(v) => Some(v as u64),
59            Self::Minute(v) => Some(v as u64 * 60),
60            Self::Hour(v) => Some(v as u64 * 3_600),
61            Self::Day(v) => Some(v as u64 * 86_400),
62            Self::Week(v) => Some(v as u64 * 604_800),
63            Self::Month(_) => None,
64        }
65    }
66
67    /// Parses strings such as `30s`, `15m`, `4h`, `1d`, `1w`, and `1M`.
68    pub fn parse_str(value: &str) -> Option<Self> {
69        let trimmed = value.trim();
70        let unit = trimmed.chars().last()?;
71        let number = &trimmed[..trimmed.len().checked_sub(unit.len_utf8())?];
72        let multiplier = if number.is_empty() {
73            1
74        } else {
75            number.parse().ok()?
76        };
77        let timeframe = match unit {
78            's' | 'S' => Self::Second(multiplier),
79            'm' => Self::Minute(multiplier),
80            'h' | 'H' => Self::Hour(multiplier),
81            'd' | 'D' => Self::Day(multiplier),
82            'w' | 'W' => Self::Week(multiplier),
83            'M' => Self::Month(multiplier),
84            _ => return None,
85        };
86        timeframe.validate().ok()
87    }
88
89    pub(crate) fn bucket_start(self, timestamp: i64, utc_offset_seconds: i32) -> i64 {
90        let local = timestamp + i64::from(utc_offset_seconds);
91        let start_local = match self {
92            Self::Second(v) => fixed_bucket(local, i64::from(v)),
93            Self::Minute(v) => fixed_bucket(local, i64::from(v) * 60),
94            Self::Hour(v) => fixed_bucket(local, i64::from(v) * 3_600),
95            Self::Day(v) => fixed_bucket(local, i64::from(v) * SECONDS_PER_DAY),
96            Self::Week(v) => {
97                let width = i64::from(v) * 7;
98                let day = local.div_euclid(SECONDS_PER_DAY);
99                let start_day = (day + 3).div_euclid(width) * width - 3;
100                start_day * SECONDS_PER_DAY
101            }
102            Self::Month(v) => {
103                let day = local.div_euclid(SECONDS_PER_DAY);
104                let (year, month, _) = civil_from_days(day);
105                let month_index = i64::from(year) * 12 + i64::from(month) - 1;
106                let width = i64::from(v);
107                let start_index = month_index.div_euclid(width) * width;
108                let start_year = start_index.div_euclid(12) as i32;
109                let start_month = start_index.rem_euclid(12) as u32 + 1;
110                days_from_civil(start_year, start_month, 1) * SECONDS_PER_DAY
111            }
112        };
113        start_local - i64::from(utc_offset_seconds)
114    }
115}
116
117fn fixed_bucket(timestamp: i64, width: i64) -> i64 {
118    timestamp.div_euclid(width) * width
119}
120
121// Civil-date conversions by Howard Hinnant, adapted to Unix epoch day zero.
122fn civil_from_days(days: i64) -> (i32, u32, u32) {
123    let z = days + 719_468;
124    let era = z.div_euclid(146_097);
125    let doe = z - era * 146_097;
126    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
127    let mut year = yoe + era * 400;
128    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
129    let mp = (5 * doy + 2) / 153;
130    let day = doy - (153 * mp + 2) / 5 + 1;
131    let month = mp + if mp < 10 { 3 } else { -9 };
132    year += i64::from(month <= 2);
133    (year as i32, month as u32, day as u32)
134}
135
136fn days_from_civil(year: i32, month: u32, day: u32) -> i64 {
137    let adjusted_year = i64::from(year) - i64::from(month <= 2);
138    let era = adjusted_year.div_euclid(400);
139    let yoe = adjusted_year - era * 400;
140    let shifted_month = i64::from(month) + if month > 2 { -3 } else { 9 };
141    let doy = (153 * shifted_month + 2) / 5 + i64::from(day) - 1;
142    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
143    era * 146_097 + doe - 719_468
144}
145
146impl fmt::Display for Timeframe {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        match self {
149            Self::Second(v) => write!(f, "{v}s"),
150            Self::Minute(v) => write!(f, "{v}m"),
151            Self::Hour(v) => write!(f, "{v}h"),
152            Self::Day(v) => write!(f, "{v}d"),
153            Self::Week(v) => write!(f, "{v}w"),
154            Self::Month(v) => write!(f, "{v}M"),
155        }
156    }
157}
158
159#[derive(Debug, Clone, PartialEq)]
160pub struct ResamplerOutput {
161    /// The just-closed target-timeframe bar, if this input bar started a new bucket.
162    /// `completed_bar.timestamp` is the bucket's **open** timestamp (see
163    /// [`Timeframe::bucket_close`] for the corresponding close timestamp) — the same convention
164    /// [`Bar::timestamp`] uses everywhere else in this crate.
165    pub completed_bar: Option<Bar>,
166    /// The still-forming bucket as of this input bar. Reading this is a deliberate lookahead/
167    /// repaint risk (Pine's `barstate.isconfirmed == false` case): its OHLC will keep changing
168    /// until the bucket closes. Prefer [`ConfirmedResampler`] when only confirmed HTF values may
169    /// be consumed.
170    pub current_unconfirmed: Bar,
171    /// Count of whole target-timeframe buckets with no incoming bars between the previous
172    /// completed bucket and this one (0 = no gap, i.e. contiguous). Always 0 for
173    /// [`Timeframe::Month`], whose bucket width is not a fixed duration (see
174    /// [`Timeframe::fixed_seconds`]), and for the very first bucket (no prior bucket to compare
175    /// against). Assumes bars are fed in non-decreasing timestamp order, as the whole resampler
176    /// does.
177    pub gap_buckets: u32,
178}
179
180/// Aggregates OHLCV bars into calendar-aligned target bars.
181#[derive(Debug, Clone)]
182pub struct BarResampler {
183    target_tf: Timeframe,
184    utc_offset_seconds: i32,
185    current_bucket: Option<Bar>,
186    bucket_start_ts: i64,
187}
188
189impl BarResampler {
190    pub fn new(target_tf: Timeframe) -> Result<Self, TimeframeError> {
191        Self::with_utc_offset(target_tf, 0)
192    }
193
194    pub fn with_utc_offset(
195        target_tf: Timeframe,
196        utc_offset_seconds: i32,
197    ) -> Result<Self, TimeframeError> {
198        Ok(Self {
199            target_tf: target_tf.validate()?,
200            utc_offset_seconds,
201            current_bucket: None,
202            bucket_start_ts: 0,
203        })
204    }
205
206    pub fn reset(&mut self) {
207        self.current_bucket = None;
208        self.bucket_start_ts = 0;
209    }
210
211    pub fn on_bar(&mut self, bar: &Bar) -> ResamplerOutput {
212        let bucket_start = self
213            .target_tf
214            .bucket_start(bar.timestamp, self.utc_offset_seconds);
215        let mut completed_bar = None;
216        let mut gap_buckets = 0u32;
217
218        if let Some(mut current) = self.current_bucket.take() {
219            if bucket_start != self.bucket_start_ts {
220                completed_bar = Some(current);
221                gap_buckets = self.gap_buckets_between(self.bucket_start_ts, bucket_start);
222                self.bucket_start_ts = bucket_start;
223                self.current_bucket = Some(start_bucket(bucket_start, bar));
224            } else {
225                current.high = current.high.max(bar.high);
226                current.low = current.low.min(bar.low);
227                current.close = bar.close;
228                current.volume += bar.volume;
229                self.current_bucket = Some(current);
230            }
231        } else {
232            self.bucket_start_ts = bucket_start;
233            self.current_bucket = Some(start_bucket(bucket_start, bar));
234        }
235
236        ResamplerOutput {
237            completed_bar,
238            current_unconfirmed: self.current_bucket.clone().expect("bucket was initialized"),
239            gap_buckets,
240        }
241    }
242
243    /// Whole buckets skipped between the previous bucket's open (`prev_start`) and the new
244    /// bucket's open (`next_start`), 0 if contiguous or if the target timeframe has no fixed
245    /// width (`Timeframe::Month`).
246    fn gap_buckets_between(&self, prev_start: i64, next_start: i64) -> u32 {
247        match self.target_tf.fixed_seconds() {
248            Some(width) if width > 0 => {
249                let delta_buckets = (next_start - prev_start) / (width as i64);
250                delta_buckets.saturating_sub(1).max(0) as u32
251            }
252            _ => 0,
253        }
254    }
255}
256
257/// A lookahead-safe view over a [`BarResampler`]: only ever yields a bar once its target-
258/// timeframe bucket is confirmed closed, so it is structurally impossible to read a still-forming
259/// (repainting) higher-timeframe value through it — the equivalent of Pine's
260/// `request.security(..., lookahead = barmerge.lookahead_off)` combined with confirmed-only
261/// consumption.
262#[derive(Debug, Clone)]
263pub struct ConfirmedResampler {
264    inner: BarResampler,
265}
266
267impl ConfirmedResampler {
268    pub fn new(target_tf: Timeframe) -> Result<Self, TimeframeError> {
269        Ok(Self {
270            inner: BarResampler::new(target_tf)?,
271        })
272    }
273
274    pub fn with_utc_offset(
275        target_tf: Timeframe,
276        utc_offset_seconds: i32,
277    ) -> Result<Self, TimeframeError> {
278        Ok(Self {
279            inner: BarResampler::with_utc_offset(target_tf, utc_offset_seconds)?,
280        })
281    }
282
283    pub fn reset(&mut self) {
284        self.inner.reset();
285    }
286
287    /// Returns `Some(bar)` only when this input bar closes a target-timeframe bucket; `None`
288    /// while the current bucket is still forming.
289    pub fn on_bar(&mut self, bar: &Bar) -> Option<Bar> {
290        self.inner.on_bar(bar).completed_bar
291    }
292}
293
294fn start_bucket(timestamp: i64, bar: &Bar) -> Bar {
295    Bar::new(
296        timestamp, bar.open, bar.high, bar.low, bar.close, bar.volume,
297    )
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[test]
305    fn parsing_rejects_zero_and_supports_seconds() {
306        assert_eq!(Timeframe::parse_str("30s"), Some(Timeframe::Second(30)));
307        assert_eq!(Timeframe::parse_str("15m"), Some(Timeframe::Minute(15)));
308        assert_eq!(Timeframe::parse_str("1M"), Some(Timeframe::Month(1)));
309        assert_eq!(Timeframe::parse_str("0m"), None);
310    }
311
312    #[test]
313    fn resamples_fixed_intervals() {
314        let mut resampler = BarResampler::new(Timeframe::Minute(5)).unwrap();
315        for i in 0..5 {
316            let out = resampler.on_bar(&Bar::new(
317                i * 60,
318                100.0,
319                105.0,
320                95.0,
321                100.0 + i as f64,
322                100.0,
323            ));
324            assert!(out.completed_bar.is_none());
325        }
326        let out = resampler.on_bar(&Bar::new(300, 105.0, 110.0, 104.0, 108.0, 100.0));
327        let completed = out.completed_bar.unwrap();
328        assert_eq!(completed.timestamp, 0);
329        assert_eq!(completed.close, 104.0);
330        assert_eq!(completed.volume, 500.0);
331    }
332
333    #[test]
334    fn month_boundaries_are_calendar_aligned() {
335        let february = Timeframe::Month(1).bucket_start(1_706_745_600, 0);
336        let march = Timeframe::Month(1).bucket_start(1_709_251_200, 0);
337        assert_eq!(february, 1_706_745_600);
338        assert_eq!(march, 1_709_251_200);
339        assert_ne!(march - february, 30 * SECONDS_PER_DAY);
340    }
341
342    #[test]
343    fn negative_timestamps_use_euclidean_buckets() {
344        assert_eq!(Timeframe::Day(1).bucket_start(-1, 0), -86_400);
345    }
346
347    #[test]
348    fn bucket_close_matches_fixed_width_and_is_none_for_month() {
349        assert_eq!(Timeframe::Minute(5).bucket_close(0), Some(300));
350        assert_eq!(Timeframe::Day(1).bucket_close(0), Some(SECONDS_PER_DAY));
351        assert_eq!(Timeframe::Month(1).bucket_close(0), None);
352    }
353
354    #[test]
355    fn gap_buckets_is_zero_for_contiguous_bars() {
356        let mut resampler = BarResampler::new(Timeframe::Minute(5)).unwrap();
357        resampler.on_bar(&Bar::new(0, 100.0, 101.0, 99.0, 100.0, 10.0));
358        let out = resampler.on_bar(&Bar::new(300, 100.0, 101.0, 99.0, 100.0, 10.0));
359        assert_eq!(out.gap_buckets, 0);
360    }
361
362    #[test]
363    fn gap_buckets_reports_skipped_htf_buckets() {
364        let mut resampler = BarResampler::new(Timeframe::Minute(5)).unwrap();
365        resampler.on_bar(&Bar::new(0, 100.0, 101.0, 99.0, 100.0, 10.0));
366        // Next bar arrives 3 buckets later (900s = 3 * 300s): two whole 5m buckets had no data.
367        let out = resampler.on_bar(&Bar::new(900, 100.0, 101.0, 99.0, 100.0, 10.0));
368        assert!(out.completed_bar.is_some());
369        assert_eq!(out.gap_buckets, 2);
370    }
371
372    #[test]
373    fn confirmed_resampler_never_exposes_unconfirmed_bucket() {
374        let mut confirmed = ConfirmedResampler::new(Timeframe::Minute(5)).unwrap();
375        for i in 0..5 {
376            let out = confirmed.on_bar(&Bar::new(
377                i * 60,
378                100.0,
379                105.0,
380                95.0,
381                100.0 + i as f64,
382                100.0,
383            ));
384            assert!(
385                out.is_none(),
386                "bucket must not repaint through ConfirmedResampler"
387            );
388        }
389        let closed = confirmed.on_bar(&Bar::new(300, 105.0, 110.0, 104.0, 108.0, 100.0));
390        let bar = closed.unwrap();
391        assert_eq!(bar.timestamp, 0);
392        assert_eq!(bar.close, 104.0);
393    }
394}