Skip to main content

nautilus_model/identifiers/
futures.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
16//! Futures symbol parsing and formatting.
17
18use serde::{Deserialize, Serialize};
19
20/// The year-digit setting for futures instrument IDs in data and execution adapters.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(try_from = "u8", into = "u8")]
23#[repr(u8)]
24pub enum FuturesYearDigits {
25    One = 1,
26    Two = 2,
27}
28
29impl FuturesYearDigits {
30    /// The default setting, also available in constant constructors.
31    pub const DEFAULT: Self = Self::Two;
32}
33
34impl Default for FuturesYearDigits {
35    fn default() -> Self {
36        Self::DEFAULT
37    }
38}
39
40impl TryFrom<u8> for FuturesYearDigits {
41    type Error = anyhow::Error;
42
43    fn try_from(value: u8) -> Result<Self, Self::Error> {
44        match value {
45            1 => Ok(Self::One),
46            2 => Ok(Self::Two),
47            _ => anyhow::bail!("`futures_year_digits` must be either 1 or 2"),
48        }
49    }
50}
51
52impl From<FuturesYearDigits> for u8 {
53    fn from(value: FuturesYearDigits) -> Self {
54        value as Self
55    }
56}
57
58/// The parsed components of a futures symbol.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub struct FuturesSymbol<'a> {
61    /// Symbol root before the month code.
62    pub root: &'a str,
63    /// Standard futures month code.
64    pub month_code: char,
65    /// One-, two-, or four-digit year suffix.
66    pub year_digits: &'a str,
67}
68
69/// Parses a single-leg futures symbol such as `ESZ6`, `ESZ26`, or `ESZ2026`.
70/// Callers must split multi-leg symbols before parsing.
71#[must_use]
72pub fn parse_futures_symbol(symbol: &str) -> Option<FuturesSymbol<'_>> {
73    for (month_pos, month_code) in symbol.char_indices().rev() {
74        if futures_month(month_code).is_none() {
75            continue;
76        }
77
78        let year_digits = &symbol[month_pos + month_code.len_utf8()..];
79
80        if !matches!(year_digits.len(), 1 | 2 | 4)
81            || !year_digits.bytes().all(|b| b.is_ascii_digit())
82            || month_pos == 0
83        {
84            continue;
85        }
86
87        return Some(FuturesSymbol {
88            root: &symbol[..month_pos],
89            month_code,
90            year_digits,
91        });
92    }
93
94    None
95}
96
97/// Formats a futures symbol with one, two, or four year digits.
98#[must_use]
99pub fn format_futures_symbol(
100    root: &str,
101    month_code: char,
102    year: i32,
103    year_digits: u8,
104) -> Option<String> {
105    if root.is_empty() || futures_month(month_code).is_none() || !(0..=9999).contains(&year) {
106        return None;
107    }
108
109    let year = match year_digits {
110        1 => format!("{}", year % 10),
111        2 => format!("{:02}", year % 100),
112        4 => format!("{year:04}"),
113        _ => return None,
114    };
115
116    Some(format!("{root}{month_code}{year}"))
117}
118
119/// Resolves one-, two-, or four-digit futures years against a reference year.
120///
121/// A single digit resolves to the nearest matching year at or after the reference year,
122/// matching venue listing practice. Two digits carry the century-local year and resolve
123/// inside a window from 30 years before to 69 years after the reference year, so a
124/// recently expired id (`ESZ25` referenced in 2026) resolves to its actual year instead
125/// of a century ahead. Four digits are exact.
126#[must_use]
127pub fn resolve_futures_year(year_digits: &str, reference_year: i32) -> Option<i32> {
128    if reference_year < 0 || !year_digits.bytes().all(|b| b.is_ascii_digit()) {
129        return None;
130    }
131
132    let partial = year_digits.parse::<i32>().ok()?;
133    match year_digits.len() {
134        1 => {
135            let mut year = reference_year - reference_year.rem_euclid(10) + partial;
136            if year < reference_year {
137                year += 10;
138            }
139
140            Some(year)
141        }
142        2 => {
143            let mut year = reference_year - reference_year.rem_euclid(100) + partial;
144            if year < reference_year - 30 {
145                year += 100;
146            } else if year > reference_year + 69 {
147                year -= 100;
148            }
149
150            Some(year)
151        }
152        4 => Some(partial),
153        _ => None,
154    }
155}
156
157/// Resolves a futures year against an authoritative last-trade year.
158///
159/// A contract can stop trading in the year after its named contract month.
160/// Single-digit years may therefore start one calendar year before expiry,
161/// while deferred spread legs retain forward resolution. Longer suffixes use
162/// the same century window as [`resolve_futures_year`].
163#[must_use]
164pub fn resolve_futures_year_from_expiry(year_digits: &str, expiry_year: i32) -> Option<i32> {
165    let reference_year = if year_digits.len() == 1 && expiry_year > 0 {
166        expiry_year - 1
167    } else {
168        expiry_year
169    };
170
171    resolve_futures_year(year_digits, reference_year)
172}
173
174/// Returns the standard futures month code for a calendar month.
175#[must_use]
176pub const fn futures_month_code(month: u8) -> Option<char> {
177    match month {
178        1 => Some('F'),
179        2 => Some('G'),
180        3 => Some('H'),
181        4 => Some('J'),
182        5 => Some('K'),
183        6 => Some('M'),
184        7 => Some('N'),
185        8 => Some('Q'),
186        9 => Some('U'),
187        10 => Some('V'),
188        11 => Some('X'),
189        12 => Some('Z'),
190        _ => None,
191    }
192}
193
194/// Returns the calendar month for a standard futures month code.
195#[must_use]
196pub const fn futures_month(month_code: char) -> Option<u8> {
197    match month_code {
198        'F' => Some(1),
199        'G' => Some(2),
200        'H' => Some(3),
201        'J' => Some(4),
202        'K' => Some(5),
203        'M' => Some(6),
204        'N' => Some(7),
205        'Q' => Some(8),
206        'U' => Some(9),
207        'V' => Some(10),
208        'X' => Some(11),
209        'Z' => Some(12),
210        _ => None,
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use rstest::rstest;
217
218    use super::*;
219
220    #[rstest]
221    fn test_futures_year_digits_defaults_to_two() {
222        assert_eq!(FuturesYearDigits::default(), FuturesYearDigits::Two);
223    }
224
225    #[rstest]
226    #[case(1, FuturesYearDigits::One)]
227    #[case(2, FuturesYearDigits::Two)]
228    fn test_futures_year_digits_integer_round_trip(
229        #[case] digits: u8,
230        #[case] expected: FuturesYearDigits,
231    ) {
232        assert_eq!(FuturesYearDigits::try_from(digits).unwrap(), expected);
233        assert_eq!(u8::from(expected), digits);
234        assert_eq!(
235            serde_json::to_value(expected).unwrap(),
236            serde_json::json!(digits)
237        );
238        assert_eq!(
239            serde_json::from_value::<FuturesYearDigits>(serde_json::json!(digits)).unwrap(),
240            expected
241        );
242    }
243
244    #[rstest]
245    #[case(0)]
246    #[case(3)]
247    #[case(4)]
248    #[case(u8::MAX)]
249    fn test_futures_year_digits_rejects_other_integers(#[case] digits: u8) {
250        let expected = "`futures_year_digits` must be either 1 or 2";
251        assert_eq!(
252            FuturesYearDigits::try_from(digits).unwrap_err().to_string(),
253            expected
254        );
255        assert_eq!(
256            serde_json::from_value::<FuturesYearDigits>(serde_json::json!(digits))
257                .unwrap_err()
258                .to_string(),
259            expected
260        );
261    }
262
263    #[rstest]
264    #[case("ESZ6", "ES", 'Z', "6")]
265    #[case("ESZ26", "ES", 'Z', "26")]
266    #[case("ESZ2026", "ES", 'Z', "2026")]
267    #[case("EX2G3", "EX2", 'G', "3")]
268    fn test_parse_futures_symbol(
269        #[case] value: &str,
270        #[case] root: &str,
271        #[case] month_code: char,
272        #[case] year_digits: &str,
273    ) {
274        assert_eq!(
275            parse_futures_symbol(value),
276            Some(FuturesSymbol {
277                root,
278                month_code,
279                year_digits,
280            })
281        );
282    }
283
284    #[rstest]
285    #[case(1, "ESZ6")]
286    #[case(2, "ESZ26")]
287    #[case(4, "ESZ2026")]
288    fn test_format_futures_symbol(#[case] digits: u8, #[case] expected: &str) {
289        assert_eq!(
290            format_futures_symbol("ES", 'Z', 2026, digits).as_deref(),
291            Some(expected)
292        );
293    }
294
295    #[rstest]
296    #[case("6", 2026, 2026)]
297    #[case("5", 2026, 2035)]
298    #[case("26", 2026, 2026)]
299    #[case("25", 2026, 2025)]
300    #[case("96", 2026, 1996)]
301    #[case("95", 2026, 2095)]
302    #[case("00", 2099, 2100)]
303    #[case("01", 2099, 2101)]
304    #[case("2026", 2099, 2026)]
305    fn test_resolve_futures_year(
306        #[case] digits: &str,
307        #[case] reference_year: i32,
308        #[case] expected: i32,
309    ) {
310        assert_eq!(resolve_futures_year(digits, reference_year), Some(expected));
311    }
312
313    #[rstest]
314    #[case(1, 'F')]
315    #[case(6, 'M')]
316    #[case(12, 'Z')]
317    fn test_futures_month_round_trip(#[case] month: u8, #[case] code: char) {
318        assert_eq!(futures_month_code(month), Some(code));
319        assert_eq!(futures_month(code), Some(month));
320    }
321
322    #[rstest]
323    #[case("")]
324    #[case("ES")]
325    #[case("ESZ")]
326    #[case("ESZ123")]
327    #[case("Z26")]
328    fn test_parse_futures_symbol_rejects_invalid_values(#[case] value: &str) {
329        assert_eq!(parse_futures_symbol(value), None);
330    }
331
332    #[rstest]
333    #[case("6", 2027, 2026)]
334    #[case("9", 2030, 2029)]
335    #[case("0", 2029, 2030)]
336    #[case("7", 2027, 2027)]
337    #[case("3", 2027, 2033)]
338    #[case("26", 2027, 2026)]
339    #[case("2026", 2027, 2026)]
340    fn test_resolve_futures_year_from_expiry(
341        #[case] digits: &str,
342        #[case] expiry_year: i32,
343        #[case] expected: i32,
344    ) {
345        assert_eq!(
346            resolve_futures_year_from_expiry(digits, expiry_year),
347            Some(expected)
348        );
349    }
350}