tickbar 0.1.0

High-performance tick-to-bar aggregator for market data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
use crate::alignment::TimeAlignment;
use crate::bar::{Bar, BarBuilder, BarSeries};
use crate::tick::Tick;
use std::collections::HashMap;
use std::time::Duration;

/// Configuration for batch processing.
#[derive(Clone)]
pub struct AggregatorConfig {
    /// Bar interval in nanoseconds.
    pub interval_nanos: i64,
    /// Time alignment strategy.
    pub alignment: TimeAlignment,
    /// Whether to generate empty bars for gaps.
    pub fill_gaps: bool,
    /// Whether to forward-fill close prices for empty bars.
    pub forward_fill: bool,
    /// Number of decimal places for prices.
    pub price_decimals: u8,
    /// Number of decimal places for volumes.
    pub volume_decimals: u8,
}

/// Core aggregation state machine.
pub struct BarAggregator {
    current_bar: BarBuilder,
    completed_bars: Vec<Bar>,
    pub(crate) interval_nanos: i64,
    _alignment: TimeAlignment,
    _price_scale: u8,
    _volume_scale: u8,
    fill_gaps: bool,
    _forward_fill: bool,
    last_timestamp: Option<i64>,
}

impl BarAggregator {
    /// Create a new `BarAggregator`.
    pub fn new(
        interval_nanos: i64,
        alignment: TimeAlignment,
        price_scale: u8,
        volume_scale: u8,
        fill_gaps: bool,
        forward_fill: bool,
        first_tick_ts: i64,
    ) -> Self {
        let aligned_start = alignment.align(first_tick_ts);
        BarAggregator {
            current_bar: BarBuilder::new(aligned_start, aligned_start + interval_nanos),
            completed_bars: Vec::new(),
            interval_nanos,
            _alignment: alignment,
            _price_scale: price_scale,
            _volume_scale: volume_scale,
            fill_gaps,
            _forward_fill: forward_fill,
            last_timestamp: None,
        }
    }

    /// Ingest a pre-sorted slice of ticks, skipping ordering validation.
    ///
    /// Caller guarantees ticks are monotonically increasing by timestamp.
    pub fn ingest_ticks_unchecked(&mut self, ticks: &[Tick]) {
        for tick in ticks {
            if tick.timestamp_nanos >= self.current_bar.end_time {
                self.finalize_current_bar();
                self.advance_to_bar(tick.timestamp_nanos);
            }
            self.current_bar.update(tick.price, tick.volume);
        }
    }

    /// Ingest a slice of ticks with ordering validation.
    ///
    /// Returns `OutOfOrderTick` if a tick arrives out of sequence.
    pub fn ingest_ticks(&mut self, ticks: &[Tick]) -> Result<(), crate::Error> {
        for tick in ticks {
            if let Some(last) = self.last_timestamp
                && tick.timestamp_nanos < last
            {
                return Err(crate::Error::OutOfOrderTick {
                    current: tick.timestamp_nanos,
                    previous: last,
                });
            }
            self.last_timestamp = Some(tick.timestamp_nanos);

            if tick.timestamp_nanos >= self.current_bar.end_time {
                self.finalize_current_bar();
                self.advance_to_bar(tick.timestamp_nanos);
            }
            self.current_bar.update(tick.price, tick.volume);
        }
        Ok(())
    }

    /// Ingest pre-sorted data from parallel arrays, avoiding `Tick` construction.
    pub fn ingest_from_arrays(&mut self, timestamps: &[i64], prices: &[i64], volumes: &[i64]) {
        let n = timestamps.len().min(prices.len()).min(volumes.len());
        for i in 0..n {
            let ts = timestamps[i];
            if ts >= self.current_bar.end_time {
                self.finalize_current_bar();
                self.advance_to_bar(ts);
            }
            self.current_bar.update(prices[i], volumes[i]);
        }
    }

    fn advance_to_bar(&mut self, ts: i64) {
        while ts >= self.current_bar.end_time {
            if self.current_bar.is_empty() && self.fill_gaps {
                self.emit_empty_bar();
            }
            self.advance_bar_window();
        }
    }

