Skip to main content

ctrader_connector/fix/
securities.rs

1//! Symbols of the account, as the quote session lists them.
2
3use crate::common::errors::{ConnectorError, FixError};
4use crate::common::ids::SymbolId;
5use crate::fix::client::FixClient;
6use crate::fix::messages::{Message, SecurityList, SecurityListRequest};
7
8const REQUEST_PREFIX: &str = "sl";
9const ALL_SYMBOLS: u32 = 0;
10const VALID_REQUEST: u32 = 0;
11const TAG_NAME: u32 = 1007;
12const TAG_DIGITS: u32 = 1008;
13
14/// One symbol of the account.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Security {
17    /// Identifier of the symbol, the same the other API of the server uses.
18    pub id: SymbolId,
19    /// Name of the symbol.
20    pub name: String,
21    /// Number of decimal places of a price of the symbol.
22    pub digits: u32,
23}
24
25fn securities(list: SecurityList) -> Result<Vec<Security>, ConnectorError> {
26    if list.result != VALID_REQUEST {
27        return Err(FixError::BusinessRejected {
28            ref_id: Some(list.security_req_id),
29            reason: Some(list.result),
30            text: None,
31        }
32        .into());
33    }
34    let missing = |tag| FixError::MissingField {
35        msg_type: SecurityList::MSG_TYPE.to_owned(),
36        tag,
37    };
38    list.symbols
39        .into_iter()
40        .map(|entry| {
41            Ok(Security {
42                id: entry.symbol,
43                name: entry.name.ok_or_else(|| missing(TAG_NAME))?,
44                digits: entry.digits.ok_or_else(|| missing(TAG_DIGITS))?,
45            })
46        })
47        .collect()
48}
49
50impl FixClient {
51    /// Lists the symbols of the account.
52    ///
53    /// # Errors
54    ///
55    /// Returns [`ConnectorError::Fix`] when the server refuses the request or lists a symbol
56    /// without its name or its digits, in which case no symbol is returned, and otherwise the
57    /// errors of [`FixClient::request`].
58    pub async fn securities(&self) -> Result<Vec<Security>, ConnectorError> {
59        let id = self.next_id(REQUEST_PREFIX);
60        let request = SecurityListRequest {
61            security_req_id: id.clone(),
62            request_type: ALL_SYMBOLS,
63            symbol: None,
64        };
65        self.request(request.into(), &id, |message| match message {
66            Message::SecurityList(list) if list.security_req_id == id => {
67                Some(securities(list.clone()))
68            }
69            _ => None,
70        })
71        .await
72    }
73}