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 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
use std::fmt::Debug;
use num_enum::TryFromPrimitive;
use crate::{
compat::{ErrorMsgV1, InstrumentDefMsgV1, SymbolMappingMsgV1, SystemMsgV1},
enums::{StatusAction, StatusReason},
SType, TradingEvent, TriState,
};
use super::*;
impl RecordHeader {
/// The multiplier for converting the `length` field to the number of bytes.
pub const LENGTH_MULTIPLIER: usize = 4;
/// Creates a new `RecordHeader`. `R` and `rtype` should be compatible.
pub const fn new<R: HasRType>(
rtype: u8,
publisher_id: u16,
instrument_id: u32,
ts_event: u64,
) -> Self {
Self {
length: (mem::size_of::<R>() / Self::LENGTH_MULTIPLIER) as u8,
rtype,
publisher_id,
instrument_id,
ts_event,
}
}
/// Returns the size of the **entire** record in bytes. The size of a `RecordHeader`
/// is constant.
pub const fn record_size(&self) -> usize {
self.length as usize * Self::LENGTH_MULTIPLIER
}
/// Tries to convert the raw record type into an enum.
///
/// # Errors
/// This function returns an error if the `rtype` field does not
/// contain a valid, known [`RType`].
pub fn rtype(&self) -> crate::Result<RType> {
RType::try_from(self.rtype)
.map_err(|_| Error::conversion::<RType>(format!("{:#04X}", self.rtype)))
}
/// Tries to convert the raw `publisher_id` into an enum which is useful for
/// exhaustive pattern matching.
///
/// # Errors
/// This function returns an error if the `publisher_id` does not correspond with
/// any known [`Publisher`].
pub fn publisher(&self) -> crate::Result<Publisher> {
Publisher::try_from(self.publisher_id)
.map_err(|_| Error::conversion::<Publisher>(self.publisher_id))
}
/// Parses the raw matching-engine-received timestamp into a datetime. Returns
/// `None` if `ts_event` contains the sentinel for a null timestamp.
pub fn ts_event(&self) -> Option<time::OffsetDateTime> {
if self.ts_event == crate::UNDEF_TIMESTAMP {
None
} else {
// u64::MAX is within maximum allowable range
Some(time::OffsetDateTime::from_unix_timestamp_nanos(self.ts_event as i128).unwrap())
}
}
}
impl Debug for RecordHeader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut debug_struct = f.debug_struct("RecordHeader");
debug_struct.field("length", &self.length);
match self.rtype() {
Ok(rtype) => debug_struct.field("rtype", &format_args!("{rtype:?}")),
Err(_) => debug_struct.field("rtype", &format_args!("{:#04X}", &self.rtype)),
};
match self.publisher() {
Ok(p) => debug_struct.field("publisher_id", &format_args!("{p:?}")),
Err(_) => debug_struct.field("publisher_id", &self.publisher_id),
};
debug_struct
.field("instrument_id", &self.instrument_id)
.field("ts_event", &self.ts_event)
.finish()
}
}
impl MboMsg {
/// Tries to convert the raw order side to an enum.
///
/// # Errors
/// This function returns an error if the `side` field does not
/// contain a valid [`Side`].
pub fn side(&self) -> crate::Result<Side> {
Side::try_from(self.side as u8)
.map_err(|_| Error::conversion::<Side>(format!("{:#04X}", self.side as u8)))
}
/// Tries to convert the raw event action to an enum.
///
/// # Errors
/// This function returns an error if the `action` field does not
/// contain a valid [`Action`].
pub fn action(&self) -> crate::Result<Action> {
Action::try_from(self.action as u8)
.map_err(|_| Error::conversion::<Action>(format!("{:#04X}", self.action as u8)))
}
/// Parses the raw interval timestamp into a datetime. Returns `None` if `ts_recv`
/// contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
/// Parses the raw `ts_in_delta`—the delta of `ts_recv - ts_exchange_send`—into a duration.
pub fn ts_in_delta(&self) -> time::Duration {
time::Duration::new(0, self.ts_in_delta)
}
}
impl TradeMsg {
/// Tries to convert the raw order side to an enum.
///
/// # Errors
/// This function returns an error if the `side` field does not
/// contain a valid [`Side`].
pub fn side(&self) -> crate::Result<Side> {
Side::try_from(self.side as u8)
.map_err(|_| Error::conversion::<Side>(format!("{:#04X}", self.side as u8)))
}
/// Tries to convert the raw event action to an enum.
///
/// # Errors
/// This function returns an error if the `action` field does not
/// contain a valid [`Action`].
pub fn action(&self) -> crate::Result<Action> {
Action::try_from(self.action as u8)
.map_err(|_| Error::conversion::<Action>(format!("{:#04X}", self.action as u8)))
}
/// Parses the raw capture-server-received timestamp into a datetime. Returns `None`
/// if `ts_recv` contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
/// Parses the raw `ts_in_delta`—the delta of `ts_recv - ts_exchange_send`—into a duration.
pub fn ts_in_delta(&self) -> time::Duration {
time::Duration::new(0, self.ts_in_delta)
}
}
impl BboMsg {
/// Tries to convert the raw `side` to an enum.
///
/// # Errors
/// This function returns an error if the `side` field does not
/// contain a valid [`Side`].
pub fn side(&self) -> crate::Result<Side> {
Side::try_from(self.side as u8)
.map_err(|_| Error::conversion::<Side>(format!("{:#04X}", self.side as u8)))
}
/// Parses the raw capture-server-received timestamp into a datetime. Returns `None`
/// if `ts_recv` contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
}
impl CbboMsg {
/// Tries to convert the raw `side` to an enum.
///
/// # Errors
/// This function returns an error if the `side` field does not
/// contain a valid [`Side`].
pub fn side(&self) -> crate::Result<Side> {
Side::try_from(self.side as u8)
.map_err(|_| Error::conversion::<Side>(format!("{:#04X}", self.side as u8)))
}
/// Tries to convert the raw event action to an enum.
///
/// # Errors
/// This function returns an error if the `action` field does not
/// contain a valid [`Action`].
pub fn action(&self) -> crate::Result<Action> {
Action::try_from(self.action as u8)
.map_err(|_| Error::conversion::<Action>(format!("{:#04X}", self.action as u8)))
}
/// Parses the raw capture-server-received timestamp into a datetime. Returns `None`
/// if `ts_recv` contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
/// Parses the raw `ts_in_delta`—the delta of `ts_recv - ts_exchange_send`—into a duration.
pub fn ts_in_delta(&self) -> time::Duration {
time::Duration::new(0, self.ts_in_delta)
}
}
impl ConsolidatedBidAskPair {
/// Tries to convert the raw `bid_pb` into an enum which is useful for
/// exhaustive pattern matching.
///
/// # Errors
/// This function returns an error if the `publisher_id` does not correspond with
/// any known [`Publisher`].
pub fn bid_pb(&self) -> crate::Result<Publisher> {
Publisher::try_from(self.bid_pb)
.map_err(|_| crate::error::Error::conversion::<Publisher>(self.bid_pb))
}
/// Tries to convert the raw `ask_pb` into an enum which is useful for
/// exhaustive pattern matching.
///
/// # Errors
/// This function returns an error if the `ask_pb` does not correspond with
/// any known [`Publisher`].
pub fn ask_pb(&self) -> crate::Result<Publisher> {
Publisher::try_from(self.ask_pb)
.map_err(|_| crate::error::Error::conversion::<Publisher>(self.ask_pb))
}
}
impl Mbp1Msg {
/// Tries to convert the raw `side` to an enum.
///
/// # Errors
/// This function returns an error if the `side` field does not
/// contain a valid [`Side`].
pub fn side(&self) -> crate::Result<Side> {
Side::try_from(self.side as u8)
.map_err(|_| Error::conversion::<Side>(format!("{:#04X}", self.side as u8)))
}
/// Tries to convert the raw event action to an enum.
///
/// # Errors
/// This function returns an error if the `action` field does not
/// contain a valid [`Action`].
pub fn action(&self) -> crate::Result<Action> {
Action::try_from(self.action as u8)
.map_err(|_| Error::conversion::<Action>(format!("{:#04X}", self.action as u8)))
}
/// Parses the raw capture-server-received timestamp into a datetime. Returns `None`
/// if `ts_recv` contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
/// Parses the raw `ts_in_delta`—the delta of `ts_recv - ts_exchange_send`—into a duration.
pub fn ts_in_delta(&self) -> time::Duration {
time::Duration::new(0, self.ts_in_delta)
}
}
impl Mbp10Msg {
/// Tries to convert the raw `side` to an enum.
///
/// # Errors
/// This function returns an error if the `side` field does not
/// contain a valid [`Side`].
pub fn side(&self) -> Result<Side> {
Side::try_from(self.side as u8)
.map_err(|_| Error::conversion::<Side>(format!("{:#04X}", self.side as u8)))
}
/// Tries to convert the raw event action to an enum.
///
/// # Errors
/// This function returns an error if the `action` field does not
/// contain a valid [`Action`].
pub fn action(&self) -> Result<Action> {
Action::try_from(self.action as u8)
.map_err(|_| Error::conversion::<Action>(format!("{:#04X}", self.action as u8)))
}
/// Parses the raw capture-server-received timestamp into a datetime. Returns `None`
/// if `ts_recv` contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
/// Parses the raw `ts_in_delta`—the delta of `ts_recv - ts_exchange_send`—into a duration.
pub fn ts_in_delta(&self) -> time::Duration {
time::Duration::new(0, self.ts_in_delta)
}
}
impl StatusMsg {
/// Tries to convert the raw status action to an enum.
///
/// # Errors
/// This function returns an error if the `action` field does not contain a valid
/// [`StatusAction`].
pub fn action(&self) -> Result<StatusAction> {
StatusAction::try_from(self.action)
.map_err(|_| Error::conversion::<StatusAction>(format!("{:#06X}", self.action)))
}
/// Tries to convert the raw status reason to an enum.
///
/// # Errors
/// This function returns an error if the `reason` field does not contain a valid
/// [`StatusReason`].
pub fn reason(&self) -> Result<StatusReason> {
StatusReason::try_from(self.reason)
.map_err(|_| Error::conversion::<StatusReason>(format!("{:#06X}", self.reason)))
}
/// Tries to convert the raw status trading event to an enum.
///
/// # Errors
/// This function returns an error if the `trading_event` field does not contain a
/// valid [`TradingEvent`].
pub fn trading_event(&self) -> Result<TradingEvent> {
TradingEvent::try_from(self.trading_event)
.map_err(|_| Error::conversion::<TradingEvent>(format!("{:#06X}", self.trading_event)))
}
/// Converts the raw `is_trading` state to an `Option<bool>` where `None` indicates
/// a value is not applicable or available.
pub fn is_trading(&self) -> Option<bool> {
TriState::try_from_primitive(self.is_trading as c_char as u8)
.map(Option::<bool>::from)
.unwrap_or_default()
}
/// Converts the raw `is_quoting` state to an `Option<bool>` where `None` indicates
/// a value is not applicable or available.
pub fn is_quoting(&self) -> Option<bool> {
TriState::try_from_primitive(self.is_quoting as c_char as u8)
.map(Option::<bool>::from)
.unwrap_or_default()
}
/// Converts the raw `is_short_sell_restricted` state to an `Option<bool>` where
/// `None` indicates a value is not applicable or available.
pub fn is_short_sell_restricted(&self) -> Option<bool> {
TriState::try_from_primitive(self.is_short_sell_restricted as c_char as u8)
.map(Option::<bool>::from)
.unwrap_or_default()
}
}
impl InstrumentDefMsg {
/// Parses the raw capture-server-received timestamp into a datetime. Returns `None`
/// if `ts_recv` contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
/// Parses the raw last eligible trade time into a datetime. Returns `None` if
/// `expiration` contains the sentinel for a null timestamp.
pub fn expiration(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.expiration)
}
/// Parses the raw time of instrument action into a datetime. Returns `None` if
/// `activation` contains the sentinel for a null timestamp.
pub fn activation(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.activation)
}
/// Returns currency used for price fields as a `&str`.
///
/// # Errors
/// This function returns an error if `currency` contains invalid UTF-8.
pub fn currency(&self) -> Result<&str> {
c_chars_to_str(&self.currency)
}
/// Returns currency used for settlement as a `&str`.
///
/// # Errors
/// This function returns an error if `settl_currency` contains invalid UTF-8.
pub fn settl_currency(&self) -> Result<&str> {
c_chars_to_str(&self.settl_currency)
}
/// Returns the strategy type of the spread as a `&str`.
///
/// # Errors
/// This function returns an error if `secsubtype` contains invalid UTF-8.
pub fn secsubtype(&self) -> Result<&str> {
c_chars_to_str(&self.secsubtype)
}
/// Returns the instrument raw symbol assigned by the publisher as a `&str`.
///
/// # Errors
/// This function returns an error if `raw_symbol` contains invalid UTF-8.
pub fn raw_symbol(&self) -> Result<&str> {
c_chars_to_str(&self.raw_symbol)
}
/// Returns exchange used to identify the instrument as a `&str`.
///
/// # Errors
/// This function returns an error if `exchange` contains invalid UTF-8.
pub fn exchange(&self) -> Result<&str> {
c_chars_to_str(&self.exchange)
}
/// Returns the underlying asset code (product code) of the instrument as a `&str`.
///
/// # Errors
/// This function returns an error if `asset` contains invalid UTF-8.
pub fn asset(&self) -> Result<&str> {
c_chars_to_str(&self.asset)
}
/// Returns the ISO standard instrument categorization code as a `&str`.
///
/// # Errors
/// This function returns an error if `cfi` contains invalid UTF-8.
pub fn cfi(&self) -> Result<&str> {
c_chars_to_str(&self.cfi)
}
/// Returns the type of the strument, e.g. FUT for future or future spread as
/// a `&str`.
///
/// # Errors
/// This function returns an error if `security_type` contains invalid UTF-8.
pub fn security_type(&self) -> Result<&str> {
c_chars_to_str(&self.security_type)
}
/// Returns the unit of measure for the instrument's original contract size, e.g.
/// USD or LBS, as a `&str`.
///
/// # Errors
/// This function returns an error if `unit_of_measure` contains invalid UTF-8.
pub fn unit_of_measure(&self) -> Result<&str> {
c_chars_to_str(&self.unit_of_measure)
}
/// Returns the symbol of the first underlying instrument as a `&str`.
///
/// # Errors
/// This function returns an error if `underlying` contains invalid UTF-8.
pub fn underlying(&self) -> Result<&str> {
c_chars_to_str(&self.underlying)
}
/// Returns the currency of [`strike_price`](Self::strike_price) as a `&str`.
///
/// # Errors
/// This function returns an error if `strike_price_currency` contains invalid UTF-8.
pub fn strike_price_currency(&self) -> Result<&str> {
c_chars_to_str(&self.strike_price_currency)
}
/// Returns the security group code of the instrumnet as a `&str`.
///
/// # Errors
/// This function returns an error if `group` contains invalid UTF-8.
pub fn group(&self) -> Result<&str> {
c_chars_to_str(&self.group)
}
/// Tries to convert the raw classification of the instrument to an enum.
///
/// # Errors
/// This function returns an error if the `instrument_class` field does not
/// contain a valid [`InstrumentClass`].
pub fn instrument_class(&self) -> Result<InstrumentClass> {
InstrumentClass::try_from(self.instrument_class as u8).map_err(|_| {
Error::conversion::<InstrumentClass>(format!("{:#04X}", self.instrument_class as u8))
})
}
/// Tries to convert the raw matching algorithm used for the instrument to an enum.
///
/// # Errors
/// This function returns an error if the `match_algorithm` field does not
/// contain a valid [`MatchAlgorithm`].
pub fn match_algorithm(&self) -> Result<MatchAlgorithm> {
MatchAlgorithm::try_from(self.match_algorithm as u8).map_err(|_| {
Error::conversion::<MatchAlgorithm>(format!("{:#04X}", self.match_algorithm as u8))
})
}
/// Returns the action indicating whether the instrument definition has been added,
/// modified, or deleted.
///
/// # Errors
/// This function returns an error if the `security_update_action` field does not
/// contain a valid [`SecurityUpdateAction`].
pub fn security_update_action(&self) -> Result<SecurityUpdateAction> {
SecurityUpdateAction::try_from(self.security_update_action as u8).map_err(|_| {
Error::conversion::<SecurityUpdateAction>(format!(
"{:#04X}",
self.security_update_action as u8
))
})
}
}
impl InstrumentDefMsgV1 {
/// Parses the raw capture-server-received timestamp into a datetime. Returns `None`
/// if `ts_recv` contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
/// Parses the raw last eligible trade time into a datetime. Returns `None` if
/// `expiration` contains the sentinel for a null timestamp.
pub fn expiration(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.expiration)
}
/// Parses the raw time of instrument action into a datetime. Returns `None` if
/// `activation` contains the sentinel for a null timestamp.
pub fn activation(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.activation)
}
/// Returns currency used for price fields as a `&str`.
///
/// # Errors
/// This function returns an error if `currency` contains invalid UTF-8.
pub fn currency(&self) -> Result<&str> {
c_chars_to_str(&self.currency)
}
/// Returns currency used for settlement as a `&str`.
///
/// # Errors
/// This function returns an error if `settl_currency` contains invalid UTF-8.
pub fn settl_currency(&self) -> Result<&str> {
c_chars_to_str(&self.settl_currency)
}
/// Returns the strategy type of the spread as a `&str`.
///
/// # Errors
/// This function returns an error if `secsubtype` contains invalid UTF-8.
pub fn secsubtype(&self) -> Result<&str> {
c_chars_to_str(&self.secsubtype)
}
/// Returns the instrument raw symbol assigned by the publisher as a `&str`.
///
/// # Errors
/// This function returns an error if `raw_symbol` contains invalid UTF-8.
pub fn raw_symbol(&self) -> Result<&str> {
c_chars_to_str(&self.raw_symbol)
}
/// Returns exchange used to identify the instrument as a `&str`.
///
/// # Errors
/// This function returns an error if `exchange` contains invalid UTF-8.
pub fn exchange(&self) -> Result<&str> {
c_chars_to_str(&self.exchange)
}
/// Returns the underlying asset code (product code) of the instrument as a `&str`.
///
/// # Errors
/// This function returns an error if `asset` contains invalid UTF-8.
pub fn asset(&self) -> Result<&str> {
c_chars_to_str(&self.asset)
}
/// Returns the ISO standard instrument categorization code as a `&str`.
///
/// # Errors
/// This function returns an error if `cfi` contains invalid UTF-8.
pub fn cfi(&self) -> Result<&str> {
c_chars_to_str(&self.cfi)
}
/// Returns the type of the strument, e.g. FUT for future or future spread as
/// a `&str`.
///
/// # Errors
/// This function returns an error if `security_type` contains invalid UTF-8.
pub fn security_type(&self) -> Result<&str> {
c_chars_to_str(&self.security_type)
}
/// Returns the unit of measure for the instrument's original contract size, e.g.
/// USD or LBS, as a `&str`.
///
/// # Errors
/// This function returns an error if `unit_of_measure` contains invalid UTF-8.
pub fn unit_of_measure(&self) -> Result<&str> {
c_chars_to_str(&self.unit_of_measure)
}
/// Returns the symbol of the first underlying instrument as a `&str`.
///
/// # Errors
/// This function returns an error if `underlying` contains invalid UTF-8.
pub fn underlying(&self) -> Result<&str> {
c_chars_to_str(&self.underlying)
}
/// Returns the currency of [`strike_price`](Self::strike_price) as a `&str`.
///
/// # Errors
/// This function returns an error if `strike_price_currency` contains invalid UTF-8.
pub fn strike_price_currency(&self) -> Result<&str> {
c_chars_to_str(&self.strike_price_currency)
}
/// Returns the security group code of the instrumnet as a `&str`.
///
/// # Errors
/// This function returns an error if `group` contains invalid UTF-8.
pub fn group(&self) -> Result<&str> {
c_chars_to_str(&self.group)
}
/// Tries to convert the raw classification of the instrument to an enum.
///
/// # Errors
/// This function returns an error if the `instrument_class` field does not
/// contain a valid [`InstrumentClass`].
pub fn instrument_class(&self) -> Result<InstrumentClass> {
InstrumentClass::try_from(self.instrument_class as u8).map_err(|_| {
Error::conversion::<InstrumentClass>(format!("{:#04X}", self.instrument_class as u8))
})
}
/// Tries to convert the raw matching algorithm used for the instrument to an enum.
///
/// # Errors
/// This function returns an error if the `match_algorithm` field does not
/// contain a valid [`MatchAlgorithm`].
pub fn match_algorithm(&self) -> Result<MatchAlgorithm> {
MatchAlgorithm::try_from(self.match_algorithm as u8).map_err(|_| {
Error::conversion::<MatchAlgorithm>(format!("{:#04X}", self.match_algorithm as u8))
})
}
}
impl ImbalanceMsg {
/// Parses the raw capture-server-received timestamp into a datetime. Returns `None`
/// if `ts_recv` contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
}
impl StatMsg {
/// Parses the raw capture-server-received timestamp into a datetime. Returns `None`
/// if `ts_recv` contains the sentinel for a null timestamp.
pub fn ts_recv(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_recv)
}
/// Parses the raw reference timestamp of the statistic value into a datetime.
/// Returns `None` if `ts_ref` contains the sentinel for a null timestamp.
pub fn ts_ref(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.ts_ref)
}
/// Tries to convert the raw type of the statistic value to an enum.
///
/// # Errors
/// This function returns an error if the `stat_type` field does not
/// contain a valid [`StatType`].
pub fn stat_type(&self) -> Result<StatType> {
StatType::try_from(self.stat_type)
.map_err(|_| Error::conversion::<StatType>(self.stat_type))
}
/// Tries to convert the raw `update_action` to an enum.
///
/// # Errors
/// This function returns an error if the `update_action` field does not
/// contain a valid [`StatUpdateAction`].
pub fn update_action(&self) -> Result<StatUpdateAction> {
StatUpdateAction::try_from(self.update_action).map_err(|_| {
Error::conversion::<StatUpdateAction>(format!("{:04X}", self.update_action))
})
}
/// Parses the raw `ts_in_delta`—the delta of `ts_recv - ts_exchange_send`—into a duration.
pub fn ts_in_delta(&self) -> time::Duration {
time::Duration::new(0, self.ts_in_delta)
}
}
impl ErrorMsgV1 {
/// Creates a new `ErrorMsgV1`.
///
/// # Errors
/// This function returns an error if `msg` is too long.
pub fn new(ts_event: u64, msg: &str) -> Self {
let mut error = Self {
hd: RecordHeader::new::<Self>(rtype::ERROR, 0, 0, ts_event),
..Default::default()
};
// leave at least one null byte
for (i, byte) in msg.as_bytes().iter().take(error.err.len() - 1).enumerate() {
error.err[i] = *byte as c_char;
}
error
}
/// Returns `err` as a `&str`.
///
/// # Errors
/// This function returns an error if `err` contains invalid UTF-8.
pub fn err(&self) -> Result<&str> {
c_chars_to_str(&self.err)
}
}
impl ErrorMsg {
/// Creates a new `ErrorMsg`.
///
/// # Errors
/// This function returns an error if `msg` is too long.
pub fn new(ts_event: u64, msg: &str, is_last: bool) -> Self {
let mut error = Self {
hd: RecordHeader::new::<Self>(rtype::ERROR, 0, 0, ts_event),
is_last: is_last as u8,
..Default::default()
};
// leave at least one null byte
for (i, byte) in msg.as_bytes().iter().take(error.err.len() - 1).enumerate() {
error.err[i] = *byte as c_char;
}
error
}
/// Returns `err` as a `&str`.
///
/// # Errors
/// This function returns an error if `err` contains invalid UTF-8.
pub fn err(&self) -> Result<&str> {
c_chars_to_str(&self.err)
}
}
impl SymbolMappingMsg {
/// Creates a new `SymbolMappingMsgV2`.
///
/// # Errors
/// This function returns an error if `stype_in_symbol` or `stype_out_symbol`
/// contain more than maximum number of characters of 70.
#[allow(clippy::too_many_arguments)]
pub fn new(
instrument_id: u32,
ts_event: u64,
stype_in: SType,
stype_in_symbol: &str,
stype_out: SType,
stype_out_symbol: &str,
start_ts: u64,
end_ts: u64,
) -> crate::Result<Self> {
Ok(Self {
// symbol mappings aren't publisher-specific
hd: RecordHeader::new::<Self>(rtype::SYMBOL_MAPPING, 0, instrument_id, ts_event),
stype_in: stype_in as u8,
stype_in_symbol: str_to_c_chars(stype_in_symbol)?,
stype_out: stype_out as u8,
stype_out_symbol: str_to_c_chars(stype_out_symbol)?,
start_ts,
end_ts,
})
}
/// Returns the input symbology type.
///
/// # Errors
/// This function returns an error if `stype_in` does not contain a valid [`SType`].
pub fn stype_in(&self) -> Result<SType> {
SType::try_from(self.stype_in).map_err(|_| Error::conversion::<SType>(self.stype_in))
}
/// Returns the input symbol as a `&str`.
///
/// # Errors
/// This function returns an error if `stype_in_symbol` contains invalid UTF-8.
pub fn stype_in_symbol(&self) -> Result<&str> {
c_chars_to_str(&self.stype_in_symbol)
}
/// Returns the output symbology type.
///
/// # Errors
/// This function returns an error if `stype_out` does not contain a valid [`SType`].
pub fn stype_out(&self) -> Result<SType> {
SType::try_from(self.stype_out).map_err(|_| Error::conversion::<SType>(self.stype_out))
}
/// Returns the output symbol as a `&str`.
///
/// # Errors
/// This function returns an error if `stype_out_symbol` contains invalid UTF-8.
pub fn stype_out_symbol(&self) -> Result<&str> {
c_chars_to_str(&self.stype_out_symbol)
}
/// Parses the raw start of the mapping interval into a datetime. Returns `None` if
/// `start_ts` contains the sentinel for a null timestamp.
pub fn start_ts(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.start_ts)
}
/// Parses the raw end of the mapping interval into a datetime. Returns `None` if
/// `end_ts` contains the sentinel for a null timestamp.
pub fn end_ts(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.end_ts)
}
}
impl SymbolMappingMsgV1 {
/// Creates a new `SymbolMappingMsg`.
///
/// # Errors
/// This function returns an error if `stype_in_symbol` or `stype_out_symbol`
/// contain more than maximum number of characters of 21.
pub fn new(
instrument_id: u32,
ts_event: u64,
stype_in_symbol: &str,
stype_out_symbol: &str,
start_ts: u64,
end_ts: u64,
) -> crate::Result<Self> {
Ok(Self {
// symbol mappings aren't publisher-specific
hd: RecordHeader::new::<Self>(rtype::SYMBOL_MAPPING, 0, instrument_id, ts_event),
stype_in_symbol: str_to_c_chars(stype_in_symbol)?,
stype_out_symbol: str_to_c_chars(stype_out_symbol)?,
_dummy: Default::default(),
start_ts,
end_ts,
})
}
/// Returns the input symbol as a `&str`.
///
/// # Errors
/// This function returns an error if `stype_in_symbol` contains invalid UTF-8.
pub fn stype_in_symbol(&self) -> Result<&str> {
c_chars_to_str(&self.stype_in_symbol)
}
/// Returns the output symbol as a `&str`.
///
/// # Errors
/// This function returns an error if `stype_out_symbol` contains invalid UTF-8.
pub fn stype_out_symbol(&self) -> Result<&str> {
c_chars_to_str(&self.stype_out_symbol)
}
/// Parses the raw start of the mapping interval into a datetime. Returns `None` if
/// `start_ts` contains the sentinel for a null timestamp.
pub fn start_ts(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.start_ts)
}
/// Parses the raw end of the mapping interval into a datetime. Returns `None` if
/// `end_ts` contains the sentinel for a null timestamp.
pub fn end_ts(&self) -> Option<time::OffsetDateTime> {
ts_to_dt(self.end_ts)
}
}
impl SystemMsg {
const HEARTBEAT: &'static str = "Heartbeat";
/// Creates a new `SystemMsg`.
///
/// # Errors
/// This function returns an error if `msg` is too long.
pub fn new(ts_event: u64, msg: &str) -> Result<Self> {
Ok(Self {
hd: RecordHeader::new::<Self>(rtype::SYSTEM, 0, 0, ts_event),
msg: str_to_c_chars(msg)?,
..Default::default()
})
}
/// Creates a new heartbeat `SystemMsg`.
pub fn heartbeat(ts_event: u64) -> Self {
Self {
hd: RecordHeader::new::<Self>(rtype::SYSTEM, 0, 0, ts_event),
msg: str_to_c_chars(Self::HEARTBEAT).unwrap(),
code: u8::MAX,
}
}
/// Checks whether the message is a heartbeat from the gateway.
pub fn is_heartbeat(&self) -> bool {
self.msg()
.map(|msg| msg == Self::HEARTBEAT)
.unwrap_or_default()
}
/// Returns the message from the Databento Live Subscription Gateway (LSG) as
/// a `&str`.
///
/// # Errors
/// This function returns an error if `msg` contains invalid UTF-8.
pub fn msg(&self) -> Result<&str> {
c_chars_to_str(&self.msg)
}
}
impl SystemMsgV1 {
/// Creates a new `SystemMsgV1`.
///
/// # Errors
/// This function returns an error if `msg` is too long.
pub fn new(ts_event: u64, msg: &str) -> Result<Self> {
Ok(Self {
hd: RecordHeader::new::<Self>(rtype::SYSTEM, 0, 0, ts_event),
msg: str_to_c_chars(msg)?,
})
}
/// Creates a new heartbeat `SystemMsg`.
pub fn heartbeat(ts_event: u64) -> Self {
Self {
hd: RecordHeader::new::<Self>(rtype::SYSTEM, 0, 0, ts_event),
msg: str_to_c_chars(SystemMsg::HEARTBEAT).unwrap(),
}
}
/// Checks whether the message is a heartbeat from the gateway.
pub fn is_heartbeat(&self) -> bool {
self.msg()
.map(|msg| msg == SystemMsg::HEARTBEAT)
.unwrap_or_default()
}
/// Returns the message from the Databento Live Subscription Gateway (LSG) as
/// a `&str`.
///
/// # Errors
/// This function returns an error if `msg` contains invalid UTF-8.
pub fn msg(&self) -> Result<&str> {
c_chars_to_str(&self.msg)
}
}
impl<T: HasRType> Record for WithTsOut<T> {
fn header(&self) -> &RecordHeader {
self.rec.header()
}
fn raw_index_ts(&self) -> u64 {
self.rec.raw_index_ts()
}
}
impl<T: HasRType> RecordMut for WithTsOut<T> {
fn header_mut(&mut self) -> &mut RecordHeader {
self.rec.header_mut()
}
}
impl<T: HasRType> HasRType for WithTsOut<T> {
fn has_rtype(rtype: u8) -> bool {
T::has_rtype(rtype)
}
}
impl<T> AsRef<[u8]> for WithTsOut<T>
where
T: HasRType + AsRef<[u8]>,
{
fn as_ref(&self) -> &[u8] {
unsafe { as_u8_slice(self) }
}
}
impl<T: HasRType> WithTsOut<T> {
/// Creates a new record with `ts_out`. Updates the `length` property in
/// [`RecordHeader`] to ensure the additional field is accounted for.
pub fn new(rec: T, ts_out: u64) -> Self {
let mut res = Self { rec, ts_out };
res.header_mut().length = (mem::size_of_val(&res) / RecordHeader::LENGTH_MULTIPLIER) as u8;
res
}
/// Parses the raw live gateway send timestamp into a datetime.
pub fn ts_out(&self) -> time::OffsetDateTime {
// u64::MAX is within maximum allowable range
time::OffsetDateTime::from_unix_timestamp_nanos(self.ts_out as i128).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_rtype_error() {
let header = RecordHeader::new::<MboMsg>(0xE, 1, 2, 3);
assert_eq!(
header.rtype().unwrap_err().to_string(),
"couldn't convert 0x0E to dbn::enums::rtype::RType"
);
}
#[test]
fn debug_mbo() {
let rec = MboMsg {
hd: RecordHeader::new::<MboMsg>(
rtype::MBO,
Publisher::OpraPillarXcbo as u16,
678,
1704468548242628731,
),
flags: FlagSet::empty().set_last().set_bad_ts_recv(),
price: 4_500_500_000_000,
side: b'B' as c_char,
action: b'A' as c_char,
..Default::default()
};
assert_eq!(
format!("{rec:?}"),
"MboMsg { hd: RecordHeader { length: 14, rtype: Mbo, publisher_id: OpraPillarXcbo, \
instrument_id: 678, ts_event: 1704468548242628731 }, order_id: 0, \
price: 4500.500000000, size: 4294967295, flags: LAST | BAD_TS_RECV (136), channel_id: 0, \
action: 'A', side: 'B', ts_recv: 18446744073709551615, ts_in_delta: 0, sequence: 0 }"
);
}
#[test]
fn debug_stats() {
let rec = StatMsg {
stat_type: StatType::OpenInterest as u16,
update_action: StatUpdateAction::New as u8,
quantity: 5,
stat_flags: 0b00000010,
..Default::default()
};
assert_eq!(
format!("{rec:?}"),
"StatMsg { hd: RecordHeader { length: 16, rtype: Statistics, publisher_id: 0, \
instrument_id: 0, ts_event: 18446744073709551615 }, ts_recv: 18446744073709551615, \
ts_ref: 18446744073709551615, price: UNDEF_PRICE, quantity: 5, sequence: 0, ts_in_delta: 0, \
stat_type: OpenInterest, channel_id: 0, update_action: New, stat_flags: 0b00000010 }"
);
}
#[test]
fn debug_instrument_err() {
let rec = ErrorMsg {
err: str_to_c_chars("Missing stype_in").unwrap(),
..Default::default()
};
assert_eq!(
format!("{rec:?}"),
"ErrorMsg { hd: RecordHeader { length: 80, rtype: Error, publisher_id: 0, \
instrument_id: 0, ts_event: 18446744073709551615 }, err: \"Missing stype_in\", code: 255, is_last: 255 }"
);
}
#[test]
fn debug_instrument_sys() {
let rec = SystemMsg::heartbeat(123);
assert_eq!(
format!("{rec:?}"),
"SystemMsg { hd: RecordHeader { length: 80, rtype: System, publisher_id: 0, \
instrument_id: 0, ts_event: 123 }, msg: \"Heartbeat\", code: 255 }"
);
}
#[test]
fn debug_instrument_symbol_mapping() {
let rec = SymbolMappingMsg {
hd: RecordHeader::new::<SymbolMappingMsg>(
rtype::SYMBOL_MAPPING,
0,
5602,
1704466940331347283,
),
stype_in: SType::RawSymbol as u8,
stype_in_symbol: str_to_c_chars("ESM4").unwrap(),
stype_out: SType::RawSymbol as u8,
stype_out_symbol: str_to_c_chars("ESM4").unwrap(),
..Default::default()
};
assert_eq!(
format!("{rec:?}"),
"SymbolMappingMsg { hd: RecordHeader { length: 44, rtype: SymbolMapping, publisher_id: 0, instrument_id: 5602, ts_event: 1704466940331347283 }, stype_in: RawSymbol, stype_in_symbol: \"ESM4\", stype_out: RawSymbol, stype_out_symbol: \"ESM4\", start_ts: 18446744073709551615, end_ts: 18446744073709551615 }"
);
}
}