    fn finalize_current_bar(&mut self) {
        if !self.current_bar.is_empty() {
            let bar = self.current_bar.build();
            self.completed_bars.push(bar);
        }
    }

    fn advance_bar_window(&mut self) {
        let next_start = self.current_bar.end_time;
        let next_end = next_start + self.interval_nanos;
        self.current_bar = BarBuilder::new(next_start, next_end);
    }

    fn emit_empty_bar(&mut self) {
        let close = self.completed_bars.last().map(|b| b.close).unwrap_or(0);
        let bar = Bar {
            timestamp_nanos: self.current_bar.start_time,
            open: close,
            high: close,
            low: close,
            close,
            volume: 0,
            tick_count: 0,
            vwap: close,
        };
        self.completed_bars.push(bar);
    }

    /// Drain all completed bars.
    pub fn drain_completed(&mut self) -> Vec<Bar> {
        std::mem::take(&mut self.completed_bars)
    }

    /// Peek at completed bars.
    pub fn peek_completed(&self) -> &[Bar] {
        &self.completed_bars
    }

    /// Finalize and return a `BarSeries` containing all bars
    /// including the in-progress (current) bar.
    pub fn finalize(self) -> BarSeries {
        let mut series = BarSeries::new("", self.interval_nanos);
        for bar in self.completed_bars {
            series.push(bar);
        }
        if !self.current_bar.is_empty() {
            series.push(self.current_bar.build());
        }
        series
    }
}

/// Public-facing aggregator with a builder pattern.
pub struct TickAggregator {
    pub(crate) aggregator: BarAggregator,
    symbol: String,
}

impl TickAggregator {
    /// Create a new builder.
    pub fn builder() -> TickAggregatorBuilder {
        TickAggregatorBuilder::default()
    }

    /// Push a single tick.
    pub fn push_tick(&mut self, tick: Tick) -> Result<(), crate::Error> {
        self.aggregator.ingest_ticks(std::slice::from_ref(&tick))
    }

    /// Push a batch of ticks.
    pub fn push_ticks(&mut self, ticks: &[Tick]) -> Result<(), crate::Error> {
        self.aggregator.ingest_ticks(ticks)
    }

    /// Drain completed bars.
    pub fn drain_completed(&mut self) -> Vec<Bar> {
        self.aggregator.drain_completed()
    }

    /// Peek at completed bars.
    pub fn peek_completed(&self) -> &[Bar] {
        self.aggregator.peek_completed()
    }

    /// Finalize and return all bars as a `BarSeries`.
    pub fn finalize(self) -> BarSeries {
        let interval = self.aggregator.interval_nanos;
        let bars = self.aggregator.finalize().into_inner();
        let mut series = BarSeries::new(&self.symbol, interval);
        for bar in bars {
            series.push(bar);
        }
        series
    }

    /// Process a batch of ticks with the given config and return bars.
    pub fn process_batch(
        ticks: &[Tick],
        config: AggregatorConfig,
        symbol: &str,
    ) -> crate::Result<BarSeries> {
        let first_ts = ticks.first().map_or(0, |t| t.timestamp_nanos);
        let mut agg = BarAggregator::new(
            config.interval_nanos,
            config.alignment,
            config.price_decimals,
            config.volume_decimals,
            config.fill_gaps,
            config.forward_fill,
            first_ts,
        );
        agg.ingest_ticks(ticks)?;

        // Finalize any in-progress bar
        if !agg.current_bar.is_empty() {
            agg.completed_bars.push(agg.current_bar.build());
        }

        let mut series = BarSeries::new(symbol, config.interval_nanos);
        for bar in agg.completed_bars {
            series.push(bar);
        }
        Ok(series)
    }
}

/// Builder for `TickAggregator`.
pub struct TickAggregatorBuilder {
    interval: Option<Duration>,
    alignment: TimeAlignment,
    fill_gaps: bool,
    forward_fill: bool,
    price_decimals: u8,
    volume_decimals: u8,
    symbol: String,
}

