1use std::str::FromStr;
19
20use ibapi::market_data::{
21 historical::{
22 BarSize as HistoricalBarSize, BarTimestamp, Duration as IBDuration, HistoricalDataBuilder,
23 ToDuration, WhatToShow as HistoricalWhatToShow,
24 },
25 realtime::WhatToShow as RealtimeWhatToShow,
26};
27use jiff::{RoundMode, SignedDuration, Timestamp, TimestampRound, Unit};
28use nautilus_core::{DurationNanos, UnixNanos};
29use nautilus_model::{
30 data::{Bar, BarSpecification, BarType},
31 enums::{AssetClass, BarAggregation, PriceType},
32 instruments::{Instrument, InstrumentAny},
33 types::{Price, Quantity},
34};
35use rust_decimal::{Decimal, RoundingStrategy};
36use time::OffsetDateTime;
37
38use super::cache::is_sentinel_price;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct IbPriceConverter {
50 precision: u8,
51 increment: Option<Price>,
52 magnifier: i32,
53}
54
55impl IbPriceConverter {
56 #[must_use]
59 pub const fn new(precision: u8) -> Self {
60 Self {
61 precision,
62 increment: None,
63 magnifier: 1,
64 }
65 }
66
67 #[must_use]
69 pub const fn with_price_magnifier(mut self, magnifier: i32) -> Self {
70 self.magnifier = if magnifier < 1 { 1 } else { magnifier };
71 self
72 }
73
74 #[must_use]
77 pub fn for_instrument(instrument: &InstrumentAny, price_magnifier: i32) -> Self {
78 let increment = match instrument {
79 InstrumentAny::CurrencyPair(pair) if pair.asset_class() == AssetClass::FX => {
80 Some(pair.price_increment())
81 }
82 _ => None,
83 };
84
85 Self {
86 precision: instrument.price_precision(),
87 increment,
88 magnifier: 1,
89 }
90 .with_price_magnifier(price_magnifier)
91 }
92
93 #[must_use]
95 pub const fn precision(&self) -> u8 {
96 self.precision
97 }
98
99 #[must_use]
103 pub fn is_sentinel(&self, ib_price: f64, size: Option<f64>) -> bool {
104 is_sentinel_price(ib_price, size)
105 || is_sentinel_price(ib_price / f64::from(self.magnifier), size)
106 }
107
108 pub fn price(&self, ib_price: f64) -> anyhow::Result<Price> {
119 self.convert(ib_price, RoundingStrategy::MidpointNearestEven)
120 }
121
122 pub fn bid_price(&self, ib_price: f64) -> anyhow::Result<Price> {
131 self.convert(ib_price, RoundingStrategy::ToNegativeInfinity)
132 }
133
134 pub fn ask_price(&self, ib_price: f64) -> anyhow::Result<Price> {
144 self.convert(ib_price, RoundingStrategy::ToPositiveInfinity)
145 }
146
147 pub fn bar_price(&self, price_type: PriceType, ib_price: f64) -> anyhow::Result<Price> {
155 match price_type {
156 PriceType::Bid => self.bid_price(ib_price),
157 PriceType::Ask => self.ask_price(ib_price),
158 _ => self.price(ib_price),
159 }
160 }
161
162 fn convert(&self, ib_price: f64, strategy: RoundingStrategy) -> anyhow::Result<Price> {
168 if self.increment.is_none() && self.magnifier == 1 {
169 return Price::new_checked(ib_price, self.precision)
170 .map_err(|e| anyhow::anyhow!("invalid price={ib_price}: {e}"));
171 }
172
173 if !ib_price.is_finite() {
174 anyhow::bail!("invalid price={ib_price}: not finite");
175 }
176
177 let overflow = || anyhow::anyhow!("invalid price={ib_price}: out of range");
178 let value = Decimal::from_str(&ib_price.to_string())
179 .map_err(|e| anyhow::anyhow!("invalid price={ib_price}: {e}"))?
180 .checked_div(Decimal::from(self.magnifier))
181 .ok_or_else(overflow)?;
182
183 let value = match self.increment {
184 Some(increment) if increment.raw() > 0 => {
185 let step = increment.as_decimal();
186 value
187 .checked_div(step)
188 .ok_or_else(overflow)?
189 .round_dp_with_strategy(0, strategy)
190 .checked_mul(step)
191 .ok_or_else(overflow)?
192 }
193 _ => value,
194 };
195
196 Price::from_decimal_dp(value, self.precision)
197 .map_err(|e| anyhow::anyhow!("invalid price={ib_price}: {e}"))
198 }
199}
200
201pub fn bar_type_to_ib_bar_size(bar_type: &BarType) -> anyhow::Result<HistoricalBarSize> {
207 let spec = bar_type.spec();
208 let aggregation = spec.aggregation;
209 let step = spec.step.get();
210
211 let bar_size = match (aggregation, step) {
212 (BarAggregation::Second, 1) => HistoricalBarSize::Sec,
214 (BarAggregation::Second, 5) => HistoricalBarSize::Sec5,
215 (BarAggregation::Second, 15) => HistoricalBarSize::Sec15,
216 (BarAggregation::Second, 30) => HistoricalBarSize::Sec30,
217 (BarAggregation::Minute, 1) => HistoricalBarSize::Min,
219 (BarAggregation::Minute, 2) => HistoricalBarSize::Min2,
220 (BarAggregation::Minute, 3) => HistoricalBarSize::Min3,
221 (BarAggregation::Minute, 5) => HistoricalBarSize::Min5,
222 (BarAggregation::Minute, 10) => HistoricalBarSize::Min10,
223 (BarAggregation::Minute, 15) => HistoricalBarSize::Min15,
224 (BarAggregation::Minute, 20) => HistoricalBarSize::Min20,
225 (BarAggregation::Minute, 30) => HistoricalBarSize::Min30,
226 (BarAggregation::Hour, 1) => HistoricalBarSize::Hour,
228 (BarAggregation::Hour, 2) => HistoricalBarSize::Hour2,
229 (BarAggregation::Hour, 3) => HistoricalBarSize::Hour3,
230 (BarAggregation::Hour, 4) => HistoricalBarSize::Hour4,
231 (BarAggregation::Hour, 8) => HistoricalBarSize::Hour8,
232 (BarAggregation::Day, 1) => HistoricalBarSize::Day,
234 (BarAggregation::Week, 1) => HistoricalBarSize::Week,
236 (BarAggregation::Month, 1) => HistoricalBarSize::Month,
238 _ => {
239 anyhow::bail!("Unsupported bar aggregation/step combination: {aggregation:?}/{step}",);
240 }
241 };
242
243 Ok(bar_size)
244}
245
246#[must_use]
248pub fn price_type_to_ib_what_to_show(price_type: PriceType) -> HistoricalWhatToShow {
249 match price_type {
250 PriceType::Last => HistoricalWhatToShow::Trades,
251 PriceType::Bid => HistoricalWhatToShow::Bid,
252 PriceType::Ask => HistoricalWhatToShow::Ask,
253 PriceType::Mid => HistoricalWhatToShow::MidPoint,
254 _ => HistoricalWhatToShow::Trades, }
256}
257
258#[must_use]
265fn uses_agg_trades(is_crypto: bool, price_type: PriceType) -> bool {
266 is_crypto && price_type == PriceType::Last
267}
268
269#[must_use]
272pub fn price_type_to_ib_what_to_show_for_security(
273 price_type: PriceType,
274 is_crypto: bool,
275) -> HistoricalWhatToShow {
276 if uses_agg_trades(is_crypto, price_type) {
277 return HistoricalWhatToShow::AggTrades;
278 }
279
280 price_type_to_ib_what_to_show(price_type)
281}
282
283#[must_use]
287pub fn price_type_to_ib_realtime_what_to_show(price_type: PriceType) -> RealtimeWhatToShow {
288 match price_type {
289 PriceType::Last => RealtimeWhatToShow::Trades,
290 PriceType::Bid => RealtimeWhatToShow::Bid,
291 PriceType::Ask => RealtimeWhatToShow::Ask,
292 PriceType::Mid => RealtimeWhatToShow::MidPoint,
293 _ => RealtimeWhatToShow::Trades, }
295}
296
297#[must_use]
300pub fn price_type_to_ib_realtime_what_to_show_for_security(
301 price_type: PriceType,
302 is_crypto: bool,
303) -> RealtimeWhatToShow {
304 if uses_agg_trades(is_crypto, price_type) {
305 return RealtimeWhatToShow::AggTrades;
306 }
307
308 price_type_to_ib_realtime_what_to_show(price_type)
309}
310
311fn _validate_bar_prices(open: &mut f64, high: &mut f64, low: &mut f64, close: &f64) {
314 if *high < *low || *high < *open || *high < *close || *low > *open || *low > *close {
315 tracing::warn!(
316 "Invalid bar prices detected: O:{}, H:{}, L:{}, C:{}. Correcting using close price",
317 open,
318 high,
319 low,
320 close
321 );
322 *open = *close;
323 *high = *close;
324 *low = *close;
325 }
326}
327
328pub fn ib_bar_to_nautilus_bar(
336 ib_bar: &ibapi::market_data::historical::Bar,
337 bar_type: BarType,
338 prices: IbPriceConverter,
339 size_precision: u8,
340) -> anyhow::Result<Bar> {
341 let ts_event = bar_close_from_open(
342 ib_bar_timestamp_to_unix_nanos(&ib_bar.date),
343 &bar_type.spec(),
344 );
345 let ts_init = ts_event;
346
347 let mut open = ib_bar.open;
349 let mut high = ib_bar.high;
350 let mut low = ib_bar.low;
351 let close = ib_bar.close;
352 _validate_bar_prices(&mut open, &mut high, &mut low, &close);
353
354 let price_type = bar_type.spec().price_type;
356 let open_price = prices.bar_price(price_type, open)?;
357 let high_price = prices.bar_price(price_type, high)?;
358 let low_price = prices.bar_price(price_type, low)?;
359 let close_price = prices.bar_price(price_type, close)?;
360
361 let volume = if ib_bar.volume < 0.0 {
363 Quantity::zero(size_precision)
364 } else {
365 Quantity::new(ib_bar.volume, size_precision)
366 };
367
368 Ok(Bar::new(
369 bar_type,
370 open_price,
371 high_price,
372 low_price,
373 close_price,
374 volume,
375 ts_event,
376 ts_init,
377 ))
378}
379
380#[must_use]
384pub fn bar_close_from_open(open: UnixNanos, spec: &BarSpecification) -> UnixNanos {
385 let is_day = spec.aggregation == BarAggregation::Day;
386
387 let duration = match spec.aggregation {
388 BarAggregation::Second
389 | BarAggregation::Minute
390 | BarAggregation::Hour
391 | BarAggregation::Day => spec.timedelta(),
392 _ => return open,
393 };
394
395 let Ok(duration) = DurationNanos::try_from(duration) else {
396 return open;
397 };
398
399 let close = open.saturating_add(duration);
400 if is_day {
401 close.saturating_sub(DurationNanos::new(1))
402 } else {
403 close
404 }
405}
406
407#[must_use]
409pub fn ib_bar_timestamp_to_unix_nanos(dt: &BarTimestamp) -> UnixNanos {
410 match dt {
411 BarTimestamp::Date(date) => ib_timestamp_to_unix_nanos(&date.midnight().assume_utc()),
412 BarTimestamp::DateTime(dt) => ib_timestamp_to_unix_nanos(dt),
413 }
414}
415
416#[must_use]
418pub fn ib_timestamp_to_unix_nanos(dt: &OffsetDateTime) -> UnixNanos {
419 let timestamp = dt.unix_timestamp_nanos();
420 UnixNanos::from(timestamp as u64)
421}
422
423pub fn jiff_to_ib_datetime(dt: &Timestamp) -> OffsetDateTime {
425 OffsetDateTime::from_unix_timestamp_nanos(dt.as_nanosecond())
426 .unwrap_or_else(|_| OffsetDateTime::now_utc())
427}
428
429pub fn calculate_duration_segments(
434 start: Option<Timestamp>,
435 end: Option<Timestamp>,
436 duration: Option<IBDuration>,
437) -> Vec<(Timestamp, IBDuration)> {
438 let end = end.unwrap_or_else(Timestamp::now);
439
440 if let Some(duration) = duration {
441 return vec![(end, duration)];
442 }
443
444 let Some(start) = start else {
445 return vec![(end, 1.days())];
446 };
447
448 let mut results = Vec::new();
449 let duration = end.duration_since(start);
450 let mut total_seconds = duration.as_secs();
451 if duration.subsec_nanos() > 0 {
452 total_seconds += 1;
453 }
454
455 if total_seconds <= 0 {
456 return results;
457 }
458
459 let years = total_seconds / (365 * 24 * 3600);
460 total_seconds %= 365 * 24 * 3600;
461 let days = total_seconds / (24 * 3600);
462 total_seconds %= 24 * 3600;
463 let seconds = total_seconds;
464
465 if years > 0 {
466 results.push((end, (years as i32).years()));
467 }
468
469 if days > 0 {
470 let minus_years_duration = jiff::SignedDuration::from_hours(24 * (years * 365));
471 let minus_years_date = end - minus_years_duration;
472 results.push((minus_years_date, (days as i32).days()));
473 }
474
475 if seconds > 0 {
476 let minus_years_duration = jiff::SignedDuration::from_hours(24 * (years * 365));
477 let minus_days_duration = jiff::SignedDuration::from_hours(24 * (days));
478 let minus_days_date = end - minus_years_duration - minus_days_duration;
479 results.push((minus_days_date, (seconds as i32).seconds()));
480 }
481
482 results
483}
484
485#[must_use]
487pub(crate) fn should_continue_historical_tick_pagination(
488 current_start_date: Option<Timestamp>,
489 current_end_date: Option<Timestamp>,
490 current_len: usize,
491 limit: Option<usize>,
492) -> bool {
493 limit.is_none_or(|limit| current_len < limit)
494 && current_start_date
495 .zip(current_end_date)
496 .is_none_or(|(start, end)| end > start)
497}
498
499pub(crate) fn historical_tick_request_end(end: Timestamp) -> Timestamp {
504 truncate_to_second(end).unwrap_or(end) + SignedDuration::from_secs(1)
505}
506
507#[allow(clippy::too_many_arguments)] pub(crate) fn extend_historical_tick_batch<T>(
510 all_ticks: &mut Vec<T>,
511 batch_ticks: Vec<T>,
512 current_start_date: Option<Timestamp>,
513 current_end_date: &mut Option<Timestamp>,
514 start_nanos: Option<UnixNanos>,
515 end_nanos: Option<UnixNanos>,
516 limit: Option<usize>,
517 ts_event: impl Fn(&T) -> UnixNanos,
518) -> bool {
519 let Some(min_ts_nanos) = batch_ticks.iter().map(&ts_event).min() else {
522 return false;
523 };
524 let Some(new_end) = Timestamp::from_nanosecond(i128::from(min_ts_nanos.as_u64()))
525 .ok()
526 .and_then(truncate_to_second)
527 else {
528 return false;
529 };
530
531 if current_end_date.is_some_and(|end| new_end >= end) {
533 tracing::warn!(
534 "Historical tick pagination stopped: page starting {new_end} does not precede the \
535 requested end"
536 );
537 retain_historical_ticks_in_range(all_ticks, start_nanos, end_nanos, &ts_event);
538 return false;
539 }
540
541 *current_end_date = Some(new_end);
542
543 all_ticks.extend(batch_ticks);
544 if current_start_date.is_some_and(|start| new_end <= start) {
545 retain_historical_ticks_in_range(all_ticks, start_nanos, end_nanos, &ts_event);
546 return false;
547 }
548
549 limit.is_none_or(|limit| all_ticks.len() < limit)
550}
551
552fn truncate_to_second(timestamp: Timestamp) -> Option<Timestamp> {
553 timestamp
554 .round(
555 TimestampRound::new()
556 .smallest(Unit::Second)
557 .mode(RoundMode::Trunc),
558 )
559 .ok()
560}
561
562pub(crate) fn retain_historical_ticks_in_range<T>(
564 ticks: &mut Vec<T>,
565 start_nanos: Option<UnixNanos>,
566 end_nanos: Option<UnixNanos>,
567 ts_event: impl Fn(&T) -> UnixNanos,
568) {
569 ticks.retain(|tick| {
570 let ts_event = ts_event(tick);
571 start_nanos.is_none_or(|start| ts_event >= start)
572 && end_nanos.is_none_or(|end| ts_event <= end)
573 });
574}
575
576#[derive(Clone, Copy, Debug, PartialEq)]
578pub(crate) enum BarRequestRange {
579 Between(Timestamp, Option<Timestamp>),
581 Ending(Option<Timestamp>, IBDuration),
583}
584
585impl BarRequestRange {
586 #[must_use]
591 pub(crate) fn requests(self, spec: &BarSpecification) -> Vec<BarRequest> {
592 match self {
593 Self::Between(start, end) => {
594 let (from, to) = between_bounds(start, end, spec);
595 between_requests(from, to, max_request_span(spec))
596 }
597 Self::Ending(end, duration) => vec![BarRequest::Ending(end, duration)],
598 }
599 }
600
601 #[must_use]
605 pub(crate) fn contains(self, ts_event: UnixNanos) -> bool {
606 match self {
607 Self::Between(start, end) => {
608 let ts_event = Timestamp::from(ts_event);
609 ts_event >= start && end.is_none_or(|end| ts_event <= end)
610 }
611 Self::Ending(..) => true,
612 }
613 }
614}
615
616#[derive(Clone, Copy, Debug, PartialEq)]
618pub(crate) enum BarRequest {
619 Between(Timestamp, Timestamp),
621 Ending(Option<Timestamp>, IBDuration),
623}
624
625impl BarRequest {
626 pub(crate) fn apply<'a, C>(
628 self,
629 request: HistoricalDataBuilder<'a, C>,
630 ) -> HistoricalDataBuilder<'a, C> {
631 match self {
632 Self::Between(from, to) => {
633 request.between(jiff_to_ib_datetime(&from), jiff_to_ib_datetime(&to))
634 }
635 Self::Ending(Some(end), duration) => {
636 request.duration(duration).ending(jiff_to_ib_datetime(&end))
637 }
638 Self::Ending(None, duration) => request.duration(duration),
639 }
640 }
641}
642
643const MAX_ONE_SECOND_BARS_SPAN: SignedDuration = SignedDuration::from_secs(2000);
645
646fn max_request_span(spec: &BarSpecification) -> Option<SignedDuration> {
649 (spec.aggregation == BarAggregation::Second && spec.step.get() == 1)
650 .then_some(MAX_ONE_SECOND_BARS_SPAN)
651}
652
653const MIN_REQUEST_SPAN: SignedDuration = SignedDuration::from_secs(60);
656
657fn between_requests(
664 from: Timestamp,
665 to: Timestamp,
666 max_span: Option<SignedDuration>,
667) -> Vec<BarRequest> {
668 if to <= from {
669 return Vec::new();
670 }
671
672 let from = from.min(to - MIN_REQUEST_SPAN);
673
674 let Some(max_span) = max_span else {
675 return vec![BarRequest::Between(from, to)];
676 };
677 debug_assert_eq!(
678 to.duration_since(from).subsec_nanos(),
679 0,
680 "Invariant: one-second request bounds are whole seconds"
681 );
682
683 let max_seconds = max_span.as_secs();
684 let mut remaining = (to.duration_since(from).as_secs() + max_seconds - 1) / max_seconds;
685 let mut requests = Vec::new();
686 let mut upper = to;
687
688 while remaining > 0 {
689 let seconds = upper.duration_since(from).as_secs();
690 let lower = upper - SignedDuration::from_secs((seconds + remaining - 1) / remaining);
691 requests.push(BarRequest::Between(lower, upper));
692 upper = lower;
693 remaining -= 1;
694 }
695
696 requests
697}
698
699#[must_use]
713fn between_bounds(
714 start: Timestamp,
715 end: Option<Timestamp>,
716 spec: &BarSpecification,
717) -> (Timestamp, Timestamp) {
718 let now = Timestamp::now();
719 let end = end.unwrap_or(now);
720 let from = round_to_second(start - spec.timedelta(), RoundMode::Ceil);
721
722 let to = match spec.aggregation {
723 BarAggregation::Second | BarAggregation::Minute | BarAggregation::Hour => {
724 round_to_second(end.min(now), RoundMode::Floor)
725 }
726 _ => end + SignedDuration::from_nanos(1),
727 };
728
729 (from, to)
730}
731
732fn round_to_second(timestamp: Timestamp, mode: RoundMode) -> Timestamp {
734 timestamp
735 .round(TimestampRound::new().smallest(Unit::Second).mode(mode))
736 .expect("a request bound rounds to a second within range")
737}
738
739#[must_use]
750pub(crate) fn bar_request_range(
751 start: Option<Timestamp>,
752 end: Option<Timestamp>,
753 duration: Option<IBDuration>,
754 is_continuous_future: bool,
755) -> Option<BarRequestRange> {
756 if !is_continuous_future
757 && duration.is_none()
758 && let Some(start) = start
759 {
760 return (start < end.unwrap_or_else(Timestamp::now))
761 .then_some(BarRequestRange::Between(start, end));
762 }
763
764 let segments = calculate_duration_segments(start, end, duration);
765
766 if is_continuous_future {
767 let now = Timestamp::now();
770 let end_in_past = segments
771 .first()
772 .is_some_and(|(end, _)| *end < now - jiff::SignedDuration::from_secs(1));
773
774 if end_in_past || segments.len() > 1 {
775 tracing::warn!(
776 "Continuous futures cannot use an explicit end_date_time (IB error 10339); \
777 the request is anchored to the current time using only the first duration \
778 segment, so the returned bars may not cover the full requested range"
779 );
780 }
781
782 return segments
783 .first()
784 .map(|(_, duration)| BarRequestRange::Ending(None, *duration));
785 }
786
787 segments
788 .first()
789 .map(|(end, duration)| BarRequestRange::Ending(Some(*end), *duration))
790}
791
792#[cfg(test)]
793mod tests {
794 use std::cmp::Ordering;
795
796 use nautilus_model::{
797 data::{BarSpecification, BarType},
798 enums::{AggregationSource, BarAggregation, PriceType},
799 identifiers::{InstrumentId, Symbol, Venue},
800 instruments::Equity,
801 types::Currency,
802 };
803 use rstest::rstest;
804 use time::macros::datetime;
805
806 use super::*;
807 use crate::stubs::currency_pair;
808
809 fn create_test_instrument_id() -> InstrumentId {
810 InstrumentId::new(Symbol::from("AAPL"), Venue::from("NASDAQ"))
811 }
812
813 #[rstest]
814 fn test_bar_type_to_ib_bar_size_seconds() {
815 let instrument_id = create_test_instrument_id();
816
817 let bar_type = BarType::new(
818 instrument_id,
819 BarSpecification::new(1, BarAggregation::Second, PriceType::Last),
820 AggregationSource::External,
821 );
822 let result = bar_type_to_ib_bar_size(&bar_type);
823 assert!(result.is_ok());
824 assert_eq!(result.unwrap(), HistoricalBarSize::Sec);
825
826 let bar_type = BarType::new(
827 instrument_id,
828 BarSpecification::new(5, BarAggregation::Second, PriceType::Last),
829 AggregationSource::External,
830 );
831 let result = bar_type_to_ib_bar_size(&bar_type);
832 assert!(result.is_ok());
833 assert_eq!(result.unwrap(), HistoricalBarSize::Sec5);
834 }
835
836 #[rstest]
837 fn test_bar_type_to_ib_bar_size_minutes() {
838 let instrument_id = create_test_instrument_id();
839
840 let bar_type = BarType::new(
841 instrument_id,
842 BarSpecification::new(1, BarAggregation::Minute, PriceType::Last),
843 AggregationSource::External,
844 );
845 let result = bar_type_to_ib_bar_size(&bar_type);
846 assert!(result.is_ok());
847 assert_eq!(result.unwrap(), HistoricalBarSize::Min);
848
849 let bar_type = BarType::new(
850 instrument_id,
851 BarSpecification::new(15, BarAggregation::Minute, PriceType::Last),
852 AggregationSource::External,
853 );
854 let result = bar_type_to_ib_bar_size(&bar_type);
855 assert!(result.is_ok());
856 assert_eq!(result.unwrap(), HistoricalBarSize::Min15);
857 }
858
859 #[rstest]
860 fn test_bar_type_to_ib_bar_size_hours() {
861 let instrument_id = create_test_instrument_id();
862
863 let bar_type = BarType::new(
864 instrument_id,
865 BarSpecification::new(1, BarAggregation::Hour, PriceType::Last),
866 AggregationSource::External,
867 );
868 let result = bar_type_to_ib_bar_size(&bar_type);
869 assert!(result.is_ok());
870 assert_eq!(result.unwrap(), HistoricalBarSize::Hour);
871 }
872
873 #[rstest]
874 fn test_bar_type_to_ib_bar_size_days() {
875 let instrument_id = create_test_instrument_id();
876
877 let bar_type = BarType::new(
878 instrument_id,
879 BarSpecification::new(1, BarAggregation::Day, PriceType::Last),
880 AggregationSource::External,
881 );
882 let result = bar_type_to_ib_bar_size(&bar_type);
883 assert!(result.is_ok());
884 assert_eq!(result.unwrap(), HistoricalBarSize::Day);
885 }
886
887 #[rstest]
888 fn test_bar_type_to_ib_bar_size_unsupported() {
889 let instrument_id = create_test_instrument_id();
890
891 let bar_type = BarType::new(
892 instrument_id,
893 BarSpecification::new(12, BarAggregation::Minute, PriceType::Last),
894 AggregationSource::External,
895 );
896 let result = bar_type_to_ib_bar_size(&bar_type);
897 assert!(result.is_err());
898 }
899
900 #[rstest]
901 fn test_price_type_to_ib_what_to_show() {
902 assert_eq!(
903 price_type_to_ib_what_to_show(PriceType::Last),
904 HistoricalWhatToShow::Trades
905 );
906 assert_eq!(
907 price_type_to_ib_what_to_show(PriceType::Bid),
908 HistoricalWhatToShow::Bid
909 );
910 assert_eq!(
911 price_type_to_ib_what_to_show(PriceType::Ask),
912 HistoricalWhatToShow::Ask
913 );
914 assert_eq!(
915 price_type_to_ib_what_to_show(PriceType::Mid),
916 HistoricalWhatToShow::MidPoint
917 );
918 }
919
920 #[rstest]
921 fn test_price_type_to_ib_what_to_show_for_security_crypto() {
922 assert_eq!(
925 price_type_to_ib_what_to_show_for_security(PriceType::Last, true),
926 HistoricalWhatToShow::AggTrades
927 );
928 assert_eq!(
930 price_type_to_ib_what_to_show_for_security(PriceType::Bid, true),
931 HistoricalWhatToShow::Bid
932 );
933 assert_eq!(
934 price_type_to_ib_what_to_show_for_security(PriceType::Ask, true),
935 HistoricalWhatToShow::Ask
936 );
937 assert_eq!(
938 price_type_to_ib_what_to_show_for_security(PriceType::Mid, true),
939 HistoricalWhatToShow::MidPoint
940 );
941 }
942
943 #[rstest]
944 fn test_price_type_to_ib_what_to_show_for_security_non_crypto() {
945 assert_eq!(
948 price_type_to_ib_what_to_show_for_security(PriceType::Last, false),
949 HistoricalWhatToShow::Trades
950 );
951 assert_eq!(
952 price_type_to_ib_what_to_show_for_security(PriceType::Bid, false),
953 HistoricalWhatToShow::Bid
954 );
955 assert_eq!(
956 price_type_to_ib_what_to_show_for_security(PriceType::Mid, false),
957 HistoricalWhatToShow::MidPoint
958 );
959 }
960
961 #[rstest]
962 fn test_aggtrades_wire_string() {
963 assert_eq!(HistoricalWhatToShow::AggTrades.to_string(), "AGGTRADES");
966 assert_eq!(RealtimeWhatToShow::AggTrades.to_string(), "AGGTRADES");
967 }
968
969 #[rstest]
970 fn test_price_type_to_ib_realtime_what_to_show() {
971 assert!(matches!(
973 price_type_to_ib_realtime_what_to_show(PriceType::Last),
974 RealtimeWhatToShow::Trades
975 ));
976 assert!(matches!(
977 price_type_to_ib_realtime_what_to_show(PriceType::Bid),
978 RealtimeWhatToShow::Bid
979 ));
980 assert!(matches!(
981 price_type_to_ib_realtime_what_to_show(PriceType::Ask),
982 RealtimeWhatToShow::Ask
983 ));
984 assert!(matches!(
985 price_type_to_ib_realtime_what_to_show(PriceType::Mid),
986 RealtimeWhatToShow::MidPoint
987 ));
988 }
989
990 #[rstest]
991 fn test_price_type_to_ib_realtime_what_to_show_for_security_crypto() {
992 assert!(matches!(
997 price_type_to_ib_realtime_what_to_show_for_security(PriceType::Last, true),
998 RealtimeWhatToShow::AggTrades
999 ));
1000 assert!(matches!(
1002 price_type_to_ib_realtime_what_to_show_for_security(PriceType::Mid, true),
1003 RealtimeWhatToShow::MidPoint
1004 ));
1005 assert!(matches!(
1006 price_type_to_ib_realtime_what_to_show_for_security(PriceType::Bid, true),
1007 RealtimeWhatToShow::Bid
1008 ));
1009 assert!(matches!(
1011 price_type_to_ib_realtime_what_to_show_for_security(PriceType::Last, false),
1012 RealtimeWhatToShow::Trades
1013 ));
1014 }
1015
1016 #[rstest]
1017 fn test_ib_bar_to_nautilus_bar() {
1018 let ib_bar = ibapi::market_data::historical::Bar {
1019 date: datetime!(2024-01-01 10:00:00 UTC).into(),
1020 open: 150.0,
1021 high: 151.0,
1022 low: 149.0,
1023 close: 150.5,
1024 volume: 1000.0,
1025 wap: 150.25,
1026 count: 100,
1027 };
1028
1029 let instrument_id = create_test_instrument_id();
1030
1031 let bar_type = BarType::new(
1032 instrument_id,
1033 BarSpecification::new(1, BarAggregation::Minute, PriceType::Last),
1034 AggregationSource::External,
1035 );
1036 let result = ib_bar_to_nautilus_bar(&ib_bar, bar_type, IbPriceConverter::new(2), 0);
1037 assert!(result.is_ok());
1038 let bar = result.unwrap();
1039 assert_eq!(bar.open.as_f64(), 150.0);
1040 assert_eq!(bar.high.as_f64(), 151.0);
1041 assert_eq!(bar.low.as_f64(), 149.0);
1042 assert_eq!(bar.close.as_f64(), 150.5);
1043 assert_eq!(bar.volume.as_f64(), 1000.0);
1044 let close = ib_timestamp_to_unix_nanos(&datetime!(2024-01-01 10:01:00 UTC));
1045 assert_eq!(bar.ts_event.as_u64(), close.as_u64());
1046 assert_eq!(bar.ts_init.as_u64(), close.as_u64());
1047 }
1048
1049 #[rstest]
1050 fn test_ib_bar_to_nautilus_bar_negative_volume() {
1051 let ib_bar = ibapi::market_data::historical::Bar {
1052 date: datetime!(2024-01-01 10:00:00 UTC).into(),
1053 open: 150.0,
1054 high: 151.0,
1055 low: 149.0,
1056 close: 150.5,
1057 volume: -1.0, wap: 150.25,
1059 count: 100,
1060 };
1061
1062 let instrument_id = create_test_instrument_id();
1063
1064 let bar_type = BarType::new(
1065 instrument_id,
1066 BarSpecification::new(1, BarAggregation::Minute, PriceType::Last),
1067 AggregationSource::External,
1068 );
1069 let result = ib_bar_to_nautilus_bar(&ib_bar, bar_type, IbPriceConverter::new(2), 0);
1070 assert!(result.is_ok());
1071 let bar = result.unwrap();
1072 assert_eq!(bar.volume.as_f64(), 0.0);
1074 }
1075
1076 #[rstest]
1077 fn test_bar_close_from_open_intraday() {
1078 let open = ib_timestamp_to_unix_nanos(&datetime!(2024-01-01 10:00:00 UTC));
1079
1080 let spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
1081 assert_eq!(
1082 bar_close_from_open(open, &spec).as_u64(),
1083 ib_timestamp_to_unix_nanos(&datetime!(2024-01-01 10:00:01 UTC)).as_u64(),
1084 );
1085
1086 let spec = BarSpecification::new(5, BarAggregation::Second, PriceType::Last);
1087 assert_eq!(
1088 bar_close_from_open(open, &spec).as_u64(),
1089 ib_timestamp_to_unix_nanos(&datetime!(2024-01-01 10:00:05 UTC)).as_u64(),
1090 );
1091
1092 let spec = BarSpecification::new(1, BarAggregation::Minute, PriceType::Last);
1093 assert_eq!(
1094 bar_close_from_open(open, &spec).as_u64(),
1095 ib_timestamp_to_unix_nanos(&datetime!(2024-01-01 10:01:00 UTC)).as_u64(),
1096 );
1097
1098 let spec = BarSpecification::new(1, BarAggregation::Hour, PriceType::Last);
1099 assert_eq!(
1100 bar_close_from_open(open, &spec).as_u64(),
1101 ib_timestamp_to_unix_nanos(&datetime!(2024-01-01 11:00:00 UTC)).as_u64(),
1102 );
1103 }
1104
1105 #[rstest]
1106 fn test_bar_close_from_open_day() {
1107 let open = ib_timestamp_to_unix_nanos(&datetime!(2024-01-01 00:00:00 UTC));
1108 let spec = BarSpecification::new(1, BarAggregation::Day, PriceType::Last);
1109 assert_eq!(
1110 bar_close_from_open(open, &spec).as_u64(),
1111 open.as_u64() + 86_400_000_000_000 - 1,
1112 );
1113 }
1114
1115 #[rstest]
1116 fn test_bar_close_from_open_week_month() {
1117 let open = ib_timestamp_to_unix_nanos(&datetime!(2024-01-13 00:00:00 UTC));
1118
1119 let spec = BarSpecification::new(1, BarAggregation::Week, PriceType::Last);
1120 assert_eq!(bar_close_from_open(open, &spec).as_u64(), open.as_u64());
1121
1122 let spec = BarSpecification::new(1, BarAggregation::Month, PriceType::Last);
1123 assert_eq!(bar_close_from_open(open, &spec).as_u64(), open.as_u64());
1124 }
1125
1126 #[rstest]
1127 fn test_ib_timestamp_to_unix_nanos() {
1128 let dt = datetime!(2024-01-01 10:00:00 UTC);
1129 let result = ib_timestamp_to_unix_nanos(&dt);
1130 assert!(result.as_i64() > 0);
1131 }
1132
1133 #[rstest]
1134 fn test_jiff_to_ib_datetime() {
1135 let utc_dt = "2024-01-01T10:00:00Z".parse::<Timestamp>().unwrap();
1136 let result = jiff_to_ib_datetime(&utc_dt);
1137 assert_eq!(result.year(), 2024);
1138 assert_eq!(result.month(), time::Month::January);
1139 assert_eq!(result.day(), 1);
1140 }
1141
1142 #[rstest]
1143 fn test_calculate_duration_segments_with_start_and_end() {
1144 let start = "2024-01-01T10:00:00Z".parse::<Timestamp>().unwrap();
1145 let end = "2024-01-02T10:00:00Z".parse::<Timestamp>().unwrap();
1146 let result = calculate_duration_segments(Some(start), Some(end), None);
1147
1148 assert_eq!(result, vec![(end, IBDuration::days(1))]);
1149 }
1150
1151 #[rstest]
1152 fn test_calculate_duration_segments_without_start_defaults_to_one_day() {
1153 let end = "2024-01-02T10:00:00Z".parse::<Timestamp>().unwrap();
1154 let result = calculate_duration_segments(None, Some(end), None);
1155
1156 assert_eq!(result, vec![(end, IBDuration::days(1))]);
1157 }
1158
1159 #[rstest]
1160 fn test_calculate_duration_segments_with_explicit_duration() {
1161 let end = "2024-01-02T10:00:00Z".parse::<Timestamp>().unwrap();
1162 let result = calculate_duration_segments(None, Some(end), Some(IBDuration::weeks(2)));
1163
1164 assert_eq!(result, vec![(end, IBDuration::weeks(2))]);
1165 }
1166
1167 #[rstest]
1168 fn test_calculate_duration_segments_splits_years_days_and_seconds() {
1169 let end = "2025-07-03T10:00:01Z".parse::<Timestamp>().unwrap();
1170 let start = "2024-01-01T10:00:00Z".parse::<Timestamp>().unwrap();
1171 let segments = calculate_duration_segments(Some(start), Some(end), None);
1172
1173 assert_eq!(
1174 segments,
1175 vec![
1176 (end, IBDuration::years(1)),
1177 (
1178 "2024-07-03T10:00:01Z".parse::<Timestamp>().unwrap(),
1179 IBDuration::days(184),
1180 ),
1181 (
1182 "2024-01-01T10:00:01Z".parse::<Timestamp>().unwrap(),
1183 IBDuration::seconds(1),
1184 ),
1185 ]
1186 );
1187 }
1188
1189 #[rstest]
1190 fn test_calculate_duration_segments_rounds_subsecond_up() {
1191 let start = Timestamp::new(1, 0).unwrap();
1192 let end = Timestamp::new(1, 1).unwrap();
1193 let segments = calculate_duration_segments(Some(start), Some(end), None);
1194
1195 assert_eq!(segments, vec![(end, IBDuration::seconds(1))]);
1196 }
1197
1198 #[rstest]
1199 #[case(None, Some(Timestamp::from_second(2).unwrap()), 0, Some(10), true)]
1200 #[case(Some(Timestamp::from_second(1).unwrap()), Some(Timestamp::from_second(2).unwrap()), 0, Some(10), true)]
1201 #[case(Some(Timestamp::from_second(2).unwrap()), Some(Timestamp::from_second(1).unwrap()), 0, Some(10), false)]
1202 #[case(Some(Timestamp::from_second(1).unwrap()), Some(Timestamp::from_second(2).unwrap()), 10, Some(10), false)]
1203 #[case(Some(Timestamp::from_second(1).unwrap()), Some(Timestamp::from_second(2).unwrap()), 10, None, true)]
1204 fn test_should_continue_historical_tick_pagination(
1205 #[case] start: Option<Timestamp>,
1206 #[case] end: Option<Timestamp>,
1207 #[case] current_len: usize,
1208 #[case] limit: Option<usize>,
1209 #[case] expected: bool,
1210 ) {
1211 assert_eq!(
1212 should_continue_historical_tick_pagination(start, end, current_len, limit),
1213 expected
1214 );
1215 }
1216
1217 fn seconds(value: i64) -> UnixNanos {
1218 UnixNanos::from(u64::try_from(value).unwrap() * 1_000_000_000)
1219 }
1220
1221 #[rstest]
1222 #[case::whole_second("2026-11-13T14:30:00Z", "2026-11-13T14:30:01Z")]
1223 #[case::within_second("2026-11-13T14:30:00.5Z", "2026-11-13T14:30:01Z")]
1224 fn test_historical_tick_request_end(#[case] end: &str, #[case] expected: &str) {
1225 assert_eq!(
1226 historical_tick_request_end(timestamp(end)),
1227 timestamp(expected)
1228 );
1229 }
1230
1231 #[rstest]
1232 fn test_extend_historical_tick_batch_ends_next_page_at_earliest_second() {
1233 let mut ticks = vec![seconds(30)];
1234 let mut end = Some(Timestamp::from_second(30).unwrap());
1235
1236 let should_continue = extend_historical_tick_batch(
1237 &mut ticks,
1238 vec![seconds(20), seconds(10), seconds(10)],
1239 Some(Timestamp::from_second(1).unwrap()),
1240 &mut end,
1241 Some(seconds(1)),
1242 Some(seconds(100)),
1243 Some(10),
1244 |ts| *ts,
1245 );
1246
1247 assert!(should_continue);
1248 assert_eq!(
1249 ticks,
1250 vec![seconds(30), seconds(20), seconds(10), seconds(10)]
1251 );
1252 assert_eq!(end, Some(Timestamp::from_second(10).unwrap()));
1253 }
1254
1255 #[rstest]
1256 fn test_extend_historical_tick_batch_stops_and_trims_at_start() {
1257 let mut ticks = Vec::new();
1258 let mut end = Some(Timestamp::from_second(100).unwrap());
1259
1260 let should_continue = extend_historical_tick_batch(
1261 &mut ticks,
1262 vec![seconds(20), seconds(10)],
1263 Some(Timestamp::from_second(10).unwrap()),
1264 &mut end,
1265 Some(seconds(10)),
1266 Some(seconds(15)),
1267 Some(10),
1268 |ts| *ts,
1269 );
1270
1271 assert!(!should_continue);
1272 assert_eq!(ticks, vec![seconds(10)]);
1273 assert_eq!(end, Some(Timestamp::from_second(10).unwrap()));
1274 }
1275
1276 #[rstest]
1277 fn test_extend_historical_tick_batch_stops_when_end_cannot_retreat() {
1278 let mut ticks = vec![seconds(30)];
1279 let mut end = Some(Timestamp::from_second(30).unwrap());
1280
1281 let should_continue = extend_historical_tick_batch(
1282 &mut ticks,
1283 vec![seconds(35), seconds(30)],
1284 None,
1285 &mut end,
1286 None,
1287 None,
1288 Some(10),
1289 |ts| *ts,
1290 );
1291
1292 assert!(!should_continue);
1293 assert_eq!(ticks, vec![seconds(30)]);
1294 assert_eq!(end, Some(Timestamp::from_second(30).unwrap()));
1295 }
1296
1297 fn timestamp(value: &str) -> Timestamp {
1298 value.parse().unwrap()
1299 }
1300
1301 #[rstest]
1302 #[case::start_spans_sessions(
1303 Some(timestamp("2026-10-05T00:00:00Z")),
1304 None,
1305 false,
1306 Some(BarRequestRange::Between(
1307 timestamp("2026-10-05T00:00:00Z"),
1308 Some(timestamp("2026-10-07T18:00:00Z")),
1309 ))
1310 )]
1311 #[case::no_start(
1312 None,
1313 None,
1314 false,
1315 Some(BarRequestRange::Ending(
1316 Some(timestamp("2026-10-07T18:00:00Z")),
1317 IBDuration::days(1),
1318 ))
1319 )]
1320 #[case::duration(
1321 None,
1322 Some(IBDuration::weeks(2)),
1323 false,
1324 Some(BarRequestRange::Ending(
1325 Some(timestamp("2026-10-07T18:00:00Z")),
1326 IBDuration::weeks(2),
1327 ))
1328 )]
1329 #[case::start_at_end(Some(timestamp("2026-10-07T18:00:00Z")), None, false, None)]
1330 #[case::start_after_end(Some(timestamp("2026-10-08T00:00:00Z")), None, false, None)]
1331 #[case::continuous_future_start(
1332 Some(timestamp("2025-07-03T10:00:00Z")),
1333 None,
1334 true,
1335 Some(BarRequestRange::Ending(None, IBDuration::years(1)))
1336 )]
1337 #[case::continuous_future_no_start(
1338 None,
1339 None,
1340 true,
1341 Some(BarRequestRange::Ending(None, IBDuration::days(1)))
1342 )]
1343 #[case::continuous_future_start_after_end(
1344 Some(timestamp("2026-10-08T00:00:00Z")),
1345 None,
1346 true,
1347 None
1348 )]
1349 fn test_bar_request_range(
1350 #[case] start: Option<Timestamp>,
1351 #[case] duration: Option<IBDuration>,
1352 #[case] is_continuous_future: bool,
1353 #[case] expected: Option<BarRequestRange>,
1354 ) {
1355 let end = timestamp("2026-10-07T18:00:00Z");
1356
1357 let range = bar_request_range(start, Some(end), duration, is_continuous_future);
1358
1359 assert_eq!(range, expected);
1360 }
1361
1362 #[rstest]
1363 #[case::start_before_now(
1364 timestamp("2026-10-05T00:00:00Z"),
1365 Some(BarRequestRange::Between(timestamp("2026-10-05T00:00:00Z"), None))
1366 )]
1367 #[case::start_after_now(timestamp("2999-01-01T00:00:00Z"), None)]
1368 fn test_bar_request_range_without_end(
1369 #[case] start: Timestamp,
1370 #[case] expected: Option<BarRequestRange>,
1371 ) {
1372 let range = bar_request_range(Some(start), None, None, false);
1373
1374 assert_eq!(range, expected);
1375 }
1376
1377 #[rstest]
1378 #[case::before_start(Some(2_000), 1_000 - 1, false)]
1379 #[case::start(Some(2_000), 1_000, true)]
1380 #[case::end(Some(2_000), 2_000, true)]
1381 #[case::after_end(Some(2_000), 2_000 + 1, false)]
1382 #[case::no_end_before_start(None, 1_000 - 1, false)]
1383 #[case::no_end(None, u64::MAX, true)]
1384 fn test_bar_request_range_between_contains_closes_in_inclusive_range(
1385 #[case] end: Option<i128>,
1386 #[case] ts_event: u64,
1387 #[case] expected: bool,
1388 ) {
1389 let range = BarRequestRange::Between(
1390 Timestamp::from_nanosecond(1_000).unwrap(),
1391 end.map(|end| Timestamp::from_nanosecond(end).unwrap()),
1392 );
1393
1394 assert_eq!(range.contains(UnixNanos::from(ts_event)), expected);
1395 }
1396
1397 #[rstest]
1398 #[case::minute(BarAggregation::Minute, "2026-10-05T09:59:00Z", "2026-10-07T18:00:00Z")]
1399 #[case::day(
1400 BarAggregation::Day,
1401 "2026-10-04T10:00:00Z",
1402 "2026-10-07T18:00:00.000000001Z"
1403 )]
1404 #[case::week(
1405 BarAggregation::Week,
1406 "2026-09-28T10:00:00Z",
1407 "2026-10-07T18:00:00.000000001Z"
1408 )]
1409 fn test_between_bounds_by_aggregation(
1410 #[case] aggregation: BarAggregation,
1411 #[case] from: &str,
1412 #[case] to: &str,
1413 ) {
1414 let spec = BarSpecification::new(1, aggregation, PriceType::Last);
1415 let start = timestamp("2026-10-05T10:00:00Z");
1416 let end = timestamp("2026-10-07T18:00:00Z");
1417
1418 let bounds = between_bounds(start, Some(end), &spec);
1419
1420 assert_eq!(bounds, (timestamp(from), timestamp(to)));
1421 }
1422
1423 fn ib_duration(request: BarRequest) -> IBDuration {
1426 match request {
1427 BarRequest::Between(from, to) => {
1428 let span = to.duration_since(from);
1429 assert!(
1430 span.subsec_nanos() == 0 && span.as_secs() <= 86_400,
1431 "span {span:?} is not whole seconds up to a day"
1432 );
1433 IBDuration::seconds(i32::try_from(span.as_secs()).unwrap())
1434 }
1435 BarRequest::Ending(_, duration) => duration,
1436 }
1437 }
1438
1439 #[rstest]
1443 #[case::one_second_2000_bars(
1444 1,
1445 BarAggregation::Second,
1446 "2026-10-07T10:33:19Z",
1447 &["2000 S"]
1448 )]
1449 #[case::one_second_2001_bars(
1450 1,
1451 BarAggregation::Second,
1452 "2026-10-07T10:33:20Z",
1453 &["1001 S", "1000 S"]
1454 )]
1455 #[case::one_second_4001_bars(
1456 1,
1457 BarAggregation::Second,
1458 "2026-10-07T11:06:40Z",
1459 &["1334 S", "1334 S", "1333 S"]
1460 )]
1461 #[case::five_second(5, BarAggregation::Second, "2026-10-07T10:33:20Z", &["2005 S"])]
1462 #[case::one_minute(1, BarAggregation::Minute, "2026-10-07T10:33:20Z", &["2060 S"])]
1463 fn test_bar_request_range_requests_durations(
1464 #[case] step: usize,
1465 #[case] aggregation: BarAggregation,
1466 #[case] end: &str,
1467 #[case] durations: &[&str],
1468 ) {
1469 let spec = BarSpecification::new(step, aggregation, PriceType::Last);
1470 let range =
1471 BarRequestRange::Between(timestamp("2026-10-07T10:00:00Z"), Some(timestamp(end)));
1472
1473 let requests = range.requests(&spec);
1474
1475 let requested: Vec<String> = requests
1476 .into_iter()
1477 .map(|request| ib_duration(request).to_string())
1478 .collect();
1479 assert_eq!(requested, durations);
1480 }
1481
1482 #[rstest]
1485 #[case::one_second_within_seconds(
1486 1,
1487 "2026-10-07T10:00:00.2Z",
1488 "2026-10-07T10:00:29.5Z",
1489 "2026-10-07T09:59:29Z",
1490 "2026-10-07T10:00:29Z"
1491 )]
1492 #[case::one_second_on_seconds(
1493 1,
1494 "2026-10-07T10:00:00Z",
1495 "2026-10-07T10:00:10Z",
1496 "2026-10-07T09:59:10Z",
1497 "2026-10-07T10:00:10Z"
1498 )]
1499 #[case::five_second(
1500 5,
1501 "2026-10-07T10:00:00Z",
1502 "2026-10-07T10:00:10Z",
1503 "2026-10-07T09:59:10Z",
1504 "2026-10-07T10:00:10Z"
1505 )]
1506 fn test_bar_request_range_requests_short_range_spans_minimum(
1507 #[case] step: usize,
1508 #[case] start: &str,
1509 #[case] end: &str,
1510 #[case] from: &str,
1511 #[case] to: &str,
1512 ) {
1513 let spec = BarSpecification::new(step, BarAggregation::Second, PriceType::Last);
1514 let range = BarRequestRange::Between(timestamp(start), Some(timestamp(end)));
1515
1516 let requests = range.requests(&spec);
1517
1518 assert_eq!(
1519 requests,
1520 vec![BarRequest::Between(timestamp(from), timestamp(to))]
1521 );
1522 assert_eq!(ib_duration(requests[0]).to_string(), "60 S");
1523 }
1524
1525 const SECOND: i128 = 1_000_000_000;
1526
1527 #[rstest]
1533 fn test_bar_request_range_one_second_bars_requests_cover_range_within_ib_limit(
1534 #[values(0, 1, SECOND / 2, SECOND - 1)] start_offset: i128,
1535 #[values(1998, 1999, 2000, 2001, 3999, 4000, 4001)] seconds: i128,
1536 #[values(0, 1, SECOND / 2, SECOND - 1)] end_offset: i128,
1537 ) {
1538 let spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
1539 let base = timestamp("2026-10-07T10:00:00Z").as_nanosecond();
1540 let start = base + start_offset;
1541 let end = base + seconds * SECOND + end_offset;
1542 let first_open = (start + SECOND - 1).div_euclid(SECOND) * SECOND - SECOND;
1543 let last_close = end.div_euclid(SECOND) * SECOND;
1544 let range = BarRequestRange::Between(
1545 Timestamp::from_nanosecond(start).unwrap(),
1546 Some(Timestamp::from_nanosecond(end).unwrap()),
1547 );
1548
1549 let bounds: Vec<(i128, i128)> = range
1550 .requests(&spec)
1551 .into_iter()
1552 .map(|request| match request {
1553 BarRequest::Between(from, to) => (from.as_nanosecond(), to.as_nanosecond()),
1554 BarRequest::Ending(..) => panic!("unexpected {request:?}"),
1555 })
1556 .collect();
1557
1558 let bars = usize::try_from((last_close - first_open) / SECOND).unwrap();
1559 assert_eq!(bounds.first().map(|b| b.1), Some(last_close));
1560 assert_eq!(bounds.last().map(|b| b.0), Some(first_open));
1561 assert_eq!(bounds.len(), bars.div_ceil(2000));
1562 assert!(
1563 bounds
1564 .iter()
1565 .all(|(from, to)| to > from && to - from <= 2000 * SECOND),
1566 "{bounds:?}"
1567 );
1568 assert!(
1569 bounds.windows(2).all(|pair| pair[0].0 == pair[1].1),
1570 "{bounds:?}"
1571 );
1572 let spans = bounds.iter().map(|(from, to)| to - from);
1573 assert!(
1574 spans.clone().max().unwrap() - spans.min().unwrap() <= SECOND,
1575 "{bounds:?}"
1576 );
1577 }
1578
1579 #[rstest]
1582 fn test_bar_request_range_requests_end_by_now() {
1583 let spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
1584 let now = Timestamp::now();
1585 let range = BarRequestRange::Between(
1586 now - SignedDuration::from_secs(3000),
1587 Some(now + SignedDuration::from_secs(3000)),
1588 );
1589
1590 let requests = range.requests(&spec);
1591
1592 let latest = Timestamp::now();
1593 assert!(
1594 !requests.is_empty()
1595 && requests
1596 .iter()
1597 .all(|request| matches!(request, BarRequest::Between(_, to) if *to <= latest)),
1598 "{requests:?}"
1599 );
1600 }
1601
1602 #[rstest]
1605 fn test_bar_request_range_holding_no_bar_is_no_request() {
1606 let spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
1607 let range = BarRequestRange::Between(
1608 timestamp("2026-10-07T10:00:00.2Z"),
1609 Some(timestamp("2026-10-07T10:00:00.7Z")),
1610 );
1611
1612 assert!(range.requests(&spec).is_empty());
1613 }
1614
1615 #[rstest]
1616 fn test_bar_request_range_ending_is_one_request() {
1617 let spec = BarSpecification::new(1, BarAggregation::Hour, PriceType::Last);
1618 let range = BarRequestRange::Ending(None, IBDuration::days(1));
1619
1620 assert_eq!(
1621 range.requests(&spec),
1622 vec![BarRequest::Ending(None, IBDuration::days(1))]
1623 );
1624 }
1625
1626 #[rstest]
1627 fn test_bar_request_range_ending_contains_every_bar() {
1628 let range = BarRequestRange::Ending(None, IBDuration::days(1));
1629
1630 assert!(range.contains(UnixNanos::from(1)));
1631 }
1632
1633 fn create_equity() -> InstrumentAny {
1634 let equity = Equity::builder()
1635 .instrument_id(create_test_instrument_id())
1636 .raw_symbol(Symbol::from("AAPL"))
1637 .currency(Currency::from("USD"))
1638 .price_precision(2)
1639 .price_increment(Price::from("0.05"))
1640 .lot_size(Quantity::from("1"))
1641 .ts_event(UnixNanos::default())
1642 .ts_init(UnixNanos::default())
1643 .build()
1644 .unwrap();
1645 InstrumentAny::from(equity)
1646 }
1647
1648 #[rstest]
1649 #[case(1.12097, "1.12095")]
1650 #[case(1.12098, "1.12100")]
1651 #[case(1.12100, "1.12100")]
1652 #[case(1.12095, "1.12095")]
1653 #[case(-1.12097, "-1.12095")]
1654 fn test_price_converter_rounds_fx_pair_to_increment(
1655 #[case] ib_price: f64,
1656 #[case] expected: &str,
1657 ) {
1658 let instrument = currency_pair("EUR", "USD", 5, "0.00005");
1659 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1660
1661 let price = prices.price(ib_price).unwrap();
1662
1663 assert_eq!(price, Price::from(expected));
1664 assert_eq!(price.precision, 5);
1665 }
1666
1667 #[rstest]
1668 #[case(1e25)]
1669 #[case(-1e25)]
1670 #[case(7.9e28)]
1671 #[case(1e300)]
1672 fn test_price_converter_returns_error_for_out_of_range_price(#[case] ib_price: f64) {
1673 let fx = IbPriceConverter::for_instrument(¤cy_pair("EUR", "USD", 5, "0.00005"), 1);
1674 let magnified = IbPriceConverter::new(4).with_price_magnifier(100);
1675
1676 assert!(fx.price(ib_price).is_err());
1677 assert!(fx.bid_price(ib_price).is_err());
1678 assert!(fx.ask_price(ib_price).is_err());
1679 assert!(magnified.price(ib_price).is_err());
1680 }
1681
1682 #[rstest]
1683 fn test_price_converter_rounds_jpy_pair_to_increment() {
1684 let instrument = currency_pair("USD", "JPY", 3, "0.005");
1685 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1686
1687 assert_eq!(prices.price(151.234).unwrap(), Price::from("151.235"));
1688 assert_eq!(prices.price(151.232).unwrap(), Price::from("151.230"));
1689 }
1690
1691 #[rstest]
1692 #[case(1.000025, "1.00000")]
1693 #[case(1.000075, "1.00010")]
1694 #[case(1.000125, "1.00010")]
1695 #[case(1.000026, "1.00005")]
1696 #[case(1.120025, "1.12000")]
1697 #[case(1.120175, "1.12020")]
1698 fn test_price_converter_ties_go_to_even_multiple(
1699 #[case] ib_price: f64,
1700 #[case] expected: &str,
1701 ) {
1702 let instrument = currency_pair("EUR", "USD", 5, "0.00005");
1703 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1704
1705 let price = prices.price(ib_price).unwrap();
1706
1707 assert_eq!(price, Price::from(expected));
1708 assert_eq!(price.precision, 5);
1709 }
1710
1711 #[rstest]
1712 #[case(151.0025, "151.000")]
1713 #[case(151.0075, "151.010")]
1714 #[case(151.0125, "151.010")]
1715 fn test_price_converter_ties_go_to_even_multiple_for_jpy_pair(
1716 #[case] ib_price: f64,
1717 #[case] expected: &str,
1718 ) {
1719 let instrument = currency_pair("USD", "JPY", 3, "0.005");
1720 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1721
1722 assert_eq!(prices.price(ib_price).unwrap(), Price::from(expected));
1723 }
1724
1725 #[rstest]
1726 fn test_price_converter_rounds_every_fx_midpoint_like_exact_ties_to_even() {
1727 let instrument = currency_pair("EUR", "USD", 5, "0.00005");
1728 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1729
1730 for n in 223_850_i64..=224_150 {
1732 let micros = n * 5;
1733 let ib_price: f64 = format!("{}.{:06}", micros / 1_000_000, micros % 1_000_000)
1734 .parse()
1735 .unwrap();
1736
1737 let (quotient, remainder) = (n / 10, n % 10);
1739 let steps = match remainder.cmp(&5) {
1740 Ordering::Less => quotient,
1741 Ordering::Greater => quotient + 1,
1742 Ordering::Equal => quotient + quotient % 2,
1743 };
1744 let hundred_thousandths = steps * 5;
1745 let expected = Price::from(
1746 format!(
1747 "{}.{:05}",
1748 hundred_thousandths / 100_000,
1749 hundred_thousandths % 100_000
1750 )
1751 .as_str(),
1752 );
1753
1754 assert_eq!(
1755 prices.price(ib_price).unwrap(),
1756 expected,
1757 "ib_price={ib_price}"
1758 );
1759 }
1760 }
1761
1762 #[rstest]
1763 fn test_price_converter_does_not_round_crypto_pair() {
1764 let instrument = currency_pair("BTC", "USD", 2, "0.05");
1765 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1766
1767 assert_eq!(prices.price(100.03).unwrap(), Price::from("100.03"));
1768 }
1769
1770 #[rstest]
1771 fn test_price_converter_does_not_round_equity() {
1772 let instrument = create_equity();
1773 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1774
1775 assert_eq!(prices.precision(), 2);
1776 assert_eq!(prices.price(100.03).unwrap(), Price::from("100.03"));
1777 }
1778
1779 #[rstest]
1780 fn test_price_converter_new_applies_precision_only() {
1781 let prices = IbPriceConverter::new(5);
1782
1783 assert_eq!(prices.precision(), 5);
1784 assert_eq!(prices.price(1.12097).unwrap(), Price::from("1.12097"));
1785 }
1786
1787 #[rstest]
1788 fn test_price_converter_rejects_non_finite_price() {
1789 let prices = IbPriceConverter::new(2);
1790
1791 assert!(prices.price(f64::NAN).is_err());
1792 }
1793
1794 #[rstest]
1795 fn test_ib_bar_to_nautilus_bar_rounds_fx_prices_to_increment() {
1796 let ib_bar = ibapi::market_data::historical::Bar {
1797 date: datetime!(2024-01-01 10:00:00 UTC).into(),
1798 open: 1.12097,
1799 high: 1.12103,
1800 low: 1.12091,
1801 close: 1.12098,
1802 volume: 0.0,
1803 wap: 0.0,
1804 count: 0,
1805 };
1806 let instrument = currency_pair("EUR", "USD", 5, "0.00005");
1807 let bar_type = BarType::new(
1808 instrument.id(),
1809 BarSpecification::new(1, BarAggregation::Minute, PriceType::Mid),
1810 AggregationSource::External,
1811 );
1812
1813 let bar = ib_bar_to_nautilus_bar(
1814 &ib_bar,
1815 bar_type,
1816 IbPriceConverter::for_instrument(&instrument, 1),
1817 0,
1818 )
1819 .unwrap();
1820
1821 assert_eq!(bar.open, Price::from("1.12095"));
1822 assert_eq!(bar.high, Price::from("1.12105"));
1823 assert_eq!(bar.low, Price::from("1.12090"));
1824 assert_eq!(bar.close, Price::from("1.12100"));
1825 }
1826
1827 #[rstest]
1828 #[case(1.12098, "1.12095", "1.12100")]
1829 #[case(1.12099, "1.12095", "1.12100")]
1830 #[case(1.12097, "1.12095", "1.12100")]
1831 #[case(1.12095, "1.12095", "1.12095")]
1832 #[case(-1.12097, "-1.12100", "-1.12095")]
1833 fn test_price_converter_rounds_bid_down_and_ask_up(
1834 #[case] ib_price: f64,
1835 #[case] bid: &str,
1836 #[case] ask: &str,
1837 ) {
1838 let instrument = currency_pair("EUR", "USD", 5, "0.00005");
1839 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1840
1841 assert_eq!(prices.bid_price(ib_price).unwrap(), Price::from(bid));
1842 assert_eq!(prices.ask_price(ib_price).unwrap(), Price::from(ask));
1843 }
1844
1845 #[rstest]
1846 fn test_price_converter_rounds_bid_down_and_ask_up_for_jpy_pair() {
1847 let instrument = currency_pair("USD", "JPY", 3, "0.005");
1848 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1849
1850 assert_eq!(prices.bid_price(151.0049).unwrap(), Price::from("151.000"));
1851 assert_eq!(prices.ask_price(151.0001).unwrap(), Price::from("151.005"));
1852 }
1853
1854 #[rstest]
1855 #[case(PriceType::Bid, "1.12095")]
1856 #[case(PriceType::Ask, "1.12100")]
1857 #[case(PriceType::Mid, "1.12095")]
1858 #[case(PriceType::Last, "1.12095")]
1859 fn test_price_converter_bar_price_follows_price_type(
1860 #[case] price_type: PriceType,
1861 #[case] expected: &str,
1862 ) {
1863 let instrument = currency_pair("EUR", "USD", 5, "0.00005");
1864 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1865
1866 assert_eq!(
1867 prices.bar_price(price_type, 1.12097).unwrap(),
1868 Price::from(expected)
1869 );
1870 }
1871
1872 #[rstest]
1873 fn test_price_converter_bid_and_ask_do_not_round_equity() {
1874 let instrument = create_equity();
1875 let prices = IbPriceConverter::for_instrument(&instrument, 1);
1876
1877 assert_eq!(prices.bid_price(100.03).unwrap(), Price::from("100.03"));
1878 assert_eq!(prices.ask_price(100.03).unwrap(), Price::from("100.03"));
1879 }
1880
1881 #[rstest]
1882 #[case(PriceType::Bid, "1.12095", "1.12105", "1.12090", "1.12095")]
1883 #[case(PriceType::Ask, "1.12100", "1.12110", "1.12095", "1.12100")]
1884 fn test_ib_bar_to_nautilus_bar_rounds_fx_bid_and_ask_bars(
1885 #[case] price_type: PriceType,
1886 #[case] open: &str,
1887 #[case] high: &str,
1888 #[case] low: &str,
1889 #[case] close: &str,
1890 ) {
1891 let ib_bar = ibapi::market_data::historical::Bar {
1892 date: datetime!(2024-01-01 10:00:00 UTC).into(),
1893 open: 1.12097,
1894 high: 1.12109,
1895 low: 1.12091,
1896 close: 1.12096,
1897 volume: 0.0,
1898 wap: 0.0,
1899 count: 0,
1900 };
1901 let instrument = currency_pair("EUR", "USD", 5, "0.00005");
1902 let bar_type = BarType::new(
1903 instrument.id(),
1904 BarSpecification::new(1, BarAggregation::Minute, price_type),
1905 AggregationSource::External,
1906 );
1907
1908 let bar = ib_bar_to_nautilus_bar(
1909 &ib_bar,
1910 bar_type,
1911 IbPriceConverter::for_instrument(&instrument, 1),
1912 0,
1913 )
1914 .unwrap();
1915
1916 assert_eq!(bar.open, Price::from(open));
1917 assert_eq!(bar.high, Price::from(high));
1918 assert_eq!(bar.low, Price::from(low));
1919 assert_eq!(bar.close, Price::from(close));
1920 assert!(bar.high >= bar.low);
1921 }
1922
1923 #[rstest]
1924 #[case(425.25, "4.2525")]
1925 #[case(486.25, "4.8625")]
1926 #[case(-100.0, "-1.0000")]
1927 fn test_price_converter_divides_by_price_magnifier(
1928 #[case] ib_price: f64,
1929 #[case] expected: &str,
1930 ) {
1931 let prices = IbPriceConverter::new(4).with_price_magnifier(100);
1932
1933 assert_eq!(prices.price(ib_price).unwrap(), Price::from(expected));
1934 }
1935
1936 #[rstest]
1937 fn test_price_converter_converts_magnified_quarter_cent_steps_exactly() {
1938 let prices = IbPriceConverter::new(4).with_price_magnifier(100);
1939
1940 for n in 0_i64..=2000 {
1942 let ib_price = n as f64 * 0.25;
1943 let ten_thousandths = n * 25;
1944 let expected = Price::from(
1945 format!(
1946 "{}.{:04}",
1947 ten_thousandths / 10_000,
1948 ten_thousandths % 10_000
1949 )
1950 .as_str(),
1951 );
1952
1953 assert_eq!(
1954 prices.price(ib_price).unwrap(),
1955 expected,
1956 "ib_price={ib_price}"
1957 );
1958 }
1959 }
1960
1961 #[rstest]
1962 #[case(0)]
1963 #[case(-5)]
1964 #[case(1)]
1965 fn test_price_converter_treats_magnifier_below_one_as_one(#[case] magnifier: i32) {
1966 let prices = IbPriceConverter::new(2).with_price_magnifier(magnifier);
1967
1968 assert_eq!(prices.price(150.25).unwrap(), Price::from("150.25"));
1969 }
1970
1971 #[rstest]
1972 #[case::magnified_sentinel(100, -100.0, None, true)]
1973 #[case::magnified_sentinel_zero_size(100, -100.0, Some(0.0), true)]
1974 #[case::magnified_price_with_size(100, -100.0, Some(5.0), false)]
1975 #[case::unmagnified_sentinel(100, -1.0, None, true)]
1976 #[case::magnified_price(100, 5.5, None, false)]
1977 #[case::other_negative_price(100, -1.25, None, false)]
1978 #[case::plain_sentinel(1, -1.0, None, true)]
1979 #[case::plain_negative_price(1, -100.0, None, false)]
1980 fn test_price_converter_detects_magnified_sentinel(
1981 #[case] magnifier: i32,
1982 #[case] ib_price: f64,
1983 #[case] size: Option<f64>,
1984 #[case] expected: bool,
1985 ) {
1986 let prices = IbPriceConverter::new(5).with_price_magnifier(magnifier);
1987
1988 assert_eq!(prices.is_sentinel(ib_price, size), expected);
1989 }
1990
1991 #[rstest]
1992 fn test_price_converter_divides_before_rounding_fx_to_increment() {
1993 let instrument = currency_pair("EUR", "USD", 5, "0.00005");
1994 let prices = IbPriceConverter::for_instrument(&instrument, 100);
1995
1996 assert_eq!(prices.price(112.097).unwrap(), Price::from("1.12095"));
1997 }
1998
1999 #[rstest]
2000 fn test_ib_bar_to_nautilus_bar_divides_magnified_prices() {
2001 let ib_bar = ibapi::market_data::historical::Bar {
2002 date: datetime!(2024-01-01 10:00:00 UTC).into(),
2003 open: 425.25,
2004 high: 430.0,
2005 low: 424.5,
2006 close: 428.5,
2007 volume: 10.0,
2008 wap: 0.0,
2009 count: 1,
2010 };
2011 let bar_type = BarType::new(
2012 create_test_instrument_id(),
2013 BarSpecification::new(1, BarAggregation::Minute, PriceType::Last),
2014 AggregationSource::External,
2015 );
2016
2017 let bar = ib_bar_to_nautilus_bar(
2018 &ib_bar,
2019 bar_type,
2020 IbPriceConverter::new(4).with_price_magnifier(100),
2021 0,
2022 )
2023 .unwrap();
2024
2025 assert_eq!(bar.open, Price::from("4.2525"));
2026 assert_eq!(bar.high, Price::from("4.3000"));
2027 assert_eq!(bar.low, Price::from("4.2450"));
2028 assert_eq!(bar.close, Price::from("4.2850"));
2029 }
2030}