1use crate::common::decimals::{PRICE_SCALE, Price, Volume};
24use crate::common::errors::{ConnectorError, ValueError};
25use crate::common::ids::{AccountId, AssetId, SymbolCategoryId, SymbolId};
26use crate::common::time::Timestamp;
27use crate::open_api::client::OpenApiClient;
28use crate::open_api::messages::{
29 ProtoOaArchivedSymbol, ProtoOaAsset, ProtoOaAssetListReq, ProtoOaLightSymbol, ProtoOaSymbol,
30 ProtoOaSymbolByIdReq, ProtoOaSymbolsListReq, ProtoOaTradingMode,
31};
32
33const DIGITS: &str = "digits";
34
35fn digits(raw: i32) -> Result<u32, ValueError> {
36 u32::try_from(raw).map_err(|_| ValueError::OutOfRange { kind: DIGITS })
37}
38
39fn collect<W, T>(items: Vec<W>) -> Result<Vec<T>, ConnectorError>
40where
41 T: TryFrom<W, Error = ValueError>,
42{
43 items
44 .into_iter()
45 .map(|item| T::try_from(item).map_err(ConnectorError::from))
46 .collect()
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51#[non_exhaustive]
52pub struct Asset {
53 pub id: AssetId,
55 pub name: String,
57 pub display_name: Option<String>,
59 pub digits: Option<u32>,
61}
62
63impl TryFrom<ProtoOaAsset> for Asset {
64 type Error = ValueError;
65
66 fn try_from(asset: ProtoOaAsset) -> Result<Self, Self::Error> {
67 Ok(Self {
68 id: AssetId::new(asset.asset_id)?,
69 name: asset.name,
70 display_name: asset.display_name,
71 digits: asset.digits.map(digits).transpose()?,
72 })
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Hash)]
78#[non_exhaustive]
79pub struct LightSymbol {
80 pub id: SymbolId,
82 pub name: Option<String>,
84 pub enabled: bool,
86 pub base_asset: Option<AssetId>,
88 pub quote_asset: Option<AssetId>,
90 pub category: Option<SymbolCategoryId>,
92 pub description: Option<String>,
94}
95
96impl TryFrom<ProtoOaLightSymbol> for LightSymbol {
97 type Error = ValueError;
98
99 fn try_from(symbol: ProtoOaLightSymbol) -> Result<Self, Self::Error> {
100 Ok(Self {
101 id: SymbolId::new(symbol.symbol_id)?,
102 name: symbol.symbol_name,
103 enabled: symbol.enabled.unwrap_or(false),
104 base_asset: symbol.base_asset_id.map(AssetId::new).transpose()?,
105 quote_asset: symbol.quote_asset_id.map(AssetId::new).transpose()?,
106 category: symbol
107 .symbol_category_id
108 .map(SymbolCategoryId::new)
109 .transpose()?,
110 description: symbol.description,
111 })
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Hash)]
117#[non_exhaustive]
118pub struct ArchivedSymbol {
119 pub id: SymbolId,
121 pub name: String,
123 pub last_update: Timestamp,
125 pub description: Option<String>,
127}
128
129impl TryFrom<ProtoOaArchivedSymbol> for ArchivedSymbol {
130 type Error = ValueError;
131
132 fn try_from(symbol: ProtoOaArchivedSymbol) -> Result<Self, Self::Error> {
133 Ok(Self {
134 id: SymbolId::new(symbol.symbol_id)?,
135 name: symbol.name,
136 last_update: Timestamp::from_millis(symbol.utc_last_update_timestamp)?,
137 description: symbol.description,
138 })
139 }
140}
141
142#[derive(Debug, Clone, PartialEq, Eq, Default)]
144#[non_exhaustive]
145pub struct SymbolList {
146 pub symbols: Vec<LightSymbol>,
148 pub archived: Vec<ArchivedSymbol>,
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
154#[non_exhaustive]
155pub enum TradingMode {
156 Enabled,
158 DisabledWithoutPendingsExecution,
160 DisabledWithPendingsExecution,
162 CloseOnly,
164}
165
166impl From<ProtoOaTradingMode> for TradingMode {
167 fn from(mode: ProtoOaTradingMode) -> Self {
168 match mode {
169 ProtoOaTradingMode::Enabled => Self::Enabled,
170 ProtoOaTradingMode::DisabledWithoutPendingsExecution => {
171 Self::DisabledWithoutPendingsExecution
172 }
173 ProtoOaTradingMode::DisabledWithPendingsExecution => {
174 Self::DisabledWithPendingsExecution
175 }
176 ProtoOaTradingMode::CloseOnlyMode => Self::CloseOnly,
177 }
178 }
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Hash)]
183#[non_exhaustive]
184pub struct Symbol {
185 pub id: SymbolId,
187 pub digits: u32,
189 pub pip_position: i32,
191 pub min_volume: Option<Volume>,
193 pub max_volume: Option<Volume>,
195 pub step_volume: Option<Volume>,
197 pub lot_size: Option<Volume>,
199 pub trading_mode: TradingMode,
201 pub short_selling: bool,
203 pub measurement_units: Option<String>,
205 pub schedule_time_zone: Option<String>,
207}
208
209impl Symbol {
210 pub fn price(&self, raw: u64) -> Result<Price, ValueError> {
217 Price::from_wire(raw, self.digits)
218 }
219
220 #[must_use]
222 pub const fn has_wire_precision(&self) -> bool {
223 self.digits <= PRICE_SCALE
224 }
225}
226
227impl TryFrom<ProtoOaSymbol> for Symbol {
228 type Error = ValueError;
229
230 fn try_from(symbol: ProtoOaSymbol) -> Result<Self, Self::Error> {
231 let volume = |raw: Option<i64>| raw.map(Volume::from_wire).transpose();
232 Ok(Self {
233 id: SymbolId::new(symbol.symbol_id)?,
234 digits: digits(symbol.digits)?,
235 pip_position: symbol.pip_position,
236 min_volume: volume(symbol.min_volume)?,
237 max_volume: volume(symbol.max_volume)?,
238 step_volume: volume(symbol.step_volume)?,
239 lot_size: volume(symbol.lot_size)?,
240 trading_mode: symbol.trading_mode().into(),
241 short_selling: symbol.enable_short_selling.unwrap_or(false),
242 measurement_units: symbol.measurement_units,
243 schedule_time_zone: symbol.schedule_time_zone,
244 })
245 }
246}
247
248#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
250#[must_use]
251pub struct SymbolsParams {
252 account: AccountId,
253 include_archived: bool,
254}
255
256impl SymbolsParams {
257 pub const fn new(account: AccountId) -> Self {
259 Self {
260 account,
261 include_archived: false,
262 }
263 }
264
265 pub const fn include_archived(mut self, include: bool) -> Self {
267 self.include_archived = include;
268 self
269 }
270
271 #[must_use]
273 pub const fn account(&self) -> AccountId {
274 self.account
275 }
276
277 #[must_use]
279 pub const fn includes_archived(&self) -> bool {
280 self.include_archived
281 }
282}
283
284impl OpenApiClient {
285 pub async fn assets(&self, account: AccountId) -> Result<Vec<Asset>, ConnectorError> {
293 let request = ProtoOaAssetListReq {
294 payload_type: None,
295 ctid_trader_account_id: account.get(),
296 };
297 collect(self.connection().request(&request).await?.asset)
298 }
299
300 pub async fn symbols(&self, params: SymbolsParams) -> Result<SymbolList, ConnectorError> {
308 let request = ProtoOaSymbolsListReq {
309 payload_type: None,
310 ctid_trader_account_id: params.account.get(),
311 include_archived_symbols: Some(params.include_archived),
312 };
313 let response = self.connection().request(&request).await?;
314 Ok(SymbolList {
315 symbols: collect(response.symbol)?,
316 archived: collect(response.archived_symbol)?,
317 })
318 }
319
320 pub async fn symbol_details(
330 &self,
331 account: AccountId,
332 symbols: &[SymbolId],
333 ) -> Result<Vec<Symbol>, ConnectorError> {
334 let request = ProtoOaSymbolByIdReq {
335 payload_type: None,
336 ctid_trader_account_id: account.get(),
337 symbol_id: symbols.iter().map(|symbol| symbol.get()).collect(),
338 };
339 collect(self.connection().request(&request).await?.symbol)
340 }
341}
342
343#[cfg(test)]
344mod tests {
345 use super::{ArchivedSymbol, Asset, LightSymbol, Symbol, SymbolsParams, TradingMode};
346 use crate::common::errors::ValueError;
347 use crate::common::ids::{AccountId, AssetId, SymbolCategoryId};
348 use crate::open_api::messages::{
349 ProtoOaArchivedSymbol, ProtoOaAsset, ProtoOaLightSymbol, ProtoOaSymbol, ProtoOaTradingMode,
350 };
351
352 fn invalid(kind: &'static str, value: i64) -> ValueError {
353 ValueError::InvalidId {
354 kind,
355 value: value.to_string(),
356 }
357 }
358
359 fn wire_asset() -> ProtoOaAsset {
360 ProtoOaAsset {
361 asset_id: 4,
362 name: "EUR".to_owned(),
363 display_name: Some("Euro".to_owned()),
364 digits: Some(2),
365 }
366 }
367
368 #[test]
369 fn asset_is_parsed_from_the_wire() {
370 let asset = Asset::try_from(wire_asset()).expect("asset");
371 assert_eq!(asset.id.get(), 4);
372 assert_eq!(asset.name, "EUR");
373 assert_eq!(asset.display_name.as_deref(), Some("Euro"));
374 assert_eq!(asset.digits, Some(2));
375 let bare = ProtoOaAsset {
376 display_name: None,
377 digits: None,
378 ..wire_asset()
379 };
380 assert_eq!(Asset::try_from(bare).expect("asset").digits, None);
381 }
382
383 #[test]
384 fn asset_values_out_of_range_are_rejected() {
385 let no_id = ProtoOaAsset {
386 asset_id: 0,
387 ..wire_asset()
388 };
389 assert_eq!(Asset::try_from(no_id), Err(invalid("asset id", 0)));
390 let negative = ProtoOaAsset {
391 digits: Some(-1),
392 ..wire_asset()
393 };
394 assert_eq!(
395 Asset::try_from(negative),
396 Err(ValueError::OutOfRange { kind: "digits" })
397 );
398 }
399
400 fn wire_light() -> ProtoOaLightSymbol {
401 ProtoOaLightSymbol {
402 symbol_id: 1,
403 symbol_name: Some("EURUSD".to_owned()),
404 enabled: Some(true),
405 base_asset_id: Some(4),
406 quote_asset_id: Some(11),
407 symbol_category_id: Some(2),
408 description: Some("Euro vs US Dollar".to_owned()),
409 sorting_number: Some(1.0),
410 }
411 }
412
413 #[test]
414 fn light_symbol_is_parsed_from_the_wire() {
415 let symbol = LightSymbol::try_from(wire_light()).expect("symbol");
416 assert_eq!(symbol.id.get(), 1);
417 assert_eq!(symbol.name.as_deref(), Some("EURUSD"));
418 assert!(symbol.enabled);
419 assert_eq!(symbol.base_asset.map(AssetId::get), Some(4));
420 assert_eq!(symbol.quote_asset.map(AssetId::get), Some(11));
421 assert_eq!(symbol.category.map(SymbolCategoryId::get), Some(2));
422 assert_eq!(symbol.description.as_deref(), Some("Euro vs US Dollar"));
423 let bare = LightSymbol::try_from(ProtoOaLightSymbol {
424 symbol_id: 9,
425 ..ProtoOaLightSymbol::default()
426 })
427 .expect("symbol");
428 assert!(!bare.enabled);
429 assert_eq!(bare.base_asset, None);
430 assert_eq!(bare.category, None);
431 }
432
433 #[test]
434 fn light_symbol_ids_out_of_range_are_rejected() {
435 let cases = [
436 (
437 ProtoOaLightSymbol {
438 symbol_id: -3,
439 ..wire_light()
440 },
441 invalid("symbol id", -3),
442 ),
443 (
444 ProtoOaLightSymbol {
445 base_asset_id: Some(0),
446 ..wire_light()
447 },
448 invalid("asset id", 0),
449 ),
450 (
451 ProtoOaLightSymbol {
452 quote_asset_id: Some(-1),
453 ..wire_light()
454 },
455 invalid("asset id", -1),
456 ),
457 (
458 ProtoOaLightSymbol {
459 symbol_category_id: Some(0),
460 ..wire_light()
461 },
462 invalid("symbol category id", 0),
463 ),
464 ];
465 for (wire, error) in cases {
466 assert_eq!(LightSymbol::try_from(wire), Err(error));
467 }
468 }
469
470 #[test]
471 fn archived_symbol_is_parsed_from_the_wire() {
472 let wire = ProtoOaArchivedSymbol {
473 symbol_id: 5,
474 name: "OLD".to_owned(),
475 utc_last_update_timestamp: 1_700_000_000_000,
476 description: None,
477 };
478 let symbol = ArchivedSymbol::try_from(wire.clone()).expect("symbol");
479 assert_eq!(symbol.id.get(), 5);
480 assert_eq!(symbol.name, "OLD");
481 assert_eq!(symbol.last_update.as_millis(), 1_700_000_000_000);
482 let early = ProtoOaArchivedSymbol {
483 utc_last_update_timestamp: -1,
484 ..wire.clone()
485 };
486 assert_eq!(
487 ArchivedSymbol::try_from(early),
488 Err(ValueError::OutOfRange { kind: "timestamp" })
489 );
490 let no_id = ProtoOaArchivedSymbol {
491 symbol_id: 0,
492 ..wire
493 };
494 assert_eq!(
495 ArchivedSymbol::try_from(no_id),
496 Err(invalid("symbol id", 0))
497 );
498 }
499
500 fn wire_symbol() -> ProtoOaSymbol {
501 ProtoOaSymbol {
502 symbol_id: 1,
503 digits: 3,
504 pip_position: 2,
505 enable_short_selling: Some(true),
506 max_volume: Some(1_000_000_000),
507 min_volume: Some(100_000),
508 step_volume: Some(100_000),
509 lot_size: Some(10_000_000),
510 trading_mode: Some(ProtoOaTradingMode::CloseOnlyMode as i32),
511 measurement_units: Some("EUR".to_owned()),
512 schedule_time_zone: Some("UTC".to_owned()),
513 ..ProtoOaSymbol::default()
514 }
515 }
516
517 #[test]
518 fn symbol_details_are_parsed_from_the_wire() {
519 let symbol = Symbol::try_from(wire_symbol()).expect("symbol");
520 assert_eq!(symbol.id.get(), 1);
521 assert_eq!(symbol.digits, 3);
522 assert_eq!(symbol.pip_position, 2);
523 let text = |volume: Option<crate::common::decimals::Volume>| {
524 volume.map(|volume| volume.to_string())
525 };
526 assert_eq!(text(symbol.min_volume).as_deref(), Some("1000.00"));
527 assert_eq!(text(symbol.max_volume).as_deref(), Some("10000000.00"));
528 assert_eq!(text(symbol.step_volume).as_deref(), Some("1000.00"));
529 assert_eq!(text(symbol.lot_size).as_deref(), Some("100000.00"));
530 assert_eq!(symbol.trading_mode, TradingMode::CloseOnly);
531 assert!(symbol.short_selling);
532 assert_eq!(symbol.measurement_units.as_deref(), Some("EUR"));
533 assert_eq!(symbol.schedule_time_zone.as_deref(), Some("UTC"));
534 assert!(symbol.has_wire_precision());
535 assert_eq!(
536 symbol.price(123_456).map(|price| price.to_string()),
537 Ok("1.235".to_owned())
538 );
539 let bare = Symbol::try_from(ProtoOaSymbol {
540 symbol_id: 2,
541 digits: 6,
542 ..ProtoOaSymbol::default()
543 })
544 .expect("symbol");
545 assert_eq!(bare.min_volume, None);
546 assert_eq!(bare.trading_mode, TradingMode::Enabled);
547 assert!(!bare.short_selling);
548 assert!(!bare.has_wire_precision());
549 assert_eq!(bare.price(1), Err(ValueError::TooManyDigits { digits: 6 }));
550 }
551
552 #[test]
553 fn symbol_details_out_of_range_are_rejected() {
554 let no_id = ProtoOaSymbol {
555 symbol_id: 0,
556 ..wire_symbol()
557 };
558 assert_eq!(Symbol::try_from(no_id), Err(invalid("symbol id", 0)));
559 let negative_digits = ProtoOaSymbol {
560 digits: -1,
561 ..wire_symbol()
562 };
563 assert_eq!(
564 Symbol::try_from(negative_digits),
565 Err(ValueError::OutOfRange { kind: "digits" })
566 );
567 for raw in [
568 ProtoOaSymbol {
569 min_volume: Some(-1),
570 ..wire_symbol()
571 },
572 ProtoOaSymbol {
573 max_volume: Some(-1),
574 ..wire_symbol()
575 },
576 ProtoOaSymbol {
577 step_volume: Some(-1),
578 ..wire_symbol()
579 },
580 ProtoOaSymbol {
581 lot_size: Some(-1),
582 ..wire_symbol()
583 },
584 ] {
585 assert!(matches!(
586 Symbol::try_from(raw),
587 Err(ValueError::Negative { kind: "volume", .. })
588 ));
589 }
590 }
591
592 #[test]
593 fn every_trading_mode_maps_to_a_variant() {
594 let modes = [
595 (ProtoOaTradingMode::Enabled, TradingMode::Enabled),
596 (
597 ProtoOaTradingMode::DisabledWithoutPendingsExecution,
598 TradingMode::DisabledWithoutPendingsExecution,
599 ),
600 (
601 ProtoOaTradingMode::DisabledWithPendingsExecution,
602 TradingMode::DisabledWithPendingsExecution,
603 ),
604 (ProtoOaTradingMode::CloseOnlyMode, TradingMode::CloseOnly),
605 ];
606 for (wire, mode) in modes {
607 assert_eq!(TradingMode::from(wire), mode);
608 }
609 }
610
611 #[test]
612 fn symbols_parameters_leave_archived_symbols_out_by_default() {
613 let account = AccountId::new(7).expect("account id");
614 let params = SymbolsParams::new(account);
615 assert_eq!(params.account(), account);
616 assert!(!params.includes_archived());
617 assert!(params.include_archived(true).includes_archived());
618 }
619}