impl Default for TickAggregatorBuilder {
    fn default() -> Self {
        TickAggregatorBuilder {
            interval: None,
            alignment: TimeAlignment::UTC,
            fill_gaps: false,
            forward_fill: false,
            price_decimals: 8,
            volume_decimals: 0,
            symbol: String::new(),
        }
    }
}

impl TickAggregatorBuilder {
    /// Set the bar interval.
    pub fn interval(mut self, interval: Duration) -> Self {
        self.interval = Some(interval);
        self
    }

    /// Set exchange-aligned time with a timezone offset in seconds.
    pub fn align_to_exchange(mut self, tz_offset: i32) -> Self {
        self.alignment = TimeAlignment::Custom(tz_offset as i64 * 1_000_000_000);
        self
    }

    /// Enable or disable gap filling.
    pub fn fill_gaps(mut self, enable: bool) -> Self {
        self.fill_gaps = enable;
        self
    }

    /// Set the symbol.
    pub fn symbol(mut self, symbol: impl Into<String>) -> Self {
        self.symbol = symbol.into();
        self
    }

    /// Build the `TickAggregator`.
    pub fn build(self) -> crate::Result<TickAggregator> {
        let interval_nanos = self
            .interval
            .ok_or_else(|| crate::Error::InvalidConfiguration("interval is required".into()))?
            .as_nanos() as i64;

        let aggregator = BarAggregator::new(
            interval_nanos,
            self.alignment,
            self.price_decimals,
            self.volume_decimals,
            self.fill_gaps,
            self.forward_fill,
            0,
        );

        Ok(TickAggregator {
            aggregator,
            symbol: self.symbol,
        })
    }
}

/// Aggregate ticks for multiple symbols in parallel.
///
/// Each symbol's ticks are processed independently on separate rayon threads.
/// Returns a map from symbol name to its `BarSeries`.
pub fn aggregate_parallel(
    ticks_by_symbol: HashMap<String, Vec<Tick>>,
    config: AggregatorConfig,
) -> HashMap<String, crate::Result<BarSeries>> {
    use rayon::prelude::*;

    ticks_by_symbol
        .into_par_iter()
        .map(|(symbol, ticks)| {
            let result = TickAggregator::process_batch(&ticks, config.clone(), &symbol);
            (symbol, result)
        })
        .collect()
}

/// A simple trading calendar that defines valid trading sessions.
#[derive(Clone, Debug)]
pub struct TradingCalendar {
    /// Ordered list of (start_nanos, end_nanos) trading sessions.
    sessions: Vec<(i64, i64)>,
}

impl TradingCalendar {
    /// Create a new `TradingCalendar` from a sorted list of sessions.
    pub fn new(sessions: Vec<(i64, i64)>) -> Self {
        TradingCalendar { sessions }
    }

