1pub mod error;
8
9use std::collections::HashMap;
10use std::path::Path;
11
12use serde::{Deserialize, Serialize};
13
14pub use error::SymbolError;
15
16pub type Result<T> = std::result::Result<T, SymbolError>;
18
19#[derive(Deserialize)]
23struct TomlFile {
24 symbol: Vec<SymbolEntry>,
25}
26
27#[derive(Deserialize)]
29struct SymbolEntry {
30 canonical: String,
31 #[serde(default)]
32 aliases: Vec<String>,
33 pip_position: u16,
34 digits: u16,
35 category: String,
36 #[serde(default)]
37 base_currency: Option<String>,
38 #[serde(default)]
39 quote_currency: Option<String>,
40 #[serde(default)]
41 pnl_currency: Option<String>,
42 lot_base_units: i64,
43 lot_step_units: i64,
44 #[serde(default = "default_lot_min_steps")]
45 lot_min_steps: i64,
46 #[serde(default)]
47 lot_max_steps: i64,
48}
49
50fn default_lot_min_steps() -> i64 {
51 1
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct SymbolSpec {
59 pub canonical: String,
61 pub pip_position: u16,
63 pub digits: u16,
65 pub category: String,
67 pub lot_base_units: i64,
69 pub lot_step_units: i64,
71 pub lot_min_steps: i64,
73 pub lot_max_steps: i64,
75}
76
77#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
79pub struct SymbolCurrencyMetadata {
80 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub base_currency: Option<String>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub quote_currency: Option<String>,
86 #[serde(default, skip_serializing_if = "String::is_empty")]
88 pub pnl_currency: String,
89}
90
91impl SymbolSpec {
92 pub fn lot_step(&self) -> f64 {
94 self.lot_step_units as f64 / self.lot_base_units as f64
95 }
96
97 pub fn lot_min(&self) -> f64 {
99 self.lot_min_steps as f64 * self.lot_step()
100 }
101
102 pub fn lot_max(&self) -> f64 {
104 if self.lot_max_steps == 0 {
105 0.0
106 } else {
107 self.lot_max_steps as f64 * self.lot_step()
108 }
109 }
110
111 pub fn to_pips(&self, p1: f64, p2: f64) -> f64 {
113 let scale = 10i64.pow(self.digits as u32);
114 let pip_scale = 10i64.pow((self.digits - self.pip_position) as u32);
115 let d1 = (p1 * scale as f64).round() as i64;
116 let d2 = (p2 * scale as f64).round() as i64;
117 (d1 - d2) as f64 / pip_scale as f64
118 }
119
120 pub fn add_pips(&self, price: f64, pips: f64) -> f64 {
122 let scale = 10i64.pow(self.digits as u32);
123 let pip_scale = 10i64.pow((self.digits - self.pip_position) as u32);
124 let d_price = (price * scale as f64).round();
125 let d_pips = pip_scale as f64 * pips;
126 (d_price + d_pips) / scale as f64
127 }
128}
129
130#[derive(Debug)]
134pub struct SymbolRegistry {
135 symbols: HashMap<String, SymbolSpec>,
137 currency_metadata: HashMap<String, SymbolCurrencyMetadata>,
139 alias_map: HashMap<String, String>,
141}
142
143impl SymbolRegistry {
144 pub fn load(path: impl AsRef<Path>) -> Result<Self> {
146 let content = std::fs::read_to_string(path)?;
147 Self::from_toml(&content)
148 }
149
150 pub fn from_toml(content: &str) -> Result<Self> {
152 let file: TomlFile = toml::from_str(content)?;
153
154 let mut symbols = HashMap::with_capacity(file.symbol.len());
155 let mut currency_metadata = HashMap::with_capacity(file.symbol.len());
156 let mut alias_map = HashMap::new();
157
158 for entry in file.symbol {
159 let canonical = entry.canonical.to_lowercase();
160
161 if symbols.contains_key(&canonical) {
163 return Err(SymbolError::DuplicateCanonical(canonical));
164 }
165
166 if entry.pip_position > entry.digits {
168 return Err(SymbolError::InvalidDigits {
169 symbol: canonical,
170 pip: entry.pip_position,
171 digits: entry.digits,
172 });
173 }
174
175 if entry.lot_step_units <= 0 || entry.lot_step_units > entry.lot_base_units {
177 return Err(SymbolError::InvalidLotSpec {
178 symbol: canonical,
179 step: entry.lot_step_units,
180 base: entry.lot_base_units,
181 });
182 }
183
184 let category = entry.category.to_ascii_lowercase();
185 let base_currency = normalize_optional_currency(
186 &canonical,
187 "base_currency",
188 entry.base_currency.as_deref(),
189 )?;
190 let quote_currency = normalize_optional_currency(
191 &canonical,
192 "quote_currency",
193 entry.quote_currency.as_deref(),
194 )?;
195 let pnl_currency =
196 required_currency(&canonical, "pnl_currency", entry.pnl_currency.as_deref())?;
197
198 if category == "forex" {
199 let base =
200 base_currency
201 .as_ref()
202 .ok_or_else(|| SymbolError::MissingCurrencyMetadata {
203 symbol: canonical.clone(),
204 field: "base_currency",
205 })?;
206 let quote = quote_currency.as_ref().ok_or_else(|| {
207 SymbolError::MissingCurrencyMetadata {
208 symbol: canonical.clone(),
209 field: "quote_currency",
210 }
211 })?;
212 if base == quote {
213 return Err(SymbolError::DuplicateForexCurrency {
214 symbol: canonical,
215 currency: base.clone(),
216 });
217 }
218 if &pnl_currency != quote {
219 return Err(SymbolError::ForexPnlCurrencyMismatch {
220 symbol: canonical,
221 quote: quote.clone(),
222 pnl: pnl_currency,
223 });
224 }
225 }
226
227 let stripped_canonical = strip_separators(&canonical);
229 if stripped_canonical != canonical {
230 alias_map.insert(stripped_canonical, canonical.clone());
231 }
232
233 for alias in &entry.aliases {
235 let key = strip_separators(&alias.to_lowercase());
236 if let Some(existing) = alias_map.get(&key) {
237 if *existing != canonical {
238 return Err(SymbolError::DuplicateAlias {
239 alias: key,
240 existing: existing.clone(),
241 new: canonical.clone(),
242 });
243 }
244 continue;
246 }
247 alias_map.insert(key, canonical.clone());
248 }
249
250 let spec = SymbolSpec {
251 canonical: canonical.clone(),
252 pip_position: entry.pip_position,
253 digits: entry.digits,
254 category,
255 lot_base_units: entry.lot_base_units,
256 lot_step_units: entry.lot_step_units,
257 lot_min_steps: entry.lot_min_steps,
258 lot_max_steps: entry.lot_max_steps,
259 };
260
261 currency_metadata.insert(
262 canonical.clone(),
263 SymbolCurrencyMetadata {
264 base_currency,
265 quote_currency,
266 pnl_currency,
267 },
268 );
269 symbols.insert(canonical, spec);
270 }
271
272 Ok(Self {
273 symbols,
274 currency_metadata,
275 alias_map,
276 })
277 }
278
279 pub fn empty() -> Self {
281 Self {
282 symbols: HashMap::new(),
283 currency_metadata: HashMap::new(),
284 alias_map: HashMap::new(),
285 }
286 }
287
288 pub fn normalize(&self, raw: &str) -> Option<&str> {
290 let key = strip_separators(&raw.to_lowercase());
291
292 if let Some(spec) = self.symbols.get(&key) {
294 return Some(&spec.canonical);
295 }
296
297 if let Some(canonical) = self.alias_map.get(&key) {
299 return Some(canonical.as_str());
300 }
301
302 None
303 }
304
305 pub fn normalize_or_passthrough(&self, raw: &str) -> String {
307 match self.normalize(raw) {
308 Some(canonical) => canonical.to_owned(),
309 None => strip_separators(&raw.to_lowercase()),
310 }
311 }
312
313 pub fn spec(&self, canonical: &str) -> Option<&SymbolSpec> {
315 self.symbols.get(canonical)
316 }
317
318 pub fn spec_by_any(&self, raw: &str) -> Option<&SymbolSpec> {
320 let canonical = self.normalize(raw)?;
321 self.symbols.get(canonical)
322 }
323
324 pub fn currency_metadata(&self, canonical: &str) -> Option<&SymbolCurrencyMetadata> {
326 self.currency_metadata.get(canonical)
327 }
328
329 pub fn currency_metadata_by_any(&self, raw: &str) -> Option<&SymbolCurrencyMetadata> {
331 let canonical = self.normalize(raw)?;
332 self.currency_metadata.get(canonical)
333 }
334
335 pub fn pnl_currency(&self, canonical: &str) -> Option<&str> {
337 self.currency_metadata
338 .get(canonical)
339 .map(|metadata| metadata.pnl_currency.as_str())
340 }
341
342 pub fn digits(&self, canonical: &str) -> Option<u16> {
344 self.symbols.get(canonical).map(|s| s.digits)
345 }
346
347 pub fn lot_step(&self, canonical: &str) -> Option<f64> {
349 self.symbols.get(canonical).map(|s| s.lot_step())
350 }
351
352 pub fn canonical_names(&self) -> Vec<&str> {
354 let mut names: Vec<&str> = self.symbols.keys().map(|s| s.as_str()).collect();
355 names.sort();
356 names
357 }
358
359 pub fn entries(&self) -> Vec<(&SymbolSpec, &SymbolCurrencyMetadata)> {
361 self.canonical_names()
362 .into_iter()
363 .filter_map(|canonical| {
364 self.symbols
365 .get(canonical)
366 .zip(self.currency_metadata.get(canonical))
367 })
368 .collect()
369 }
370
371 pub fn is_known(&self, raw: &str) -> bool {
373 self.normalize(raw).is_some()
374 }
375
376 pub fn len(&self) -> usize {
378 self.symbols.len()
379 }
380
381 pub fn is_empty(&self) -> bool {
383 self.symbols.is_empty()
384 }
385
386 pub fn symbols_in_category(&self, category: &str) -> Vec<&SymbolSpec> {
388 let cat = category.to_lowercase();
389 self.symbols
390 .values()
391 .filter(|s| s.category == cat)
392 .collect()
393 }
394
395 pub fn suggest(&self, raw: &str, max_distance: usize, limit: usize) -> Vec<(&str, usize)> {
400 if limit == 0 {
401 return Vec::new();
402 }
403
404 let key = strip_separators(&raw.to_lowercase());
405 if key.is_empty() {
406 return Vec::new();
407 }
408
409 if self.normalize(raw).is_some() {
411 return Vec::new();
412 }
413
414 let mut candidates: Vec<(&str, usize)> = self
415 .symbols
416 .keys()
417 .filter_map(|canonical| {
418 let d = levenshtein(&key, canonical);
419 if d <= max_distance {
420 Some((canonical.as_str(), d))
421 } else {
422 None
423 }
424 })
425 .collect();
426
427 for (alias, canonical) in &self.alias_map {
429 let d = levenshtein(&key, alias);
430 if d <= max_distance && !candidates.iter().any(|(c, _)| *c == canonical.as_str()) {
431 candidates.push((canonical.as_str(), d));
432 }
433 }
434
435 candidates.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(b.0)));
436 candidates.truncate(limit);
437 candidates
438 }
439}
440
441pub fn normalize_currency_code(raw: &str) -> Option<String> {
445 let normalized = raw.trim().to_ascii_uppercase();
446 if normalized.len() == 3 && normalized.bytes().all(|byte| byte.is_ascii_uppercase()) {
447 Some(normalized)
448 } else {
449 None
450 }
451}
452
453fn normalize_optional_currency(
454 symbol: &str,
455 field: &'static str,
456 value: Option<&str>,
457) -> Result<Option<String>> {
458 value
459 .map(|raw| {
460 normalize_currency_code(raw).ok_or_else(|| SymbolError::InvalidCurrencyCode {
461 symbol: symbol.to_owned(),
462 field,
463 value: raw.to_owned(),
464 })
465 })
466 .transpose()
467}
468
469fn required_currency(symbol: &str, field: &'static str, value: Option<&str>) -> Result<String> {
470 let raw = value.ok_or_else(|| SymbolError::MissingCurrencyMetadata {
471 symbol: symbol.to_owned(),
472 field,
473 })?;
474 normalize_currency_code(raw).ok_or_else(|| SymbolError::InvalidCurrencyCode {
475 symbol: symbol.to_owned(),
476 field,
477 value: raw.to_owned(),
478 })
479}
480
481fn strip_separators(s: &str) -> String {
483 s.chars()
484 .filter(|c| !matches!(c, '/' | '-' | '_' | ' '))
485 .collect()
486}
487
488fn levenshtein(a: &str, b: &str) -> usize {
490 let a: Vec<char> = a.chars().collect();
491 let b: Vec<char> = b.chars().collect();
492 let (m, n) = (a.len(), b.len());
493
494 let mut prev: Vec<usize> = (0..=n).collect();
496 let mut curr = vec![0usize; n + 1];
497
498 for i in 1..=m {
499 curr[0] = i;
500 for j in 1..=n {
501 let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
502 curr[j] = (prev[j] + 1) .min(curr[j - 1] + 1) .min(prev[j - 1] + cost); }
506 std::mem::swap(&mut prev, &mut curr);
507 }
508
509 prev[n]
510}
511
512#[cfg(test)]
515mod tests {
516 use super::*;
517
518 fn minimal_toml() -> &'static str {
519 r#"
520[[symbol]]
521canonical = "eurusd"
522aliases = ["eur/usd", "eur-usd", "eur_usd"]
523pip_position = 4
524digits = 5
525category = "forex"
526base_currency = "EUR"
527quote_currency = "USD"
528pnl_currency = "USD"
529lot_base_units = 100000
530lot_step_units = 1000
531lot_min_steps = 1
532lot_max_steps = 0
533
534[[symbol]]
535canonical = "xauusd"
536aliases = ["gold", "xau/usd", "xau-usd"]
537pip_position = 1
538digits = 2
539category = "metal"
540base_currency = "XAU"
541quote_currency = "USD"
542pnl_currency = "USD"
543lot_base_units = 100
544lot_step_units = 1
545lot_min_steps = 1
546lot_max_steps = 0
547
548[[symbol]]
549canonical = "us100"
550aliases = ["nas100", "nasdaq", "us tech 100"]
551pip_position = 1
552digits = 2
553category = "index"
554pnl_currency = "USD"
555lot_base_units = 1
556lot_step_units = 1
557lot_min_steps = 1
558lot_max_steps = 0
559"#
560 }
561
562 #[test]
563 fn load_from_toml_string() {
564 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
565 assert_eq!(reg.len(), 3);
566 assert!(reg.spec("eurusd").is_some());
567 assert!(reg.spec("xauusd").is_some());
568 assert!(reg.spec("us100").is_some());
569 }
570
571 #[test]
572 fn normalize_canonical_name() {
573 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
574 assert_eq!(reg.normalize("eurusd"), Some("eurusd"));
575 }
576
577 #[test]
578 fn normalize_alias() {
579 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
580 assert_eq!(reg.normalize("nasdaq"), Some("us100"));
581 assert_eq!(reg.normalize("gold"), Some("xauusd"));
582 assert_eq!(reg.normalize("nas100"), Some("us100"));
583 }
584
585 #[test]
586 fn normalize_with_separators() {
587 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
588 assert_eq!(reg.normalize("EUR/USD"), Some("eurusd"));
589 assert_eq!(reg.normalize("XAU-USD"), Some("xauusd"));
590 assert_eq!(reg.normalize("eur_usd"), Some("eurusd"));
591 assert_eq!(reg.normalize("us tech 100"), Some("us100"));
592 }
593
594 #[test]
595 fn normalize_case_insensitive() {
596 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
597 assert_eq!(reg.normalize("EURUSD"), Some("eurusd"));
598 assert_eq!(reg.normalize("EurUsd"), Some("eurusd"));
599 assert_eq!(reg.normalize("GOLD"), Some("xauusd"));
600 assert_eq!(reg.normalize("NAS100"), Some("us100"));
601 }
602
603 #[test]
604 fn normalize_unknown_returns_none() {
605 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
606 assert_eq!(reg.normalize("foobar"), None);
607 }
608
609 #[test]
610 fn passthrough_unknown() {
611 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
612 assert_eq!(reg.normalize_or_passthrough("foobar"), "foobar");
613 assert_eq!(reg.normalize_or_passthrough("FOO/BAR"), "foobar");
614 }
615
616 #[test]
617 fn spec_lookup() {
618 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
619 let spec = reg.spec("eurusd").unwrap();
620 assert_eq!(spec.pip_position, 4);
621 assert_eq!(spec.digits, 5);
622 assert_eq!(spec.category, "forex");
623 assert_eq!(spec.lot_base_units, 100_000);
624 assert_eq!(spec.lot_step_units, 1_000);
625 }
626
627 #[test]
628 fn spec_by_any_alias() {
629 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
630 let spec = reg.spec_by_any("gold").unwrap();
631 assert_eq!(spec.canonical, "xauusd");
632 assert_eq!(spec.category, "metal");
633 }
634
635 #[test]
636 fn empty_registry() {
637 let reg = SymbolRegistry::empty();
638 assert_eq!(reg.len(), 0);
639 assert!(reg.is_empty());
640 assert_eq!(reg.normalize("eurusd"), None);
641 }
642
643 #[test]
644 fn canonical_names_list() {
645 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
646 let names = reg.canonical_names();
647 assert_eq!(names, vec!["eurusd", "us100", "xauusd"]);
648 }
649
650 #[test]
651 fn symbols_in_category() {
652 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
653 let forex = reg.symbols_in_category("forex");
654 assert_eq!(forex.len(), 1);
655 assert_eq!(forex[0].canonical, "eurusd");
656 }
657
658 #[test]
659 fn is_known_check() {
660 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
661 assert!(reg.is_known("eurusd"));
662 assert!(reg.is_known("GOLD"));
663 assert!(reg.is_known("NAS/100"));
664 assert!(!reg.is_known("foobar"));
665 }
666
667 #[test]
668 fn duplicate_canonical_error() {
669 let toml = r#"
670[[symbol]]
671canonical = "eurusd"
672aliases = []
673pip_position = 4
674digits = 5
675category = "forex"
676base_currency = "EUR"
677quote_currency = "USD"
678pnl_currency = "USD"
679lot_base_units = 100000
680lot_step_units = 1000
681
682[[symbol]]
683canonical = "eurusd"
684aliases = []
685pip_position = 4
686digits = 5
687category = "forex"
688base_currency = "EUR"
689quote_currency = "USD"
690pnl_currency = "USD"
691lot_base_units = 100000
692lot_step_units = 1000
693"#;
694 let err = SymbolRegistry::from_toml(toml).unwrap_err();
695 assert!(matches!(err, SymbolError::DuplicateCanonical(ref s) if s == "eurusd"));
696 }
697
698 #[test]
699 fn duplicate_alias_error() {
700 let toml = r#"
701[[symbol]]
702canonical = "us100"
703aliases = ["nasdaq"]
704pip_position = 1
705digits = 2
706category = "index"
707pnl_currency = "USD"
708lot_base_units = 1
709lot_step_units = 1
710
711[[symbol]]
712canonical = "us500"
713aliases = ["nasdaq"]
714pip_position = 1
715digits = 2
716category = "index"
717pnl_currency = "USD"
718lot_base_units = 1
719lot_step_units = 1
720"#;
721 let err = SymbolRegistry::from_toml(toml).unwrap_err();
722 assert!(matches!(err, SymbolError::DuplicateAlias { .. }));
723 }
724
725 #[test]
726 fn invalid_lot_spec_error() {
727 let toml = r#"
728[[symbol]]
729canonical = "bad"
730aliases = []
731pip_position = 4
732digits = 5
733category = "forex"
734base_currency = "EUR"
735quote_currency = "USD"
736pnl_currency = "USD"
737lot_base_units = 100000
738lot_step_units = 0
739"#;
740 let err = SymbolRegistry::from_toml(toml).unwrap_err();
741 assert!(matches!(err, SymbolError::InvalidLotSpec { .. }));
742 }
743
744 #[test]
745 fn invalid_digits_error() {
746 let toml = r#"
747[[symbol]]
748canonical = "bad"
749aliases = []
750pip_position = 6
751digits = 5
752category = "forex"
753base_currency = "EUR"
754quote_currency = "USD"
755pnl_currency = "USD"
756lot_base_units = 100000
757lot_step_units = 1000
758"#;
759 let err = SymbolRegistry::from_toml(toml).unwrap_err();
760 assert!(matches!(err, SymbolError::InvalidDigits { .. }));
761 }
762
763 #[test]
764 fn lot_step_forex() {
765 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
766 let spec = reg.spec("eurusd").unwrap();
767 assert!((spec.lot_step() - 0.01).abs() < f64::EPSILON);
768 }
769
770 #[test]
771 fn lot_step_gold() {
772 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
773 let spec = reg.spec("xauusd").unwrap();
774 assert!((spec.lot_step() - 0.01).abs() < f64::EPSILON);
775 }
776
777 #[test]
778 fn lot_min_derived() {
779 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
780 let spec = reg.spec("eurusd").unwrap();
781 assert!((spec.lot_min() - 0.01).abs() < f64::EPSILON);
782 }
783
784 #[test]
785 fn lot_max_no_limit() {
786 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
787 let spec = reg.spec("eurusd").unwrap();
788 assert!((spec.lot_max() - 0.0).abs() < f64::EPSILON);
789 }
790
791 #[test]
792 fn to_pips_eurusd() {
793 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
794 let spec = reg.spec("eurusd").unwrap();
795 let pips = spec.to_pips(1.10500, 1.10000);
797 assert!((pips - 50.0).abs() < 0.001);
798 }
799
800 #[test]
801 fn to_pips_gold() {
802 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
803 let spec = reg.spec("xauusd").unwrap();
804 let pips = spec.to_pips(2050.50, 2050.00);
806 assert!((pips - 5.0).abs() < 0.001);
807 }
808
809 #[test]
810 fn add_pips_eurusd() {
811 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
812 let spec = reg.spec("eurusd").unwrap();
813 let result = spec.add_pips(1.10000, 30.0);
814 assert!((result - 1.10300).abs() < 1e-10);
815 }
816
817 #[test]
818 fn add_pips_negative() {
819 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
820 let spec = reg.spec("eurusd").unwrap();
821 let result = spec.add_pips(1.10000, -15.0);
822 assert!((result - 1.09850).abs() < 1e-10);
823 }
824
825 #[test]
826 fn digits_convenience() {
827 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
828 assert_eq!(reg.digits("eurusd"), Some(5));
829 assert_eq!(reg.digits("xauusd"), Some(2));
830 assert_eq!(reg.digits("unknown"), None);
831 }
832
833 #[test]
834 fn lot_step_convenience() {
835 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
836 assert!((reg.lot_step("eurusd").unwrap() - 0.01).abs() < f64::EPSILON);
837 assert!(reg.lot_step("unknown").is_none());
838 }
839
840 #[test]
843 fn levenshtein_identical() {
844 assert_eq!(super::levenshtein("eurusd", "eurusd"), 0);
845 }
846
847 #[test]
848 fn levenshtein_one_deletion() {
849 assert_eq!(super::levenshtein("adusd", "audusd"), 1);
851 }
852
853 #[test]
854 fn levenshtein_one_substitution() {
855 assert_eq!(super::levenshtein("euruds", "eurusd"), 2);
859 assert_eq!(super::levenshtein("eurxsd", "eurusd"), 1);
861 }
862
863 #[test]
864 fn levenshtein_empty() {
865 assert_eq!(super::levenshtein("", "abc"), 3);
866 assert_eq!(super::levenshtein("abc", ""), 3);
867 assert_eq!(super::levenshtein("", ""), 0);
868 }
869
870 #[test]
873 fn suggest_single_deletion_typo() {
874 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
875 let suggestions = reg.suggest("euusd", 2, 5);
878 assert!(suggestions.iter().any(|(name, _)| *name == "eurusd"));
879 }
880
881 #[test]
882 fn suggest_substitution_typo() {
883 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
884 let suggestions = reg.suggest("eurxsd", 1, 5);
886 assert_eq!(suggestions.len(), 1);
887 assert_eq!(suggestions[0], ("eurusd", 1));
888 }
889
890 #[test]
891 fn suggest_returns_empty_for_known_symbol() {
892 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
893 let suggestions = reg.suggest("eurusd", 2, 5);
894 assert!(suggestions.is_empty());
895 }
896
897 #[test]
898 fn suggest_returns_empty_for_known_alias() {
899 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
900 let suggestions = reg.suggest("gold", 2, 5);
901 assert!(suggestions.is_empty());
902 }
903
904 #[test]
905 fn suggest_returns_empty_when_too_distant() {
906 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
907 let suggestions = reg.suggest("zzzzzzzzz", 1, 5);
908 assert!(suggestions.is_empty());
909 }
910
911 #[test]
912 fn suggest_respects_limit() {
913 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
914 let suggestions = reg.suggest("usd", 3, 1);
915 assert!(suggestions.len() <= 1);
916 }
917
918 #[test]
919 fn suggest_sorted_by_distance_then_name() {
920 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
921 let suggestions = reg.suggest("euusd", 2, 10);
923 assert!(!suggestions.is_empty());
924 assert_eq!(suggestions[0].0, "eurusd");
925 assert_eq!(suggestions[0].1, 1);
926 for w in suggestions.windows(2) {
928 assert!(w[0].1 < w[1].1 || (w[0].1 == w[1].1 && w[0].0 <= w[1].0),);
929 }
930 }
931
932 #[test]
933 fn suggest_empty_input() {
934 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
935 let suggestions = reg.suggest("", 2, 5);
936 assert!(suggestions.is_empty());
937 }
938
939 #[test]
940 fn suggest_zero_limit() {
941 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
942 let suggestions = reg.suggest("eurxsd", 2, 0);
943 assert!(suggestions.is_empty());
944 }
945
946 #[test]
947 fn suggest_matches_via_alias_proximity() {
948 let reg = SymbolRegistry::from_toml(minimal_toml()).unwrap();
949 let suggestions = reg.suggest("golds", 1, 5);
951 assert!(suggestions.iter().any(|(name, _)| *name == "xauusd"));
952 }
953}