Skip to main content

nautilus_tardis/http/
instruments.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 nautilus_core::{DurationNanos, Params, UnixNanos};
17use nautilus_model::{
18    identifiers::{InstrumentId, Symbol},
19    instruments::{CryptoFuture, CryptoOption, CryptoPerpetual, CurrencyPair, InstrumentAny},
20    types::{Currency, Price, Quantity},
21};
22use rust_decimal::Decimal;
23
24use super::{models::TardisInstrumentInfo, parse::parse_settlement_currency};
25use crate::common::parse::{option_terms, parse_option_kind};
26
27/// Returns a currency from the internal map or creates a new crypto currency.
28///
29/// Uses [`Currency::get_or_create_crypto`] to handle unknown currency codes,
30/// which automatically registers newly listed exchange assets.
31pub(crate) fn get_currency(code: &str) -> Currency {
32    Currency::get_or_create_crypto(code)
33}
34
35/// Builds an `Option<Params>` from raw Tardis instrument metadata.
36fn build_info_params(info: &TardisInstrumentInfo) -> Option<Params> {
37    match serde_json::to_value(info) {
38        Ok(value) => match serde_json::from_value(value) {
39            Ok(params) => Some(params),
40            Err(e) => {
41                log::warn!("Failed to convert instrument info to Params: {e}");
42                None
43            }
44        },
45        Err(e) => {
46            log::warn!("Failed to serialize instrument info: {e}");
47            None
48        }
49    }
50}
51
52/// Creates a currency pair instrument definition.
53///
54/// # Panics
55///
56/// Panics if the constructed instrument fails validation.
57#[expect(clippy::too_many_arguments)]
58#[must_use]
59pub fn create_currency_pair(
60    info: &TardisInstrumentInfo,
61    instrument_id: InstrumentId,
62    raw_symbol: Symbol,
63    price_increment: Price,
64    size_increment: Quantity,
65    multiplier: Option<Quantity>,
66    margin_init: Decimal,
67    margin_maint: Decimal,
68    ts_event: UnixNanos,
69    ts_init: UnixNanos,
70) -> InstrumentAny {
71    InstrumentAny::CurrencyPair(
72        CurrencyPair::builder()
73            .instrument_id(instrument_id)
74            .raw_symbol(raw_symbol)
75            .base_currency(get_currency(info.base_currency.to_uppercase().as_str()))
76            .quote_currency(get_currency(info.quote_currency.to_uppercase().as_str()))
77            .price_precision(price_increment.precision)
78            .size_precision(size_increment.precision)
79            .price_increment(price_increment)
80            .size_increment(size_increment)
81            .maybe_multiplier(multiplier)
82            .lot_size(size_increment)
83            .min_quantity(Quantity::from(info.min_trade_amount.to_string()))
84            .margin_init(margin_init)
85            .margin_maint(margin_maint)
86            .maybe_info(build_info_params(info))
87            .ts_event(ts_event)
88            .ts_init(ts_init)
89            .build()
90            .unwrap(),
91    )
92}
93
94/// Creates a crypto perpetual instrument definition.
95///
96/// # Panics
97///
98/// Panics if the constructed instrument fails validation.
99#[expect(clippy::too_many_arguments)]
100#[must_use]
101pub fn create_crypto_perpetual(
102    info: &TardisInstrumentInfo,
103    instrument_id: InstrumentId,
104    raw_symbol: Symbol,
105    price_increment: Price,
106    size_increment: Quantity,
107    multiplier: Option<Quantity>,
108    margin_init: Decimal,
109    margin_maint: Decimal,
110    ts_event: UnixNanos,
111    ts_init: UnixNanos,
112) -> InstrumentAny {
113    let is_inverse = info.inverse.unwrap_or(false);
114
115    InstrumentAny::CryptoPerpetual(
116        CryptoPerpetual::builder()
117            .instrument_id(instrument_id)
118            .raw_symbol(raw_symbol)
119            .base_currency(get_currency(info.base_currency.to_uppercase().as_str()))
120            .quote_currency(get_currency(info.quote_currency.to_uppercase().as_str()))
121            .settlement_currency(get_currency(
122                parse_settlement_currency(info, is_inverse).as_str(),
123            ))
124            .is_inverse(is_inverse)
125            .price_precision(price_increment.precision)
126            .size_precision(size_increment.precision)
127            .price_increment(price_increment)
128            .size_increment(size_increment)
129            .maybe_multiplier(multiplier)
130            .lot_size(size_increment)
131            .min_quantity(Quantity::from(info.min_trade_amount.to_string()))
132            .margin_init(margin_init)
133            .margin_maint(margin_maint)
134            .maybe_info(build_info_params(info))
135            .ts_event(ts_event)
136            .ts_init(ts_init)
137            .build()
138            .unwrap(),
139    )
140}
141
142/// Creates a crypto future instrument definition.
143///
144/// # Panics
145///
146/// Panics if the constructed instrument fails validation.
147#[expect(clippy::too_many_arguments)]
148#[must_use]
149pub fn create_crypto_future(
150    info: &TardisInstrumentInfo,
151    instrument_id: InstrumentId,
152    raw_symbol: Symbol,
153    activation: UnixNanos,
154    expiration: UnixNanos,
155    price_increment: Price,
156    size_increment: Quantity,
157    multiplier: Option<Quantity>,
158    margin_init: Decimal,
159    margin_maint: Decimal,
160    ts_event: UnixNanos,
161    ts_init: UnixNanos,
162) -> InstrumentAny {
163    let is_inverse = info.inverse.unwrap_or(false);
164
165    InstrumentAny::CryptoFuture(
166        CryptoFuture::builder()
167            .instrument_id(instrument_id)
168            .raw_symbol(raw_symbol)
169            .underlying(get_currency(info.base_currency.to_uppercase().as_str()))
170            .quote_currency(get_currency(info.quote_currency.to_uppercase().as_str()))
171            .settlement_currency(get_currency(
172                parse_settlement_currency(info, is_inverse).as_str(),
173            ))
174            .is_inverse(is_inverse)
175            .activation_ns(activation)
176            .expiration_ns(expiration)
177            .price_precision(price_increment.precision)
178            .size_precision(size_increment.precision)
179            .price_increment(price_increment)
180            .size_increment(size_increment)
181            .maybe_multiplier(multiplier)
182            .lot_size(size_increment)
183            .min_quantity(Quantity::from(info.min_trade_amount.to_string()))
184            .margin_init(margin_init)
185            .margin_maint(margin_maint)
186            .maybe_info(build_info_params(info))
187            .ts_event(ts_event)
188            .ts_init(ts_init)
189            .build()
190            .unwrap(),
191    )
192}
193
194#[expect(clippy::too_many_arguments)]
195/// Create a crypto option instrument definition.
196///
197/// # Errors
198///
199/// Returns an error if the `option_type` or `strike_price` field of `InstrumentInfo` is `None`.
200///
201/// # Panics
202///
203/// Panics if the constructed instrument fails validation.
204pub fn create_crypto_option(
205    info: &TardisInstrumentInfo,
206    instrument_id: InstrumentId,
207    raw_symbol: Symbol,
208    activation: UnixNanos,
209    expiration: UnixNanos,
210    price_increment: Price,
211    size_increment: Quantity,
212    multiplier: Option<Quantity>,
213    margin_init: Decimal,
214    margin_maint: Decimal,
215    ts_event: UnixNanos,
216    ts_init: UnixNanos,
217) -> anyhow::Result<InstrumentAny> {
218    let is_inverse = info.inverse.unwrap_or(false);
219
220    let option_type = info.option_type.ok_or_else(|| {
221        anyhow::anyhow!(
222            "CryptoOption missing `option_type` field for instrument: {}",
223            info.id
224        )
225    })?;
226
227    let strike_price = info.strike_price.ok_or_else(|| {
228        anyhow::anyhow!(
229            "CryptoOption missing `strike_price` field for instrument: {}",
230            info.id
231        )
232    })?;
233
234    let (exercise_style, settlement_type) = option_terms(info.exchange);
235
236    Ok(InstrumentAny::CryptoOption(
237        CryptoOption::builder()
238            .instrument_id(instrument_id)
239            .raw_symbol(raw_symbol)
240            .underlying(get_currency(info.base_currency.to_uppercase().as_str()))
241            .quote_currency(get_currency(info.quote_currency.to_uppercase().as_str()))
242            .settlement_currency(get_currency(
243                parse_settlement_currency(info, is_inverse).as_str(),
244            ))
245            .is_inverse(is_inverse)
246            .option_kind(parse_option_kind(option_type))
247            .strike_price(Price::new(strike_price, price_increment.precision))
248            .activation_ns(activation)
249            .expiration_ns(expiration)
250            .price_precision(price_increment.precision)
251            .size_precision(size_increment.precision)
252            .price_increment(price_increment)
253            .size_increment(size_increment)
254            .maybe_multiplier(multiplier)
255            .lot_size(size_increment)
256            .min_quantity(Quantity::from(info.min_trade_amount.to_string()))
257            .margin_init(margin_init)
258            .margin_maint(margin_maint)
259            .maybe_info(build_info_params(info))
260            .maybe_exercise_style(exercise_style)
261            .maybe_settlement_type(settlement_type)
262            .ts_event(ts_event)
263            .ts_init(ts_init)
264            .build()
265            .unwrap(),
266    ))
267}
268
269/// Checks if an instrument is available and valid based on time constraints.
270pub fn is_available(
271    info: &TardisInstrumentInfo,
272    start: Option<UnixNanos>,
273    end: Option<UnixNanos>,
274    available_offset: Option<DurationNanos>,
275    effective: Option<UnixNanos>,
276) -> bool {
277    let available_since =
278        UnixNanos::from(info.available_since) + available_offset.unwrap_or_default();
279    let available_to = info.available_to.map_or(UnixNanos::max(), UnixNanos::from);
280
281    if let Some(effective_date) = effective {
282        // Effective date must be within availability period
283        if available_since > effective_date || available_to <= effective_date {
284            return false;
285        }
286
287        // Effective date must be within requested [start, end] if provided
288        if start.is_some_and(|s| effective_date < s) || end.is_some_and(|e| effective_date > e) {
289            return false;
290        }
291    } else {
292        // Otherwise check for overlap between [available_since, available_to] and [start, end]
293        if start.is_some_and(|s| available_to < s) || end.is_some_and(|e| available_since > e) {
294            return false;
295        }
296    }
297
298    true
299}
300
301#[cfg(test)]
302mod tests {
303    use rstest::rstest;
304
305    use super::*;
306    use crate::common::testing::load_test_json;
307
308    fn create_test_instrument(
309        available_since: u64,
310        available_to: Option<u64>,
311    ) -> TardisInstrumentInfo {
312        let json_data = load_test_json("instrument_spot.json");
313        let mut info: TardisInstrumentInfo = serde_json::from_str(&json_data).unwrap();
314        info.available_since = UnixNanos::from(available_since).to_datetime_utc();
315        info.available_to = available_to.map(|a| UnixNanos::from(a).to_datetime_utc());
316        info
317    }
318
319    #[rstest]
320    #[case::no_constraints(None, None, None, None, true)]
321    #[case::within_start_end(Some(100), Some(300), None, None, true)]
322    #[case::before_start(Some(200), Some(300), None, None, true)]
323    #[case::after_end(Some(100), Some(150), None, None, true)]
324    #[case::with_offset_within_range(Some(200), Some(300), Some(50), None, true)]
325    #[case::with_offset_adjusted_within_range(Some(150), Some(300), Some(50), None, true)]
326    #[case::effective_within_availability(None, None, None, Some(150), true)]
327    #[case::effective_before_availability(None, None, None, Some(50), false)]
328    #[case::effective_after_availability(None, None, None, Some(250), false)]
329    #[case::effective_within_start_end(Some(100), Some(200), None, Some(150), true)]
330    #[case::effective_before_start(Some(150), Some(200), None, Some(120), false)]
331    #[case::effective_after_end(Some(100), Some(150), None, Some(180), false)]
332    #[case::effective_equals_available_since(None, None, None, Some(100), true)]
333    #[case::effective_equals_available_since_with_offset(None, None, Some(10), Some(110), true)]
334    #[case::effective_equals_available_to(None, None, None, Some(200), false)]
335    fn test_is_available(
336        #[case] start: Option<u64>,
337        #[case] end: Option<u64>,
338        #[case] available_offset: Option<u64>,
339        #[case] effective: Option<u64>,
340        #[case] expected: bool,
341    ) {
342        // Create instrument with fixed availability 100-200
343        let info = create_test_instrument(100, Some(200));
344
345        // Convert all u64 values to UnixNanos
346        let start_nanos = start.map(UnixNanos::from);
347        let end_nanos = end.map(UnixNanos::from);
348        let offset_nanos = available_offset.map(DurationNanos::new);
349        let effective_nanos = effective.map(UnixNanos::from);
350
351        // Run the test
352        let result = is_available(&info, start_nanos, end_nanos, offset_nanos, effective_nanos);
353
354        assert_eq!(
355            result, expected,
356            "Test failed with start={start:?}, end={end:?}, offset={available_offset:?}, effective={effective:?}"
357        );
358    }
359
360    #[rstest]
361    #[case::before_rename(199, "XBT/USDT")]
362    #[case::at_rename(200, "BTC/USDT")]
363    #[case::after_rename(201, "BTC/USDT")]
364    fn test_renamed_instrument_availability(#[case] effective: u64, #[case] expected: &str) {
365        let mut previous = create_test_instrument(100, Some(200));
366        previous.id = "XBT/USDT".into();
367        let mut current = create_test_instrument(200, None);
368        current.id = "BTC/USDT".into();
369        let available = [previous, current]
370            .into_iter()
371            .filter(|info| is_available(info, None, None, None, Some(UnixNanos::from(effective))))
372            .map(|info| info.id.to_string())
373            .collect::<Vec<_>>();
374
375        assert_eq!(available, vec![expected]);
376    }
377
378    #[rstest]
379    fn test_infinite_available_to() {
380        // Create instrument with infinite availability (no end date)
381        let info = create_test_instrument(100, None);
382
383        // Should be available for any end date
384        assert!(is_available(
385            &info,
386            None,
387            Some(UnixNanos::from(1000000)),
388            None,
389            None
390        ));
391
392        // Should be available for any effective date after available_since
393        assert!(is_available(
394            &info,
395            None,
396            None,
397            None,
398            Some(UnixNanos::from(101))
399        ));
400
401        assert!(is_available(
402            &info,
403            None,
404            None,
405            None,
406            Some(UnixNanos::from(100))
407        ));
408        assert!(!is_available(
409            &info,
410            None,
411            None,
412            None,
413            Some(UnixNanos::from(99))
414        ));
415    }
416
417    #[rstest]
418    fn test_available_offset_effects() {
419        // Create instrument with fixed availability 100-200
420        let info = create_test_instrument(100, Some(200));
421
422        assert!(is_available(
423            &info,
424            None,
425            None,
426            None,
427            Some(UnixNanos::from(100))
428        ));
429
430        // With offset of 10, effective date of 100 should be invalid (since available_since becomes 110)
431        assert!(!is_available(
432            &info,
433            None,
434            None,
435            Some(DurationNanos::new(10)),
436            Some(UnixNanos::from(100))
437        ));
438
439        // Test with larger offset
440        assert!(!is_available(
441            &info,
442            None,
443            None,
444            Some(DurationNanos::new(20)),
445            Some(UnixNanos::from(119))
446        ));
447        assert!(is_available(
448            &info,
449            None,
450            None,
451            Some(DurationNanos::new(20)),
452            Some(UnixNanos::from(121))
453        ));
454    }
455
456    #[rstest]
457    fn test_with_real_dates() {
458        // Using realistic Unix timestamps (milliseconds since epoch)
459        // April 24, 2023 00:00:00 UTC = 1682294400000
460        // April 2, 2024 12:10:00 UTC = 1712061000000
461
462        let info = create_test_instrument(1682294400000, Some(1712061000000));
463
464        // Test effective date is within range
465        let mid_date = UnixNanos::from(1695000000000); // Sept 2023
466        assert!(is_available(&info, None, None, None, Some(mid_date)));
467
468        // Test with start/end constraints
469        let start = UnixNanos::from(1690000000000); // July 2023
470        let end = UnixNanos::from(1700000000000); // Nov 2023
471        assert!(is_available(
472            &info,
473            Some(start),
474            Some(end),
475            None,
476            Some(mid_date)
477        ));
478
479        let offset = DurationNanos::new(86_400_000);
480
481        let offset_boundary = UnixNanos::from(1_682_294_400_000 + 86_400_000);
482        assert!(is_available(
483            &info,
484            None,
485            None,
486            Some(offset),
487            Some(offset_boundary)
488        ));
489
490        let start_date = UnixNanos::from(1682294400000);
491        assert!(is_available(&info, None, None, None, Some(start_date)));
492
493        // Effective date at exactly the end should fail
494        let end_date = UnixNanos::from(1712061000000);
495        assert!(!is_available(&info, None, None, None, Some(end_date)));
496    }
497
498    #[rstest]
499    fn test_complex_scenarios() {
500        // Create instrument with fixed availability 100-200
501        let info = create_test_instrument(100, Some(200));
502
503        // Scenario: Start and end window partially overlaps with availability
504        assert!(is_available(
505            &info,
506            Some(UnixNanos::from(150)),
507            Some(UnixNanos::from(250)),
508            None,
509            None
510        ));
511        assert!(is_available(
512            &info,
513            Some(UnixNanos::from(50)),
514            Some(UnixNanos::from(150)),
515            None,
516            None
517        ));
518
519        // Scenario: Start and end window completely contains availability
520        assert!(is_available(
521            &info,
522            Some(UnixNanos::from(50)),
523            Some(UnixNanos::from(250)),
524            None,
525            None
526        ));
527
528        // Scenario: Start and end window completely within availability
529        assert!(is_available(
530            &info,
531            Some(UnixNanos::from(120)),
532            Some(UnixNanos::from(180)),
533            None,
534            None
535        ));
536
537        // Scenario: Effective date with start/end constraints
538        assert!(is_available(
539            &info,
540            Some(UnixNanos::from(120)),
541            Some(UnixNanos::from(180)),
542            None,
543            Some(UnixNanos::from(150))
544        ));
545
546        // Scenario: Effective date outside start/end constraints but within availability
547        assert!(!is_available(
548            &info,
549            Some(UnixNanos::from(120)),
550            Some(UnixNanos::from(140)),
551            None,
552            Some(UnixNanos::from(150))
553        ));
554    }
555
556    #[rstest]
557    fn test_edge_cases() {
558        // Test with empty "changes" array
559        let mut info = create_test_instrument(100, Some(200));
560        info.changes = Some(vec![]);
561        assert!(is_available(
562            &info,
563            None,
564            None,
565            None,
566            Some(UnixNanos::from(150))
567        ));
568
569        // Test with very large timestamps (near u64::MAX)
570        let far_future_info = create_test_instrument(100, None); // No end date = indefinite future
571        let far_future_date = UnixNanos::from(u64::MAX - 1000);
572        assert!(is_available(
573            &far_future_info,
574            None,
575            None,
576            None,
577            Some(UnixNanos::from(101))
578        ));
579        assert!(is_available(
580            &far_future_info,
581            None,
582            Some(far_future_date),
583            None,
584            None
585        ));
586
587        // Test with offset that increases available_since
588        let info = create_test_instrument(100, Some(200));
589
590        // Adding offset of 50 to available_since (100) makes it 150
591        let offset = DurationNanos::new(50);
592        assert!(!is_available(
593            &info,
594            None,
595            None,
596            Some(offset),
597            Some(UnixNanos::from(149))
598        ));
599        assert!(is_available(
600            &info,
601            None,
602            None,
603            Some(offset),
604            Some(UnixNanos::from(151))
605        ));
606
607        // Test with offset equal to zero (no effect)
608        let zero_offset = DurationNanos::ZERO;
609        assert!(is_available(
610            &info,
611            None,
612            None,
613            Some(zero_offset),
614            Some(UnixNanos::from(100))
615        ));
616        assert!(is_available(
617            &info,
618            None,
619            None,
620            Some(zero_offset),
621            Some(UnixNanos::from(101))
622        ));
623    }
624}