    /// Returns `true` if the given timestamp falls within a trading session.
    pub fn is_trading_time(&self, timestamp_nanos: i64) -> bool {
        self.sessions
            .binary_search_by(|&(start, end)| {
                if timestamp_nanos < start {
                    std::cmp::Ordering::Greater
                } else if timestamp_nanos >= end {
                    std::cmp::Ordering::Less
                } else {
                    std::cmp::Ordering::Equal
                }
            })
            .is_ok()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bar_aggregator_simple() {
        let ticks = vec![
            Tick {
                timestamp_nanos: 0,
                price: 100,
                volume: 1000,
                flags: 0,
            },
            Tick {
                timestamp_nanos: 30_000_000_000,
                price: 110,
                volume: 500,
                flags: 0,
            },
        ];
        let mut agg = BarAggregator::new(60_000_000_000, TimeAlignment::UTC, 8, 0, false, false, 0);
        agg.ingest_ticks(&ticks).unwrap();
        let series = agg.finalize();
        assert_eq!(series.as_slice().len(), 1);
        let bar = series.as_slice()[0];
        assert_eq!(bar.open, 100);
        assert_eq!(bar.close, 110);
        assert_eq!(bar.high, 110);
        assert_eq!(bar.low, 100);
        assert_eq!(bar.volume, 1500);
    }

    #[test]
    fn test_bar_aggregator_multiple_bars() {
        let ticks = vec![
            Tick {
                timestamp_nanos: 0,
                price: 100,
                volume: 1000,
                flags: 0,
            },
            Tick {
                timestamp_nanos: 61_000_000_000,
                price: 200,
                volume: 500,
                flags: 0,
            },
        ];
        let mut agg = BarAggregator::new(60_000_000_000, TimeAlignment::UTC, 8, 0, false, false, 0);
        agg.ingest_ticks(&ticks).unwrap();
        let series = agg.finalize();
        assert_eq!(series.as_slice().len(), 2);
        assert_eq!(series.as_slice()[0].close, 100);
        assert_eq!(series.as_slice()[1].close, 200);
    }

    #[test]
    fn test_gap_filling() {
        let ticks = vec![
            Tick {
                timestamp_nanos: 0,
                price: 100,
                volume: 1000,
                flags: 0,
            },
            Tick {
                timestamp_nanos: 180_000_000_000,
                price: 200,
                volume: 500,
                flags: 0,
            },
        ];
        let mut agg = BarAggregator::new(60_000_000_000, TimeAlignment::UTC, 8, 0, true, false, 0);
        agg.ingest_ticks(&ticks).unwrap();
        let series = agg.finalize();
        let bars = series.as_slice();
        assert_eq!(bars.len(), 4);
        assert_eq!(bars[0].timestamp_nanos, 0);
        assert_eq!(bars[0].close, 100);
        assert_eq!(bars[1].close, 100);
        assert_eq!(bars[2].close, 100);
        assert_eq!(bars[3].close, 200);
    }

    #[test]
    fn test_tick_aggregator_builder() {
        let mut agg = TickAggregator::builder()
            .interval(Duration::from_secs(60))
            .symbol("AAPL")
            .build()
            .unwrap();
        agg.push_tick(Tick {
            timestamp_nanos: 0,
            price: 100,
            volume: 1000,
            flags: 0,
        })
        .unwrap();
        let series = agg.finalize();
        assert_eq!(series.symbol(), "AAPL");
        assert_eq!(series.as_slice().len(), 1);
    }

    #[test]
    fn test_process_batch() {
        let ticks = vec![Tick {
            timestamp_nanos: 0,
            price: 100,
            volume: 1000,
            flags: 0,
        }];
        let config = AggregatorConfig {
            interval_nanos: 60_000_000_000,
            alignment: TimeAlignment::UTC,
            fill_gaps: false,
            forward_fill: false,
            price_decimals: 8,
            volume_decimals: 0,
        };
        let series = TickAggregator::process_batch(&ticks, config, "AAPL").unwrap();
        assert_eq!(series.symbol(), "AAPL");
        assert_eq!(series.as_slice().len(), 1);
    }

    #[test]
    fn test_aggregate_parallel() {
        let mut map = HashMap::new();
        map.insert(
            "AAPL".to_string(),
            vec![Tick {
                timestamp_nanos: 0,
                price: 100,
                volume: 1000,
                flags: 0,
            }],
        );
        map.insert(
            "GOOG".to_string(),
            vec![Tick {
                timestamp_nanos: 0,
                price: 200,
                volume: 2000,
                flags: 0,
            }],
        );
        let config = AggregatorConfig {
            interval_nanos: 60_000_000_000,
            alignment: TimeAlignment::UTC,
            fill_gaps: false,
            forward_fill: false,
            price_decimals: 8,
            volume_decimals: 0,
        };
        let results = aggregate_parallel(map, config);
        assert_eq!(results.len(), 2);
        assert!(results.get("AAPL").unwrap().is_ok());
        assert!(results.get("GOOG").unwrap().is_ok());
    }

    #[test]
    fn test_trading_calendar() {
        let sessions = vec![(0, 86_400_000_000_000)];
        let cal = TradingCalendar::new(sessions);
        assert!(cal.is_trading_time(0));
        assert!(cal.is_trading_time(43_200_000_000_000));
        assert!(!cal.is_trading_time(86_400_000_000_000));
        assert!(!cal.is_trading_time(100_000_000_000_000));
    }

    #[test]
    fn test_builder_missing_interval() {
        let result = TickAggregator::builder().build();
        assert!(result.is_err());
    }
}