Skip to main content

nautilus_databento/
symbology.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::borrow::Cow;
17
18use ahash::{AHashMap, AHashSet};
19use databento::dbn::{self, PitSymbolMap, SType};
20use dbn::{Publisher, Record};
21use indexmap::IndexMap;
22use nautilus_model::identifiers::{
23    InstrumentId, Symbol, Venue,
24    futures::{
25        FuturesYearDigits, format_futures_symbol, parse_futures_symbol, resolve_futures_year,
26        resolve_futures_year_from_expiry,
27    },
28};
29
30use super::types::PublisherId;
31
32#[derive(Debug)]
33pub struct MetadataCache {
34    metadata: dbn::Metadata,
35    date_metadata_map: AHashMap<time::Date, PitSymbolMap>,
36}
37
38impl MetadataCache {
39    #[must_use]
40    pub fn new(metadata: dbn::Metadata) -> Self {
41        Self {
42            metadata,
43            date_metadata_map: AHashMap::new(),
44        }
45    }
46
47    /// # Errors
48    ///
49    /// Returns an error if metadata for the given `date` cannot be retrieved.
50    pub fn symbol_map_for_date(&mut self, date: time::Date) -> dbn::Result<&PitSymbolMap> {
51        if !self.date_metadata_map.contains_key(&date) {
52            let map = self.metadata.symbol_map_for_date(date)?;
53            self.date_metadata_map.insert(date, map);
54        }
55
56        self.date_metadata_map
57            .get(&date)
58            .ok_or_else(|| dbn::Error::decode(format!("metadata cache missing for date {date}")))
59    }
60}
61
62pub fn instrument_id_to_symbol_string(
63    instrument_id: InstrumentId,
64    symbol_venue_map: &mut AHashMap<Symbol, Venue>,
65) -> String {
66    symbol_venue_map
67        .entry(instrument_id.symbol)
68        .or_insert(instrument_id.venue);
69    instrument_id.symbol.to_string()
70}
71
72/// Decodes a Databento record into a Nautilus `InstrumentId`.
73///
74/// `Some` restricts year hints to the request set; an empty set disables hints.
75/// `None` uses hints from shared venue mappings.
76///
77/// # Errors
78///
79/// Returns an error if:
80/// - The publisher cannot be extracted from the record.
81/// - The publisher ID is not found in the venue map.
82/// - The underlying instrument ID mapping fails.
83#[expect(clippy::too_many_arguments)]
84pub fn decode_nautilus_instrument_id(
85    record: &dbn::RecordRef,
86    metadata: &mut MetadataCache,
87    publisher_venue_map: &IndexMap<PublisherId, Venue>,
88    symbol_venue_map: &AHashMap<Symbol, Venue>,
89    futures_year_digits: FuturesYearDigits,
90    share_class_space: bool,
91    futures_symbols: &AHashMap<(PublisherId, u32, time::Date), Symbol>,
92    requested_symbols: Option<&AHashSet<Symbol>>,
93) -> anyhow::Result<InstrumentId> {
94    let publisher = record
95        .publisher()
96        .map_err(|e| anyhow::anyhow!("Invalid `publisher` for record: {e}"))?;
97    let publisher_id = publisher as PublisherId;
98    let venue = publisher_venue_map
99        .get(&publisher_id)
100        .ok_or_else(|| anyhow::anyhow!("`Venue` not found for `publisher_id` {publisher_id}"))?;
101    let mut instrument_id = get_nautilus_instrument_id_for_record(
102        record,
103        metadata,
104        *venue,
105        futures_year_digits,
106        share_class_space,
107        futures_symbols,
108        symbol_venue_map,
109        requested_symbols,
110    )?;
111
112    if publisher == Publisher::GlbxMdp3Glbx
113        && let Some(venue) = symbol_venue_map.get(&instrument_id.symbol)
114    {
115        instrument_id.venue = *venue;
116    }
117
118    Ok(instrument_id)
119}
120
121/// Gets the Nautilus `InstrumentId` for a Databento record.
122///
123/// Cached definitions apply only to the record's publisher, numeric ID, and date.
124/// Databento can reuse numeric IDs on later dates.
125/// Requested symbols distinguish contracts that trade after their contract-month year.
126/// `Some` restricts year hints to the request set; an empty set disables hints.
127/// `None` uses hints from shared venue mappings.
128///
129/// # Errors
130///
131/// Returns an error if:
132/// - The record type is not supported.
133/// - Timestamp overflow occurs when calculating the date.
134/// - Symbol metadata lookup fails.
135/// - No raw symbol is found for the instrument ID.
136#[expect(clippy::too_many_arguments)]
137pub fn get_nautilus_instrument_id_for_record(
138    record: &dbn::RecordRef,
139    metadata: &mut MetadataCache,
140    venue: Venue,
141    futures_year_digits: FuturesYearDigits,
142    share_class_space: bool,
143    futures_symbols: &AHashMap<(PublisherId, u32, time::Date), Symbol>,
144    symbol_venue_map: &AHashMap<Symbol, Venue>,
145    requested_symbols: Option<&AHashSet<Symbol>>,
146) -> anyhow::Result<InstrumentId> {
147    if record.get::<dbn::MboMsg>().is_none()
148        && record.get::<dbn::TradeMsg>().is_none()
149        && record.get::<dbn::Mbp1Msg>().is_none()
150        && record.get::<dbn::Bbo1SMsg>().is_none()
151        && record.get::<dbn::Bbo1MMsg>().is_none()
152        && record.get::<dbn::Mbp10Msg>().is_none()
153        && record.get::<dbn::OhlcvMsg>().is_none()
154        && record.get::<dbn::StatusMsg>().is_none()
155        && record.get::<dbn::ImbalanceMsg>().is_none()
156        && record.get::<dbn::StatMsg>().is_none()
157        && record.get::<dbn::InstrumentDefMsg>().is_none()
158        && record.get::<dbn::Cmbp1Msg>().is_none()
159        && record.get::<dbn::CbboMsg>().is_none()
160    {
161        anyhow::bail!("DBN message type is not currently supported");
162    }
163
164    let instrument_id = record.header().instrument_id;
165    let nanoseconds = record.raw_index_ts();
166    let duration = time::Duration::nanoseconds(nanoseconds as i64);
167    let datetime = time::OffsetDateTime::UNIX_EPOCH
168        .checked_add(duration)
169        .ok_or_else(|| anyhow::anyhow!("Timestamp overflow for record"))?;
170    let date = datetime.date();
171    let symbol_map = metadata.symbol_map_for_date(date)?;
172    let raw_symbol = symbol_map
173        .get(instrument_id)
174        .ok_or_else(|| anyhow::anyhow!("No raw symbol found for {instrument_id}"))?;
175
176    if futures_year_digits == FuturesYearDigits::Two
177        && record.get::<dbn::InstrumentDefMsg>().is_none()
178        && let Some(symbol) =
179            futures_symbols.get(&(record.header().publisher_id, instrument_id, date))
180    {
181        return Ok(InstrumentId::new(*symbol, venue));
182    }
183
184    let symbol = nautilus_symbol(raw_symbol, share_class_space);
185    let instrument_id = InstrumentId::new(symbol, venue);
186    resolve_futures_instrument_id(
187        record,
188        instrument_id,
189        futures_year_digits,
190        symbol_venue_map,
191        requested_symbols,
192    )
193}
194
195#[must_use]
196pub fn infer_symbology_type(symbol: &str) -> SType {
197    if symbol.ends_with(".FUT") || symbol.ends_with(".OPT") {
198        return SType::Parent;
199    }
200
201    // Three dot-separated parts with an all-digit rank (`ES.c.0`), without a part vector
202    if let Some(rank) = continuous_rank(symbol)
203        && rank.chars().all(|c| c.is_ascii_digit())
204    {
205        return SType::Continuous;
206    }
207
208    if symbol.chars().all(|c| c.is_ascii_digit()) {
209        return SType::InstrumentId;
210    }
211
212    SType::RawSymbol
213}
214
215/// Returns the third `.`-separated part when `symbol` has exactly three parts.
216fn continuous_rank(symbol: &str) -> Option<&str> {
217    let mut parts = symbol.split('.');
218    if parts.next().is_none() || parts.next().is_none() {
219        return None;
220    }
221
222    let rank = parts.next()?;
223    parts.next().is_none().then_some(rank)
224}
225
226/// # Errors
227///
228/// Returns an error if `symbols` is empty or symbols have inconsistent symbology types.
229pub fn check_consistent_symbology(symbols: &[&str]) -> anyhow::Result<()> {
230    if symbols.is_empty() {
231        anyhow::bail!("No symbols provided");
232    }
233    let first_symbol = symbols[0];
234    let first_stype = infer_symbology_type(first_symbol);
235
236    for symbol in symbols {
237        let next_stype = infer_symbology_type(symbol);
238        if next_stype != first_stype {
239            anyhow::bail!(
240                "Inconsistent symbology types: '{first_stype}' for {first_symbol} vs '{next_stype}' for {symbol}"
241            );
242        }
243    }
244
245    Ok(())
246}
247
248pub(crate) fn dataset_uses_futures_symbology(dataset: &str) -> bool {
249    matches!(
250        dataset,
251        "GLBX.MDP3"
252            | "IFEU.IMPACT"
253            | "NDEX.IMPACT"
254            | "IFUS.IMPACT"
255            | "IFLL.IMPACT"
256            | "XEUR.EOBI"
257            | "XEEE.EOBI"
258            | "XCBF.PITCH"
259            | "XOSE.ITCH"
260    )
261}
262
263/// Converts a Databento symbol to a Nautilus symbol.
264///
265/// With `share_class_space`, a share class's dot becomes a space (`BRK.B` -> `BRK B`), since a
266/// dot separates symbol and venue in instrument IDs and Interactive Brokers spells the class with
267/// a space. Parent (`ES.FUT`) and continuous (`ES.c.0`) symbols keep their dots.
268#[must_use]
269pub fn nautilus_symbol(raw_symbol: &str, share_class_space: bool) -> Symbol {
270    Symbol::from_str_unchecked(nautilus_symbol_str(raw_symbol, share_class_space))
271}
272
273/// Borrows `raw_symbol` when its spelling does not change.
274///
275/// A dotted letter-only share class is recognized before symbology inference, so ordinary
276/// symbols such as `AAPL` return without allocating on the historical and DBN record path.
277fn nautilus_symbol_str<'a>(raw_symbol: &'a str, share_class_space: bool) -> Cow<'a, str> {
278    if !share_class_space || !is_share_class_symbol(raw_symbol, '.') {
279        return Cow::Borrowed(raw_symbol);
280    }
281
282    // Parent symbols (`ES.FUT`, `SPX.OPT`) are dotted and letter-only, but keep their dots
283    if infer_symbology_type(raw_symbol) != SType::RawSymbol {
284        return Cow::Borrowed(raw_symbol);
285    }
286
287    Cow::Owned(raw_symbol.replace('.', " "))
288}
289
290/// Returns whether `symbol` is a share class: uppercase-letter parts joined by single
291/// `separator`s, such as `BRK.B` or `BRK B`.
292///
293/// Option and futures symbols such as `BRKB  261120C00525000` or `ESZ6 P5000` don't qualify.
294fn is_share_class_symbol(symbol: &str, separator: char) -> bool {
295    symbol.contains(separator)
296        && symbol
297            .split(separator)
298            .all(|part| !part.is_empty() && part.bytes().all(|c| c.is_ascii_uppercase()))
299}
300
301pub(crate) fn raw_symbol(
302    symbol: &str,
303    dataset: &str,
304    futures_year_digits: FuturesYearDigits,
305    share_class_space: bool,
306) -> String {
307    if share_class_space && is_share_class_symbol(symbol, ' ') {
308        symbol.replace(' ', ".")
309    } else if futures_year_digits == FuturesYearDigits::Two
310        && dataset_uses_futures_symbology(dataset)
311    {
312        rewrite_futures_symbol(symbol, 0, 1, false).unwrap_or_else(|| symbol.to_string())
313    } else {
314        symbol.to_string()
315    }
316}
317
318fn rewrite_futures_symbol(
319    symbol: &str,
320    reference_year: i32,
321    year_digits: u8,
322    from_definition: bool,
323) -> Option<String> {
324    let (code, suffix) = symbol
325        .split_once(' ')
326        .map_or((symbol, ""), |(code, suffix)| (code, suffix));
327
328    let legs = code
329        .split('-')
330        .map(|leg| {
331            let parsed = parse_futures_symbol(leg)?;
332            let year = if year_digits == 1 {
333                parsed.year_digits.parse::<i32>().ok()?
334            } else if from_definition {
335                resolve_futures_year_from_expiry(parsed.year_digits, reference_year)?
336            } else {
337                resolve_futures_year(parsed.year_digits, reference_year)?
338            };
339
340            format_futures_symbol(parsed.root, parsed.month_code, year, year_digits)
341        })
342        .collect::<Option<Vec<_>>>()?;
343
344    let code = legs.join("-");
345    Some(if suffix.is_empty() {
346        code
347    } else {
348        format!("{code} {suffix}")
349    })
350}
351
352pub(crate) fn resolve_futures_instrument_id(
353    record: &dbn::RecordRef,
354    instrument_id: InstrumentId,
355    futures_year_digits: FuturesYearDigits,
356    symbol_venue_map: &AHashMap<Symbol, Venue>,
357    requested_symbols: Option<&AHashSet<Symbol>>,
358) -> anyhow::Result<InstrumentId> {
359    if futures_year_digits != FuturesYearDigits::Two
360        || !record
361            .publisher()
362            .is_ok_and(|publisher| dataset_uses_futures_symbology(publisher.dataset().as_str()))
363    {
364        return Ok(instrument_id);
365    }
366
367    let mut timestamp = record.raw_index_ts();
368    let definition = record.get::<dbn::InstrumentDefMsg>();
369    let maturity_year = definition
370        .filter(|msg| msg.instrument_class as u8 != b'S')
371        .map(|msg| msg.maturity_year)
372        .filter(|year| !matches!(*year, 0 | u16::MAX))
373        .map(i32::from);
374
375    if let Some(msg) = definition {
376        if !matches!(msg.instrument_class as u8 as char, 'F' | 'S' | 'C' | 'P') {
377            return Ok(instrument_id);
378        }
379
380        if msg.expiration == dbn::UNDEF_TIMESTAMP && maturity_year.is_none() {
381            log::warn!(
382                "Keeping raw futures symbol for {instrument_id}: definition has no expiration"
383            );
384            return Ok(instrument_id);
385        }
386
387        timestamp = msg.expiration;
388    }
389
390    let reference_year = if let Some(year) = maturity_year {
391        year
392    } else {
393        time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(timestamp))
394            .map_err(|e| anyhow::anyhow!("Invalid futures reference timestamp {timestamp}: {e}"))?
395            .year()
396    };
397
398    let mut symbol = rewrite_futures_symbol(
399        instrument_id.symbol.as_str(),
400        reference_year,
401        2,
402        definition.is_some(),
403    );
404
405    if definition.is_none() {
406        symbol = select_requested_futures_symbol(
407            symbol,
408            instrument_id.symbol.as_str(),
409            reference_year,
410            symbol_venue_map,
411            requested_symbols,
412        );
413    }
414
415    Ok(symbol.map_or(instrument_id, |symbol| {
416        InstrumentId::new(Symbol::from(symbol.as_str()), instrument_id.venue)
417    }))
418}
419
420fn select_requested_futures_symbol(
421    inferred: Option<String>,
422    native: &str,
423    reference_year: i32,
424    symbol_venue_map: &AHashMap<Symbol, Venue>,
425    requested_symbols: Option<&AHashSet<Symbol>>,
426) -> Option<String> {
427    let hints_empty =
428        requested_symbols.map_or_else(|| symbol_venue_map.is_empty(), |symbols| symbols.is_empty());
429
430    let contains = |symbol: &str| {
431        let symbol = Symbol::from(symbol);
432        requested_symbols.map_or_else(
433            || symbol_venue_map.contains_key(&symbol),
434            |symbols| symbols.contains(&symbol),
435        )
436    };
437
438    if hints_empty || inferred.as_ref().is_none_or(|symbol| contains(symbol)) {
439        return inferred;
440    }
441
442    rewrite_futures_symbol(native, reference_year - 1, 2, false)
443        .filter(|symbol| contains(symbol))
444        .or(inferred)
445}
446
447#[cfg(test)]
448mod tests {
449    use std::borrow::Cow;
450
451    use rstest::*;
452
453    use super::*;
454
455    #[rstest]
456    #[case("1", "instrument_id")]
457    #[case("123456789", "instrument_id")]
458    #[case("", "instrument_id")]
459    #[case("AAPL", "raw_symbol")]
460    #[case("ESM4", "raw_symbol")]
461    #[case("BRN FMM0024!", "raw_symbol")]
462    #[case("BRN  99   5617289", "raw_symbol")]
463    #[case("SPY   240319P00511000", "raw_symbol")]
464    #[case("ES.c.0.1", "raw_symbol")]
465    #[case("ES.FUT", "parent")]
466    #[case("ES.OPT", "parent")]
467    #[case("BRN.FUT", "parent")]
468    #[case("SPX.OPT", "parent")]
469    #[case("ES.c.0", "continuous")]
470    #[case("SPX.n.0", "continuous")]
471    #[case("ES.c.", "continuous")]
472    #[case("..", "continuous")]
473    #[case("12.34.56", "continuous")]
474    fn test_infer_symbology_type(#[case] symbol: String, #[case] expected: SType) {
475        let result = infer_symbology_type(&symbol);
476        assert_eq!(result, expected);
477    }
478
479    #[rstest]
480    fn test_check_consistent_symbology_when_empty_symbols() {
481        let symbols: Vec<&str> = vec![];
482        assert!(check_consistent_symbology(&symbols).is_err());
483    }
484
485    #[rstest]
486    fn test_instrument_id_to_symbol_string_updates_map() {
487        let symbol = Symbol::from("TEST");
488        let venue = Venue::from("XNAS");
489        let instrument_id = InstrumentId::new(symbol, venue);
490        let mut map: AHashMap<Symbol, Venue> = AHashMap::new();
491
492        // First call should insert the mapping
493        let sym_str = instrument_id_to_symbol_string(instrument_id, &mut map);
494        assert_eq!(sym_str, "TEST");
495        assert_eq!(map.get(&Symbol::from("TEST")), Some(&Venue::from("XNAS")));
496
497        // Call again with same symbol but different venue should not override existing
498        let other = Venue::from("XLON");
499        let inst2 = InstrumentId::new(Symbol::from("TEST"), other);
500        let sym_str2 = instrument_id_to_symbol_string(inst2, &mut map);
501        assert_eq!(sym_str2, "TEST");
502
503        // Venue remains the original
504        assert_eq!(map.get(&Symbol::from("TEST")), Some(&Venue::from("XNAS")));
505    }
506
507    #[rstest]
508    fn test_check_consistent_symbology_when_inconsistent() {
509        let symbols = vec!["ESM4", "ES.OPT"];
510        let result = check_consistent_symbology(&symbols);
511        assert!(result.is_err());
512        assert_eq!(
513            result.err().unwrap().to_string(),
514            "Inconsistent symbology types: 'raw_symbol' for ESM4 vs 'parent' for ES.OPT"
515        );
516    }
517
518    #[rstest]
519    #[case(vec!["AAPL,MSFT"])]
520    #[case(vec!["ES.OPT,ES.FUT"])]
521    #[case(vec!["ES.c.0,ES.c.1"])]
522    fn test_check_consistent_symbology_when_consistent(#[case] symbols: Vec<&str>) {
523        let result = check_consistent_symbology(&symbols);
524        assert!(result.is_ok());
525    }
526
527    #[rstest]
528    #[case("BRK.B", true, "BRK B")]
529    #[case("BF.B", true, "BF B")]
530    #[case("BRK.B", false, "BRK.B")]
531    #[case("AAPL", true, "AAPL")]
532    #[case("SPY   240319P00511000", true, "SPY   240319P00511000")]
533    #[case("ES.FUT", true, "ES.FUT")]
534    #[case("SPX.OPT", true, "SPX.OPT")]
535    #[case("ES.c.0", true, "ES.c.0")]
536    #[case("ES.n.0", true, "ES.n.0")]
537    fn test_nautilus_symbol_spells_share_class_with_space(
538        #[case] raw: &str,
539        #[case] share_class_space: bool,
540        #[case] expected: &str,
541    ) {
542        assert_eq!(
543            nautilus_symbol(raw, share_class_space),
544            Symbol::from(expected)
545        );
546    }
547
548    #[rstest]
549    #[case("AAPL", true)]
550    #[case("AAPL", false)]
551    #[case("ESM4", true)]
552    #[case("123456", true)]
553    #[case("SPY   240319P00511000", true)]
554    #[case("ES.FUT", true)]
555    #[case("SPX.OPT", true)]
556    #[case("ES.c.0", true)]
557    #[case("ES.n.0", true)]
558    #[case("BRK.B", false)]
559    fn test_nautilus_symbol_borrows_when_unchanged(
560        #[case] raw: &str,
561        #[case] share_class_space: bool,
562    ) {
563        assert!(matches!(
564            nautilus_symbol_str(raw, share_class_space),
565            Cow::Borrowed(value) if value == raw
566        ));
567    }
568
569    #[rstest]
570    #[case("BRK.B", "BRK B")]
571    #[case("BF.B", "BF B")]
572    fn test_nautilus_symbol_owns_spelled_share_class(#[case] raw: &str, #[case] expected: &str) {
573        assert!(matches!(
574            nautilus_symbol_str(raw, true),
575            Cow::Owned(value) if value == expected
576        ));
577    }
578
579    #[rstest]
580    #[case("BRK B", "EQUS.MINI", true, "BRK.B")]
581    #[case("BRK B", "XNYS.PILLAR", true, "BRK.B")]
582    #[case("BRK B", "EQUS.MINI", false, "BRK B")]
583    #[case("AAPL", "EQUS.MINI", true, "AAPL")]
584    #[case("BRKB  261120C00525000", "OPRA.PILLAR", true, "BRKB  261120C00525000")]
585    #[case("ESZ6 P5000", "GLBX.MDP3", true, "ESZ6 P5000")]
586    #[case("BRN FMM0024!", "IFEU.IMPACT", true, "BRN FMM0024!")]
587    #[case("BRN  99   5617289", "IFEU.IMPACT", true, "BRN  99   5617289")]
588    fn test_raw_symbol_spells_share_class_with_dot(
589        #[case] symbol: &str,
590        #[case] dataset: &str,
591        #[case] share_class_space: bool,
592        #[case] expected: &str,
593    ) {
594        assert_eq!(
595            raw_symbol(symbol, dataset, FuturesYearDigits::One, share_class_space),
596            expected
597        );
598    }
599
600    #[rstest]
601    #[case("ESZ26", "GLBX.MDP3", 2, "ESZ6")]
602    #[case("ESZ95", "GLBX.MDP3", 2, "ESZ5")]
603    #[case("ESZ26 P5000", "GLBX.MDP3", 2, "ESZ6 P5000")]
604    #[case("ESU26-ESM27", "GLBX.MDP3", 2, "ESU6-ESM7")]
605    #[case("CLZ29-CLF30", "GLBX.MDP3", 2, "CLZ9-CLF0")]
606    #[case("ESZ26", "XNAS.ITCH", 2, "ESZ26")]
607    #[case("ESZ26", "GLBX.MDP3", 1, "ESZ26")]
608    #[case("ES.c.0", "GLBX.MDP3", 2, "ES.c.0")]
609    #[case("ES.FUT", "GLBX.MDP3", 2, "ES.FUT")]
610    #[case("BRN FMM0024!", "IFEU.IMPACT", 2, "BRN FMM0024!")]
611    fn test_raw_symbol_preserves_venue_format(
612        #[case] symbol: &str,
613        #[case] dataset: &str,
614        #[case] digits: u8,
615        #[case] expected: &str,
616    ) {
617        assert_eq!(
618            raw_symbol(symbol, dataset, digits.try_into().unwrap(), false),
619            expected
620        );
621    }
622
623    #[rstest]
624    #[case("ESZ6", "2026-12-18T00:00:00Z", "ESZ26.XCME")]
625    #[case("ESZ9", "2029-12-21T00:00:00Z", "ESZ29.XCME")]
626    #[case("ESH0", "2020-03-20T00:00:00Z", "ESH20.XCME")]
627    #[case("ESH0", "2030-03-15T00:00:00Z", "ESH30.XCME")]
628    #[case("CLF6", "2025-12-19T00:00:00Z", "CLF26.XCME")]
629    #[case("CLF0", "2029-12-19T00:00:00Z", "CLF30.XCME")]
630    #[case("SR3Z6", "2027-03-16T00:00:00Z", "SR3Z26.XCME")]
631    #[case("SR3Z9", "2030-03-19T00:00:00Z", "SR3Z29.XCME")]
632    #[case("SR3Z6-SR3H7", "2027-03-16T00:00:00Z", "SR3Z26-SR3H27.XCME")]
633    #[case("SR3Z6-SR3Z3", "2027-03-16T00:00:00Z", "SR3Z26-SR3Z33.XCME")]
634    #[case("CLZ9-CLF0", "2029-11-20T00:00:00Z", "CLZ29-CLF30.XCME")]
635    fn test_futures_definition_uses_contract_year(
636        #[case] symbol: &str,
637        #[case] expiry: &str,
638        #[case] expected: InstrumentId,
639    ) {
640        let expiration = expiry.parse::<jiff::Timestamp>().unwrap().as_nanosecond() as u64;
641
642        let msg = dbn::InstrumentDefMsg {
643            hd: dbn::RecordHeader::new::<dbn::InstrumentDefMsg>(
644                dbn::rtype::INSTRUMENT_DEF,
645                1,
646                42,
647                0,
648            ),
649            instrument_class: if symbol.contains('-') { b'S' } else { b'F' } as std::ffi::c_char,
650            expiration,
651            ..Default::default()
652        };
653
654        let id = InstrumentId::new(Symbol::from(symbol), Venue::from("XCME"));
655        let record = dbn::RecordRef::from(&msg);
656        assert_eq!(
657            resolve_futures_instrument_id(
658                &record,
659                id,
660                FuturesYearDigits::Two,
661                &AHashMap::new(),
662                None
663            )
664            .unwrap(),
665            expected
666        );
667        assert_eq!(
668            resolve_futures_instrument_id(
669                &record,
670                id,
671                FuturesYearDigits::One,
672                &AHashMap::new(),
673                None
674            )
675            .unwrap(),
676            id
677        );
678    }
679
680    #[rstest]
681    #[case(dbn::UNDEF_TIMESTAMP)]
682    #[case(1_000_000_000)]
683    fn test_bbo_year_uses_receive_timestamp(#[case] ts_event: u64) {
684        let ts_recv = "2029-12-20T00:00:00Z"
685            .parse::<jiff::Timestamp>()
686            .unwrap()
687            .as_nanosecond() as u64;
688        let mut msg = dbn::BboMsg::default_for_schema(dbn::Schema::Bbo1S);
689        msg.hd.publisher_id = 1;
690        msg.hd.instrument_id = 42;
691        msg.hd.ts_event = ts_event;
692        msg.ts_recv = ts_recv;
693        let id = InstrumentId::from("CLF0.XNYM");
694        assert_eq!(
695            resolve_futures_instrument_id(
696                &dbn::RecordRef::from(&msg),
697                id,
698                FuturesYearDigits::Two,
699                &AHashMap::new(),
700                None
701            )
702            .unwrap(),
703            InstrumentId::from("CLF30.XNYM")
704        );
705    }
706
707    #[rstest]
708    #[case(2, "SR3Z6", "SR3Z26", "SR3Z26.XCME")]
709    #[case(2, "SR3Z6", "SR3Z36", "SR3Z36.XCME")]
710    #[case(2, "SR3Z6", "CLF26", "SR3Z36.XCME")]
711    #[case(2, "SR3Z6-SR3H7", "SR3Z26-SR3H27", "SR3Z26-SR3H27.XCME")]
712    #[case(1, "SR3Z6", "SR3Z26", "SR3Z6.XCME")]
713    fn test_market_record_uses_requested_contract_year(
714        #[case] digits: u8,
715        #[case] native: &str,
716        #[case] requested: &str,
717        #[case] expected: InstrumentId,
718    ) {
719        let mut msg = dbn::BboMsg::default_for_schema(dbn::Schema::Bbo1S);
720        msg.hd.publisher_id = 1;
721        msg.ts_recv = "2027-02-01T00:00:00Z"
722            .parse::<jiff::Timestamp>()
723            .unwrap()
724            .as_nanosecond() as u64;
725        let id = InstrumentId::new(Symbol::from(native), Venue::from("XCME"));
726        let symbols = AHashMap::from_iter([(Symbol::from(requested), Venue::from("XCME"))]);
727
728        let result = resolve_futures_instrument_id(
729            &dbn::RecordRef::from(&msg),
730            id,
731            digits.try_into().unwrap(),
732            &symbols,
733            None,
734        )
735        .unwrap();
736
737        assert_eq!(result, expected);
738    }
739
740    #[rstest]
741    #[case(2026, "CLF26.XCME")]
742    #[case(0, "CLF6.XCME")]
743    #[case(u16::MAX, "CLF6.XCME")]
744    fn test_definition_maturity_year_resolves_without_expiration(
745        #[case] maturity_year: u16,
746        #[case] expected: InstrumentId,
747    ) {
748        let msg = dbn::InstrumentDefMsg {
749            hd: dbn::RecordHeader::new::<dbn::InstrumentDefMsg>(
750                dbn::rtype::INSTRUMENT_DEF,
751                1,
752                42,
753                0,
754            ),
755            instrument_class: b'F' as std::ffi::c_char,
756            maturity_year,
757            expiration: dbn::UNDEF_TIMESTAMP,
758            ..Default::default()
759        };
760
761        let id = InstrumentId::from("CLF6.XCME");
762        let result = resolve_futures_instrument_id(
763            &dbn::RecordRef::from(&msg),
764            id,
765            FuturesYearDigits::Two,
766            &AHashMap::new(),
767            None,
768        )
769        .unwrap();
770        assert_eq!(result, expected);
771        assert_eq!(
772            resolve_futures_instrument_id(
773                &dbn::RecordRef::from(&msg),
774                id,
775                FuturesYearDigits::One,
776                &AHashMap::new(),
777                None
778            )
779            .unwrap(),
780            id
781        );
782    }
783}