1use std::collections::BTreeMap;
31use std::fmt;
32use std::time::Duration;
33
34use crate::common::decimals::Price;
35use crate::common::errors::{ConnectorError, ValueError};
36use crate::common::ids::{AccountId, SymbolId};
37use crate::common::time::{TimeRange, Timestamp};
38use crate::open_api::client::OpenApiClient;
39use crate::open_api::connection::{ReplayKey, ReplayStage};
40use crate::open_api::messages::{
41 ProtoOaGetTrendbarsReq, ProtoOaSpotEvent, ProtoOaSubscribeLiveTrendbarReq, ProtoOaTrendbar,
42 ProtoOaTrendbarPeriod, ProtoOaUnsubscribeLiveTrendbarReq,
43};
44use crate::open_api::quotes::wire_price;
45use crate::open_api::stream::{Feed, starts_replay};
46
47const MINUTE: u64 = 60;
48const HOUR: u64 = 60 * MINUTE;
49const DAY: u64 = 24 * HOUR;
50const WEEK: u64 = 7 * DAY;
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
54pub enum Period {
55 M1,
57 M2,
59 M3,
61 M4,
63 M5,
65 M10,
67 M15,
69 M30,
71 H1,
73 H4,
75 H12,
77 D1,
79 W1,
81 Mn1,
83}
84
85impl Period {
86 pub const ALL: [Self; 14] = [
88 Self::M1,
89 Self::M2,
90 Self::M3,
91 Self::M4,
92 Self::M5,
93 Self::M10,
94 Self::M15,
95 Self::M30,
96 Self::H1,
97 Self::H4,
98 Self::H12,
99 Self::D1,
100 Self::W1,
101 Self::Mn1,
102 ];
103
104 const fn wire(self) -> ProtoOaTrendbarPeriod {
105 match self {
106 Self::M1 => ProtoOaTrendbarPeriod::M1,
107 Self::M2 => ProtoOaTrendbarPeriod::M2,
108 Self::M3 => ProtoOaTrendbarPeriod::M3,
109 Self::M4 => ProtoOaTrendbarPeriod::M4,
110 Self::M5 => ProtoOaTrendbarPeriod::M5,
111 Self::M10 => ProtoOaTrendbarPeriod::M10,
112 Self::M15 => ProtoOaTrendbarPeriod::M15,
113 Self::M30 => ProtoOaTrendbarPeriod::M30,
114 Self::H1 => ProtoOaTrendbarPeriod::H1,
115 Self::H4 => ProtoOaTrendbarPeriod::H4,
116 Self::H12 => ProtoOaTrendbarPeriod::H12,
117 Self::D1 => ProtoOaTrendbarPeriod::D1,
118 Self::W1 => ProtoOaTrendbarPeriod::W1,
119 Self::Mn1 => ProtoOaTrendbarPeriod::Mn1,
120 }
121 }
122
123 #[must_use]
125 pub const fn duration(self) -> Duration {
126 Duration::from_secs(match self {
127 Self::M1 => MINUTE,
128 Self::M2 => 2 * MINUTE,
129 Self::M3 => 3 * MINUTE,
130 Self::M4 => 4 * MINUTE,
131 Self::M5 => 5 * MINUTE,
132 Self::M10 => 10 * MINUTE,
133 Self::M15 => 15 * MINUTE,
134 Self::M30 => 30 * MINUTE,
135 Self::H1 => HOUR,
136 Self::H4 => 4 * HOUR,
137 Self::H12 => 12 * HOUR,
138 Self::D1 => DAY,
139 Self::W1 => WEEK,
140 Self::Mn1 => 30 * DAY,
141 })
142 }
143
144 #[must_use]
148 pub const fn max_range(self) -> Duration {
149 Duration::from_secs(match self {
150 Self::M1 | Self::M2 | Self::M3 | Self::M4 | Self::M5 => 5 * WEEK,
151 Self::M10 | Self::M15 | Self::M30 | Self::H1 => 35 * WEEK,
152 Self::H4 | Self::H12 | Self::D1 => 366 * DAY,
153 Self::W1 | Self::Mn1 => 1830 * DAY,
154 })
155 }
156}
157
158impl fmt::Display for Period {
159 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
160 formatter.write_str(self.wire().as_str_name())
161 }
162}
163
164const LOW: &str = "trendbar low";
165const OPEN: &str = "trendbar open";
166const HIGH: &str = "trendbar high";
167const CLOSE: &str = "trendbar close";
168const START: &str = "trendbar timestamp";
169const VOLUME: &str = "trendbar volume";
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
173#[non_exhaustive]
174pub struct Trendbar {
175 pub symbol: SymbolId,
177 pub period: Period,
179 pub timestamp: Timestamp,
181 pub open: Price,
183 pub high: Price,
185 pub low: Price,
187 pub close: Price,
189 pub volume: u64,
191}
192
193impl Trendbar {
194 fn parse(
195 symbol: SymbolId,
196 period: Period,
197 bar: &ProtoOaTrendbar,
198 last: Option<u64>,
199 ) -> Result<Self, ValueError> {
200 let low = bar.low.ok_or(ValueError::Missing { kind: LOW })?;
201 let low = u64::try_from(low).map_err(|_| ValueError::OutOfRange { kind: LOW })?;
202 let above = |delta: Option<u64>, kind: &'static str| {
203 delta
204 .ok_or(ValueError::Missing { kind })?
205 .checked_add(low)
206 .ok_or(ValueError::OutOfRange { kind })
207 };
208 let close = match (bar.delta_close, last) {
209 (None, Some(last)) => last,
210 (delta, _) => above(delta, CLOSE)?,
211 };
212 let minutes = bar
213 .utc_timestamp_in_minutes
214 .ok_or(ValueError::Missing { kind: START })?;
215 Ok(Self {
216 symbol,
217 period,
218 timestamp: Timestamp::from_minutes(minutes),
219 open: wire_price(above(bar.delta_open, OPEN)?)?,
220 high: wire_price(above(bar.delta_high, HIGH)?)?,
221 low: wire_price(low)?,
222 close: wire_price(close)?,
223 volume: u64::try_from(bar.volume)
224 .map_err(|_| ValueError::OutOfRange { kind: VOLUME })?,
225 })
226 }
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231#[must_use]
232pub struct TrendbarsParams {
233 account: AccountId,
234 symbol: SymbolId,
235 period: Period,
236 range: TimeRange,
237 count: Option<usize>,
238}
239
240impl TrendbarsParams {
241 pub const fn new(
243 account: AccountId,
244 symbol: SymbolId,
245 period: Period,
246 range: TimeRange,
247 ) -> Self {
248 Self {
249 account,
250 symbol,
251 period,
252 range,
253 count: None,
254 }
255 }
256
257 pub const fn count(mut self, count: usize) -> Self {
259 self.count = Some(count);
260 self
261 }
262
263 #[must_use]
265 pub const fn account(&self) -> AccountId {
266 self.account
267 }
268
269 #[must_use]
271 pub const fn symbol(&self) -> SymbolId {
272 self.symbol
273 }
274
275 #[must_use]
277 pub const fn period(&self) -> Period {
278 self.period
279 }
280
281 #[must_use]
283 pub const fn range(&self) -> TimeRange {
284 self.range
285 }
286
287 #[must_use]
289 pub const fn limit(&self) -> Option<usize> {
290 self.count
291 }
292}
293
294pub(crate) fn trendbar_key(account: AccountId, symbol: SymbolId, period: Period) -> ReplayKey {
295 ReplayKey::new(
296 ReplayStage::Subscription,
297 format!("trendbars/{account}/{symbol}/{period}"),
298 )
299}
300
301fn span_millis(span: Duration) -> i64 {
302 i64::try_from(span.as_millis()).unwrap_or(i64::MAX)
303}
304
305#[derive(Debug)]
318pub struct TrendbarStream {
319 client: OpenApiClient,
320 feed: Feed,
321 account: AccountId,
322 symbol: SymbolId,
323 period: Period,
324 bid: Option<u64>,
325}
326
327impl TrendbarStream {
328 #[must_use]
330 pub const fn account(&self) -> AccountId {
331 self.account
332 }
333
334 #[must_use]
336 pub const fn symbol(&self) -> SymbolId {
337 self.symbol
338 }
339
340 #[must_use]
342 pub const fn period(&self) -> Period {
343 self.period
344 }
345
346 pub async fn next(&mut self) -> Result<Trendbar, ConnectorError> {
359 let period = i32::from(self.period.wire());
360 loop {
361 let event = match self.feed.next().await {
362 Ok(event) => event,
363 Err(error) => {
364 if matches!(error, ConnectorError::Lagged { .. }) {
365 self.bid = None;
366 }
367 return Err(error);
368 }
369 };
370 if starts_replay(&event) {
371 self.bid = None;
372 continue;
373 }
374 let Some(spot) = event.decode::<ProtoOaSpotEvent>() else {
375 continue;
376 };
377 if spot.ctid_trader_account_id != self.account.get()
378 || spot.symbol_id != self.symbol.get()
379 {
380 continue;
381 }
382 self.bid = spot.bid.or(self.bid);
383 let Some(bar) = spot.trendbar.iter().find(|bar| bar.period == Some(period)) else {
384 continue;
385 };
386 if bar.delta_close.is_none() && self.bid.is_none() {
387 continue;
388 }
389 return Ok(Trendbar::parse(self.symbol, self.period, bar, self.bid)?);
390 }
391 }
392
393 pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
399 self.client
400 .unsubscribe_live_trendbars(self.account, self.symbol, self.period)
401 .await
402 }
403}
404
405impl OpenApiClient {
406 pub async fn trendbars(
420 &self,
421 params: &TrendbarsParams,
422 ) -> Result<Vec<Trendbar>, ConnectorError> {
423 let from = params.range.from().as_millis();
424 let span = span_millis(params.period.max_range());
425 let wanted = params.count.unwrap_or(usize::MAX);
426 let mut cursor = params.range.to().as_millis();
427 let mut bars = BTreeMap::new();
428 while cursor >= from && bars.len() < wanted {
429 let start = cursor.saturating_sub(span).max(from);
430 let request = ProtoOaGetTrendbarsReq {
431 payload_type: None,
432 ctid_trader_account_id: params.account.get(),
433 from_timestamp: start,
434 to_timestamp: cursor,
435 period: i32::from(params.period.wire()),
436 symbol_id: params.symbol.get(),
437 count: None,
438 };
439 let response = self.connection().request(&request).await?;
440 let mut earliest = start;
441 for (index, wire) in response.trendbar.iter().enumerate() {
442 let bar = Trendbar::parse(params.symbol, params.period, wire, None)?;
443 let opened = bar.timestamp.as_millis();
444 earliest = if index == 0 {
445 opened
446 } else {
447 earliest.min(opened)
448 };
449 bars.insert(bar.timestamp, bar);
450 }
451 cursor = earliest.min(cursor).saturating_sub(1);
452 }
453 let skipped = bars.len().saturating_sub(wanted);
454 Ok(bars.into_values().skip(skipped).collect())
455 }
456
457 pub async fn subscribe_live_trendbars(
469 &self,
470 account: AccountId,
471 symbol: SymbolId,
472 period: Period,
473 ) -> Result<TrendbarStream, ConnectorError> {
474 let stream = TrendbarStream {
475 client: self.clone(),
476 feed: Feed::new(self.connection(), account),
477 account,
478 symbol,
479 period,
480 bid: None,
481 };
482 if !self.has_spots(account, symbol) {
483 self.subscribe_spots(account, &[symbol]).await?;
484 }
485 let request = ProtoOaSubscribeLiveTrendbarReq {
486 payload_type: None,
487 ctid_trader_account_id: account.get(),
488 period: i32::from(period.wire()),
489 symbol_id: symbol.get(),
490 };
491 self.connection().request(&request).await?;
492 self.connection()
493 .register_replay(trendbar_key(account, symbol, period), &request)
494 .await?;
495 self.track_trendbars(account, symbol, period, true);
496 Ok(stream)
497 }
498
499 pub async fn unsubscribe_live_trendbars(
506 &self,
507 account: AccountId,
508 symbol: SymbolId,
509 period: Period,
510 ) -> Result<(), ConnectorError> {
511 let request = ProtoOaUnsubscribeLiveTrendbarReq {
512 payload_type: None,
513 ctid_trader_account_id: account.get(),
514 period: i32::from(period.wire()),
515 symbol_id: symbol.get(),
516 };
517 self.connection().request(&request).await?;
518 self.connection()
519 .remove_replay(trendbar_key(account, symbol, period))
520 .await?;
521 self.track_trendbars(account, symbol, period, false);
522 Ok(())
523 }
524}
525
526#[cfg(test)]
527mod tests {
528 use std::time::Duration;
529
530 use super::{Period, Trendbar, TrendbarsParams, trendbar_key};
531 use crate::common::errors::ValueError;
532 use crate::common::ids::{AccountId, SymbolId};
533 use crate::common::time::{TimeRange, Timestamp};
534 use crate::open_api::messages::{ProtoOaTrendbar, ProtoOaTrendbarPeriod};
535
536 fn symbol() -> SymbolId {
537 SymbolId::new(1).expect("symbol id")
538 }
539
540 fn wire() -> ProtoOaTrendbar {
541 ProtoOaTrendbar {
542 volume: 42,
543 period: None,
544 low: Some(108_500),
545 delta_open: Some(5),
546 delta_close: Some(7),
547 delta_high: Some(12),
548 utc_timestamp_in_minutes: Some(3),
549 }
550 }
551
552 fn parse(bar: &ProtoOaTrendbar, last: Option<u64>) -> Result<Trendbar, ValueError> {
553 Trendbar::parse(symbol(), Period::M5, bar, last)
554 }
555
556 #[test]
557 fn periods_map_to_the_wire_and_grow_in_length() {
558 let names: Vec<String> = Period::ALL.iter().map(ToString::to_string).collect();
559 assert_eq!(
560 names,
561 [
562 "M1", "M2", "M3", "M4", "M5", "M10", "M15", "M30", "H1", "H4", "H12", "D1", "W1",
563 "MN1"
564 ]
565 );
566 for (index, period) in Period::ALL.iter().enumerate() {
567 assert_eq!(
568 ProtoOaTrendbarPeriod::try_from(i32::try_from(index + 1).expect("number")),
569 Ok(period.wire())
570 );
571 assert!(period.max_range() > period.duration());
572 }
573 assert!(
574 Period::ALL
575 .windows(2)
576 .all(|pair| pair[0].duration() < pair[1].duration() && pair[0] < pair[1])
577 );
578 assert!(
579 Period::ALL
580 .windows(2)
581 .all(|pair| pair[0].max_range() <= pair[1].max_range())
582 );
583 assert_eq!(Period::M1.duration(), Duration::from_secs(60));
584 assert_eq!(Period::Mn1.duration(), Duration::from_secs(2_592_000));
585 assert_eq!(Period::M5.max_range(), Duration::from_millis(3_024_000_000));
586 assert_eq!(
587 Period::H1.max_range(),
588 Duration::from_millis(21_168_000_000)
589 );
590 assert_eq!(
591 Period::D1.max_range(),
592 Duration::from_millis(31_622_400_000)
593 );
594 assert_eq!(
595 Period::W1.max_range(),
596 Duration::from_millis(158_112_000_000)
597 );
598 }
599
600 #[test]
601 fn bar_prices_are_the_low_plus_their_deltas() {
602 let bar = parse(&wire(), None).expect("bar");
603 assert_eq!(bar.symbol, symbol());
604 assert_eq!(bar.period, Period::M5);
605 assert_eq!(bar.timestamp.as_millis(), 180_000);
606 let prices = [bar.open, bar.high, bar.low, bar.close].map(|price| price.to_string());
607 assert_eq!(prices, ["1.08505", "1.08512", "1.08500", "1.08507"]);
608 assert_eq!(bar.volume, 42);
609 assert_eq!(parse(&wire(), Some(1)), Ok(bar));
610 }
611
612 #[test]
613 fn a_live_bar_takes_its_close_from_the_last_price() {
614 let live = ProtoOaTrendbar {
615 delta_close: None,
616 ..wire()
617 };
618 let bar = parse(&live, Some(108_509)).expect("bar");
619 assert_eq!(bar.close.to_string(), "1.08509");
620 assert_eq!(
621 parse(&live, None),
622 Err(ValueError::Missing {
623 kind: "trendbar close"
624 })
625 );
626 }
627
628 #[test]
629 fn bars_with_absent_or_impossible_fields_are_rejected() {
630 let missing = |kind| Err(ValueError::Missing { kind });
631 let out_of_range = |kind| Err(ValueError::OutOfRange { kind });
632 let cases = [
633 (
634 ProtoOaTrendbar {
635 low: None,
636 ..wire()
637 },
638 missing("trendbar low"),
639 ),
640 (
641 ProtoOaTrendbar {
642 delta_open: None,
643 ..wire()
644 },
645 missing("trendbar open"),
646 ),
647 (
648 ProtoOaTrendbar {
649 delta_high: None,
650 ..wire()
651 },
652 missing("trendbar high"),
653 ),
654 (
655 ProtoOaTrendbar {
656 utc_timestamp_in_minutes: None,
657 ..wire()
658 },
659 missing("trendbar timestamp"),
660 ),
661 (
662 ProtoOaTrendbar {
663 low: Some(-1),
664 ..wire()
665 },
666 out_of_range("trendbar low"),
667 ),
668 (
669 ProtoOaTrendbar {
670 delta_high: Some(u64::MAX),
671 ..wire()
672 },
673 out_of_range("trendbar high"),
674 ),
675 (
676 ProtoOaTrendbar {
677 volume: -1,
678 ..wire()
679 },
680 out_of_range("trendbar volume"),
681 ),
682 ];
683 for (bar, error) in cases {
684 assert_eq!(parse(&bar, None), error);
685 }
686 assert_eq!(
687 ValueError::Missing {
688 kind: "trendbar low"
689 }
690 .to_string(),
691 "trendbar low is missing"
692 );
693 }
694
695 #[test]
696 fn parameters_keep_what_they_were_built_from() {
697 let account = AccountId::new(7).expect("account id");
698 let at = |millis| Timestamp::from_millis(millis).expect("timestamp");
699 let range = TimeRange::new(at(10), at(20)).expect("range");
700 let params = TrendbarsParams::new(account, symbol(), Period::H4, range);
701 assert_eq!(params.account(), account);
702 assert_eq!(params.symbol(), symbol());
703 assert_eq!(params.period(), Period::H4);
704 assert_eq!(params.range(), range);
705 assert_eq!(params.limit(), None);
706 assert_eq!(params.count(3).limit(), Some(3));
707 assert_eq!(
708 trendbar_key(account, symbol(), Period::H4).id(),
709 "trendbars/7/1/H4"
710 );
711 }
712}