Skip to main content

nautilus_model/types/
currency.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//! Represents a medium of exchange in a specified denomination with a fixed decimal precision.
17//!
18//! Handles up to 16 decimals of precision.
19
20use std::{
21    fmt::{Debug, Display},
22    hash::{Hash, Hasher},
23    str::FromStr,
24};
25
26use nautilus_core::correctness::{
27    CorrectnessResult, CorrectnessResultExt, FAILED, check_nonempty_string, check_valid_string_utf8,
28};
29use serde::{Deserialize, Serialize, Serializer};
30use thiserror::Error;
31use ustr::Ustr;
32
33#[allow(unused_imports)]
34use super::fixed::{FIXED_PRECISION, check_fixed_precision};
35use crate::{currencies::CURRENCY_MAP, deserialization::StringInput, enums::CurrencyType};
36
37/// Error returned when a currency cannot be resolved from the model currency map.
38#[derive(Clone, Debug, Error, Eq, PartialEq)]
39pub enum CurrencyLookupError {
40    /// A legacy currency-map lock failure.
41    ///
42    /// Current lookup methods use infallible locks and do not return this variant.
43    #[error("Failed to acquire lock on `CURRENCY_MAP`: {reason}")]
44    LockFailure {
45        /// The legacy lock failure reason.
46        reason: String,
47    },
48    /// The requested currency code is not present in the currency map.
49    #[error("Unknown currency: {code}")]
50    UnknownCode {
51        /// The currency code that was requested.
52        code: String,
53    },
54}
55
56/// Represents a medium of exchange in a specified denomination with a fixed decimal precision.
57///
58/// Handles up to [`FIXED_PRECISION`] decimals of precision.
59#[repr(C)]
60#[derive(Clone, Copy, Eq)]
61#[cfg_attr(
62    feature = "python",
63    pyo3::pyclass(module = "nautilus_trader.model", frozen, eq, hash, from_py_object)
64)]
65#[cfg_attr(
66    feature = "python",
67    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
68)]
69pub struct Currency {
70    /// The currency code as an alpha-3 string (e.g., "USD", "EUR").
71    pub code: Ustr,
72    /// The currency decimal precision.
73    pub precision: u8,
74    /// The ISO 4217 currency code.
75    pub iso4217: u16,
76    /// The full name of the currency.
77    pub name: Ustr,
78    /// The currency type, indicating its category (e.g. Fiat, Crypto).
79    pub currency_type: CurrencyType,
80}
81
82impl Currency {
83    /// Creates a new [`Currency`] instance with correctness checking.
84    ///
85    /// # Errors
86    ///
87    /// Returns an error if:
88    /// - `code` is not a valid string.
89    /// - `name` is the empty string.
90    /// - `precision` is invalid outside the valid representable range [0, `FIXED_PRECISION`].
91    ///
92    /// # Notes
93    ///
94    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
95    pub fn new_checked<T: AsRef<str>>(
96        code: T,
97        precision: u8,
98        iso4217: u16,
99        name: T,
100        currency_type: CurrencyType,
101    ) -> CorrectnessResult<Self> {
102        let code = code.as_ref();
103        let name = name.as_ref();
104        check_valid_string_utf8(code, "code")?;
105        check_nonempty_string(name, "name")?;
106        check_fixed_precision(precision)?;
107        Ok(Self {
108            code: Ustr::from(code),
109            precision,
110            iso4217,
111            name: Ustr::from(name),
112            currency_type,
113        })
114    }
115
116    /// Creates a new [`Currency`] instance.
117    ///
118    /// # Panics
119    ///
120    /// Panics if a correctness check fails. See [`Currency::new_checked`] for more details.
121    pub fn new<T: AsRef<str>>(
122        code: T,
123        precision: u8,
124        iso4217: u16,
125        name: T,
126        currency_type: CurrencyType,
127    ) -> Self {
128        Self::new_checked(code, precision, iso4217, name, currency_type).expect_display(FAILED)
129    }
130
131    /// Register the given `currency` in the internal currency map.
132    ///
133    /// - If `overwrite` is `true`, any existing currency will be replaced.
134    /// - If `overwrite` is `false` and the currency already exists, the operation is a no-op.
135    ///
136    /// Registered DeFi tokens retain their first name and amount definition, including when
137    /// `overwrite` is `true`.
138    ///
139    /// # Errors
140    ///
141    /// Returns an error if the amount definition conflicts with a registered DeFi token.
142    pub fn register(currency: Self, overwrite: bool) -> CorrectnessResult<()> {
143        let mut map = CURRENCY_MAP.lock();
144
145        #[cfg(feature = "defi")]
146        if let Some(registered) = crate::defi::currency::check_registration(currency)? {
147            map.insert(registered.code.to_string(), registered);
148            return Ok(());
149        }
150
151        if !overwrite && map.contains_key(currency.code.as_str()) {
152            // If overwrite is false and the currency already exists, simply return
153            return Ok(());
154        }
155
156        // Insert or overwrite the currency in the map
157        map.insert(currency.code.to_string(), currency);
158        Ok(())
159    }
160
161    /// Attempts to parse a [`Currency`] from a string, returning `None` if not found.
162    pub fn try_from_str(s: &str) -> Option<Self> {
163        let map_guard = CURRENCY_MAP.lock();
164        map_guard.get(s).copied()
165    }
166
167    /// Checks if the currency identified by the given `code` is a fiat currency.
168    ///
169    /// # Errors
170    ///
171    /// Returns an error if a currency with the given `code` does not exist.
172    pub fn is_fiat(code: &str) -> Result<bool, CurrencyLookupError> {
173        let currency = Self::from_str(code)?;
174        Ok(currency.currency_type == CurrencyType::Fiat)
175    }
176
177    /// Checks if the currency identified by the given `code` is a cryptocurrency.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error if a currency with the given `code` does not exist.
182    pub fn is_crypto(code: &str) -> Result<bool, CurrencyLookupError> {
183        let currency = Self::from_str(code)?;
184        Ok(currency.currency_type == CurrencyType::Crypto)
185    }
186
187    /// Checks if the currency identified by the given `code` is a commodity (such as a precious
188    /// metal).
189    ///
190    /// # Errors
191    ///
192    /// Returns an error if a currency with the given `code` does not exist.
193    pub fn is_commodity_backed(code: &str) -> Result<bool, CurrencyLookupError> {
194        let currency = Self::from_str(code)?;
195        Ok(currency.currency_type == CurrencyType::CommodityBacked)
196    }
197
198    /// Returns a currency from the internal map or creates a new crypto currency if not found.
199    ///
200    /// This is a convenience method for adapters that need to handle unknown currencies
201    /// (e.g., newly listed assets on exchanges). If the currency code is not found in the
202    /// internal map, a new cryptocurrency is created with:
203    /// - 8 decimal precision
204    /// - ISO 4217 code of 0
205    /// - `CurrencyType::Crypto`
206    ///
207    /// The newly created currency is automatically registered in the internal map.
208    #[must_use]
209    pub fn get_or_create_crypto<T: AsRef<str>>(code: T) -> Self {
210        let code_str = code.as_ref();
211        Self::try_from_str(code_str).unwrap_or_else(|| {
212            let currency = Self::new(code_str, 8, 0, code_str, CurrencyType::Crypto);
213
214            if let Err(e) = Self::register(currency, false) {
215                log::error!("Failed to register currency '{code_str}': {e}");
216
217                #[cfg(feature = "defi")]
218                if let Some((registered, _)) = crate::defi::currency::lookup(currency.code) {
219                    return registered;
220                }
221            }
222
223            currency
224        })
225    }
226
227    /// Gets or creates a cryptocurrency with context logging.
228    ///
229    /// This is a convenience wrapper around [`Currency::get_or_create_crypto`] that:
230    /// - Trims whitespace from the currency code
231    /// - Handles empty strings with a fallback to USDT
232    /// - Provides optional context for logging
233    ///
234    /// Used by exchange adapters for consistent currency handling across parsing operations.
235    ///
236    /// # Arguments
237    ///
238    /// * `code` - The currency code (will be trimmed)
239    /// * `context` - Optional context for logging (e.g., "balance detail", "instrument")
240    #[must_use]
241    pub fn get_or_create_crypto_with_context<T: AsRef<str>>(
242        code: T,
243        context: Option<&str>,
244    ) -> Self {
245        let trimmed = code.as_ref().trim();
246        let ctx = context.unwrap_or("unknown");
247
248        if trimmed.is_empty() {
249            log::warn!(
250                "get_or_create_crypto_with_context called with empty code (context: {ctx}), using USDT as fallback"
251            );
252            return Self::USDT();
253        }
254
255        Self::get_or_create_crypto(trimmed)
256    }
257}
258
259impl PartialEq for Currency {
260    fn eq(&self, other: &Self) -> bool {
261        self.code == other.code
262    }
263}
264
265impl Hash for Currency {
266    fn hash<H: Hasher>(&self, state: &mut H) {
267        self.code.hash(state);
268    }
269}
270
271impl Debug for Currency {
272    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273        write!(
274            f,
275            "{}(code='{}', precision={}, iso4217={}, name='{}', currency_type={})",
276            stringify!(Currency),
277            self.code,
278            self.precision,
279            self.iso4217,
280            self.name,
281            self.currency_type,
282        )
283    }
284}
285
286impl Display for Currency {
287    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288        write!(f, "{}", self.code)
289    }
290}
291
292impl FromStr for Currency {
293    type Err = CurrencyLookupError;
294
295    fn from_str(s: &str) -> Result<Self, Self::Err> {
296        let map_guard = CURRENCY_MAP.lock();
297        map_guard
298            .get(s)
299            .copied()
300            .ok_or_else(|| CurrencyLookupError::UnknownCode {
301                code: s.to_string(),
302            })
303    }
304}
305
306impl<T: AsRef<str>> From<T> for Currency {
307    fn from(value: T) -> Self {
308        match Self::from_str(value.as_ref()) {
309            Ok(currency) => currency,
310            Err(e) => panic!("{FAILED}: {e}"),
311        }
312    }
313}
314
315impl Serialize for Currency {
316    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
317    where
318        S: Serializer,
319    {
320        self.code.serialize(serializer)
321    }
322}
323
324impl<'de> Deserialize<'de> for Currency {
325    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
326    where
327        D: serde::Deserializer<'de>,
328    {
329        let StringInput(currency_str) = Deserialize::deserialize(deserializer)?;
330        Self::from_str(currency_str.as_ref()).map_err(serde::de::Error::custom)
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use std::str::FromStr;
337
338    use rstest::rstest;
339
340    use crate::{
341        enums::CurrencyType,
342        types::{Currency, CurrencyLookupError},
343    };
344
345    #[rstest]
346    fn test_debug() {
347        let currency = Currency::AUD();
348        assert_eq!(
349            format!("{currency:?}"),
350            "Currency(code='AUD', precision=2, iso4217=36, name='Australian dollar', currency_type=FIAT)".to_string()
351        );
352    }
353
354    #[rstest]
355    fn test_display() {
356        let currency = Currency::AUD();
357        assert_eq!(format!("{currency}"), "AUD");
358    }
359
360    #[rstest]
361    #[should_panic(expected = "code")]
362    fn test_invalid_currency_code() {
363        let _ = Currency::new("", 2, 840, "United States dollar", CurrencyType::Fiat);
364    }
365
366    #[cfg(not(feature = "defi"))]
367    #[rstest]
368    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
369    fn test_invalid_precision() {
370        // Precision greater than maximum (use 19 which exceeds even defi precision of 18)
371        let _ = Currency::new("USD", 19, 840, "United States dollar", CurrencyType::Fiat);
372    }
373
374    #[cfg(feature = "defi")]
375    #[rstest]
376    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `WEI_PRECISION`")]
377    fn test_invalid_precision() {
378        // Precision greater than maximum (use 19 which exceeds even defi precision of 18)
379        let _ = Currency::new("ETH", 19, 0, "Ethereum", CurrencyType::Crypto);
380    }
381
382    #[rstest]
383    fn test_register_no_overwrite() {
384        let currency1 = Currency::new("TEST1", 2, 999, "Test Currency 1", CurrencyType::Fiat);
385        Currency::register(currency1, false).unwrap();
386
387        let currency2 = Currency::new(
388            "TEST1",
389            2,
390            999,
391            "Test Currency 2 Updated",
392            CurrencyType::Fiat,
393        );
394        Currency::register(currency2, false).unwrap();
395
396        let found = Currency::try_from_str("TEST1").unwrap();
397        assert_eq!(found.name.as_str(), "Test Currency 1");
398    }
399
400    #[rstest]
401    fn test_register_with_overwrite() {
402        let currency1 = Currency::new("TEST2", 2, 998, "Test Currency 2", CurrencyType::Fiat);
403        Currency::register(currency1, false).unwrap();
404
405        let currency2 = Currency::new(
406            "TEST2",
407            2,
408            998,
409            "Test Currency 2 Overwritten",
410            CurrencyType::Fiat,
411        );
412        Currency::register(currency2, true).unwrap();
413
414        let found = Currency::try_from_str("TEST2").unwrap();
415        assert_eq!(found.name.as_str(), "Test Currency 2 Overwritten");
416    }
417
418    #[rstest]
419    fn test_new_for_fiat() {
420        let currency = Currency::new("AUD", 2, 36, "Australian dollar", CurrencyType::Fiat);
421        assert_eq!(currency, currency);
422        assert_eq!(currency.code.as_str(), "AUD");
423        assert_eq!(currency.precision, 2);
424        assert_eq!(currency.iso4217, 36);
425        assert_eq!(currency.name.as_str(), "Australian dollar");
426        assert_eq!(currency.currency_type, CurrencyType::Fiat);
427    }
428
429    #[rstest]
430    fn test_new_for_crypto() {
431        let currency = Currency::new("ETH", 8, 0, "Ether", CurrencyType::Crypto);
432        assert_eq!(currency, currency);
433        assert_eq!(currency.code.as_str(), "ETH");
434        assert_eq!(currency.precision, 8);
435        assert_eq!(currency.iso4217, 0);
436        assert_eq!(currency.name.as_str(), "Ether");
437        assert_eq!(currency.currency_type, CurrencyType::Crypto);
438    }
439
440    #[rstest]
441    fn test_try_from_str_valid() {
442        let test_currency = Currency::new("TEST", 2, 999, "Test Currency", CurrencyType::Fiat);
443        Currency::register(test_currency, true).unwrap();
444
445        let currency = Currency::try_from_str("TEST");
446        assert!(currency.is_some());
447        assert_eq!(currency.unwrap(), test_currency);
448    }
449
450    #[rstest]
451    fn test_try_from_str_invalid() {
452        let invalid_currency = Currency::try_from_str("INVALID");
453        assert!(invalid_currency.is_none());
454    }
455
456    #[rstest]
457    fn test_equality() {
458        let currency1 = Currency::new("USD", 2, 840, "United States dollar", CurrencyType::Fiat);
459        let currency2 = Currency::new("USD", 2, 840, "United States dollar", CurrencyType::Fiat);
460        assert_eq!(currency1, currency2);
461    }
462
463    #[rstest]
464    fn test_currency_partial_eq_only_checks_code() {
465        let c1 = Currency::new("ABC", 2, 999, "Currency ABC", CurrencyType::Fiat);
466        let c2 = Currency::new("ABC", 8, 100, "Completely Different", CurrencyType::Crypto);
467
468        assert_eq!(c1, c2, "Should be equal if 'code' is the same");
469    }
470
471    #[rstest]
472    fn test_is_fiat() {
473        let currency = Currency::new("TESTFIAT", 2, 840, "Test Fiat", CurrencyType::Fiat);
474        Currency::register(currency, true).unwrap();
475
476        let result = Currency::is_fiat("TESTFIAT");
477        assert!(result.is_ok());
478        assert!(
479            result.unwrap(),
480            "Expected TESTFIAT to be recognized as fiat"
481        );
482    }
483
484    #[rstest]
485    fn test_is_crypto() {
486        let currency = Currency::new("TESTCRYPTO", 8, 0, "Test Crypto", CurrencyType::Crypto);
487        Currency::register(currency, true).unwrap();
488
489        let result = Currency::is_crypto("TESTCRYPTO");
490        assert!(result.is_ok());
491        assert!(
492            result.unwrap(),
493            "Expected TESTCRYPTO to be recognized as crypto"
494        );
495    }
496
497    #[rstest]
498    fn test_is_commodity_backed() {
499        let currency = Currency::new("TESTGOLD", 5, 0, "Test Gold", CurrencyType::CommodityBacked);
500        Currency::register(currency, true).unwrap();
501
502        let result = Currency::is_commodity_backed("TESTGOLD");
503        assert!(result.is_ok());
504        assert!(
505            result.unwrap(),
506            "Expected TESTGOLD to be recognized as commodity-backed"
507        );
508    }
509
510    #[rstest]
511    fn test_is_fiat_unknown_currency() {
512        let err = Currency::is_fiat("NON_EXISTENT").unwrap_err();
513        assert_eq!(
514            err,
515            CurrencyLookupError::UnknownCode {
516                code: "NON_EXISTENT".to_string()
517            }
518        );
519        assert_eq!(err.to_string(), "Unknown currency: NON_EXISTENT");
520    }
521
522    #[rstest]
523    #[case(Currency::is_fiat)]
524    #[case(Currency::is_crypto)]
525    #[case(Currency::is_commodity_backed)]
526    fn test_currency_classification_unknown_code_returns_typed_error(
527        #[case] classify: fn(&str) -> Result<bool, CurrencyLookupError>,
528    ) {
529        let err = classify("UNKNOWN_CLASSIFICATION").unwrap_err();
530
531        assert_eq!(
532            err,
533            CurrencyLookupError::UnknownCode {
534                code: "UNKNOWN_CLASSIFICATION".to_string()
535            }
536        );
537        assert_eq!(err.to_string(), "Unknown currency: UNKNOWN_CLASSIFICATION");
538    }
539
540    #[rstest]
541    fn test_from_str_unknown_code_returns_typed_error() {
542        let err = Currency::from_str("UNKNOWN_FROM_STR").unwrap_err();
543
544        assert_eq!(
545            err,
546            CurrencyLookupError::UnknownCode {
547                code: "UNKNOWN_FROM_STR".to_string()
548            }
549        );
550        assert_eq!(err.to_string(), "Unknown currency: UNKNOWN_FROM_STR");
551    }
552
553    #[rstest]
554    fn test_currency_lookup_error_legacy_lock_failure_display() {
555        let err = CurrencyLookupError::LockFailure {
556            reason: "legacy lock failure".to_string(),
557        };
558
559        assert_eq!(
560            err,
561            CurrencyLookupError::LockFailure {
562                reason: "legacy lock failure".to_string()
563            }
564        );
565        assert_eq!(
566            err.to_string(),
567            "Failed to acquire lock on `CURRENCY_MAP`: legacy lock failure"
568        );
569    }
570
571    #[rstest]
572    #[should_panic(expected = "Unknown currency: UNKNOWN_FROM_PANIC")]
573    fn test_from_unknown_code_panics_with_display_error() {
574        let _: Currency = Currency::from("UNKNOWN_FROM_PANIC");
575    }
576
577    #[rstest]
578    fn test_serialization_deserialization() {
579        let currency = Currency::USD();
580        let serialized = serde_json::to_string(&currency).unwrap();
581        let deserialized: Currency = serde_json::from_str(&serialized).unwrap();
582        assert_eq!(currency, deserialized);
583    }
584
585    #[rstest]
586    fn test_get_or_create_crypto_existing() {
587        // Test with an existing currency (BTC is in the default map)
588        let currency = Currency::get_or_create_crypto("BTC");
589        assert_eq!(currency.code.as_str(), "BTC");
590        assert_eq!(currency.currency_type, CurrencyType::Crypto);
591    }
592
593    #[rstest]
594    fn test_get_or_create_crypto_new() {
595        // Test with a non-existent currency code
596        let currency = Currency::get_or_create_crypto("NEWCOIN");
597        assert_eq!(currency.code.as_str(), "NEWCOIN");
598        assert_eq!(currency.precision, 8);
599        assert_eq!(currency.iso4217, 0);
600        assert_eq!(currency.name.as_str(), "NEWCOIN");
601        assert_eq!(currency.currency_type, CurrencyType::Crypto);
602
603        // Verify it was registered and can be retrieved
604        let retrieved = Currency::try_from_str("NEWCOIN");
605        assert!(retrieved.is_some());
606        assert_eq!(retrieved.unwrap(), currency);
607    }
608
609    #[rstest]
610    fn test_get_or_create_crypto_idempotent() {
611        // First call creates and registers
612        let currency1 = Currency::get_or_create_crypto("TESTCOIN");
613
614        // Second call should retrieve the same currency
615        let currency2 = Currency::get_or_create_crypto("TESTCOIN");
616
617        assert_eq!(currency1, currency2);
618    }
619
620    #[rstest]
621    fn test_get_or_create_crypto_with_ustr() {
622        use ustr::Ustr;
623
624        // Test that it works with Ustr (via AsRef<str>)
625        let code = Ustr::from("USTRCOIN");
626        let currency = Currency::get_or_create_crypto(code);
627        assert_eq!(currency.code.as_str(), "USTRCOIN");
628        assert_eq!(currency.currency_type, CurrencyType::Crypto);
629    }
630
631    #[rstest]
632    fn test_get_or_create_crypto_with_context_valid() {
633        let result = Currency::get_or_create_crypto_with_context("BTC", Some("test context"));
634        assert_eq!(result, Currency::BTC());
635    }
636
637    #[rstest]
638    fn test_get_or_create_crypto_with_context_empty() {
639        let result = Currency::get_or_create_crypto_with_context("", Some("test context"));
640        assert_eq!(result, Currency::USDT());
641    }
642
643    #[rstest]
644    fn test_get_or_create_crypto_with_context_whitespace() {
645        let result = Currency::get_or_create_crypto_with_context("  ", Some("test context"));
646        assert_eq!(result, Currency::USDT());
647    }
648
649    #[rstest]
650    fn test_get_or_create_crypto_with_context_unknown() {
651        // Unknown codes should create a new Currency, preserving newly listed assets
652        let result = Currency::get_or_create_crypto_with_context("NEWCOIN", Some("test context"));
653        assert_eq!(result.code.as_str(), "NEWCOIN");
654        assert_eq!(result.precision, 8);
655    }
656}