Skip to main content

ctrader_connector/open_api/
client.rs

1//! Client that authorises an application and its trading accounts over one connection.
2//!
3//! ```no_run
4//! use ctrader_connector::common::config::ConfigurationOpenApi;
5//! use ctrader_connector::open_api::client::OpenApiClient;
6//!
7//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
8//! let client = OpenApiClient::connect(ConfigurationOpenApi::from_env()?).await?;
9//! client.authorise_application().await?;
10//! for account in client.accounts().await? {
11//!     client.authorise_account(account.id).await?;
12//! }
13//! client.shutdown().await;
14//! # Ok(())
15//! # }
16//! ```
17//!
18//! # When the server ends an authorisation
19//!
20//! The server can end the authorisation of a session while the connection stays up. It
21//! announces that the access token of some accounts is no longer valid, which happens to every
22//! session opened with a token once the pair it belongs to was refreshed; that it dropped the
23//! session of an account; or that it ends the session of the application. Each is reported as
24//! [`Event::SessionEnded`] to the readers of [`OpenApiClient::events`] and as
25//! [`ConnectorError::SessionEnded`] by the typed streams of the account, and every later request
26//! of the session fails with [`ConnectorError::SessionEnded`], which names the account and the
27//! cause, without being sent. Nothing of the session is replayed after a reconnection.
28//!
29//! To continue on the same client, authorise the session again:
30//!
31//! - after an invalidated or refused token, hand the client a valid pair with
32//!   [`OpenApiClient::set_tokens`], or obtain one with [`OpenApiClient::refresh_token`], and
33//!   call [`OpenApiClient::authorise_account`];
34//! - after a dropped account session, call [`OpenApiClient::authorise_account`];
35//! - after the end of the application session, call
36//!   [`OpenApiClient::authorise_application`] and then
37//!   [`OpenApiClient::authorise_account`] for every account.
38//!
39//! Subscriptions of the session are not restored by this: subscribe again afterwards.
40
41use std::collections::BTreeSet;
42use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
43
44use tokio::sync::broadcast;
45
46use crate::common::config::{AccessToken, ConfigurationOpenApi, RefreshToken};
47use crate::common::errors::{ConnectorError, TokenError, ValueError};
48use crate::common::ids::{AccountId, SymbolId};
49use crate::open_api::connection::{Connection, ConnectionOptions, Event, ReplayKey, ReplayStage};
50use crate::open_api::messages::{
51    ProtoOaAccountAuthReq, ProtoOaApplicationAuthReq, ProtoOaCtidTraderAccount,
52    ProtoOaGetAccountListByAccessTokenReq, ProtoOaRefreshTokenReq, ProtoOaSubscribeSpotsReq,
53    ProtoOaUnsubscribeSpotsReq, ProtoOaVersionReq,
54};
55use crate::open_api::token::{TokenPair, refresh_over_http};
56use crate::open_api::transport::{Connect, Tls};
57use crate::open_api::trendbars::{Period, trendbar_key};
58
59/// Trading account an access token grants access to.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61#[non_exhaustive]
62pub struct Account {
63    /// Identifier of the account.
64    pub id: AccountId,
65    /// Tells whether the account belongs to the live environment.
66    pub is_live: bool,
67    /// Login number of the account at the broker, when the server reports it.
68    pub login: Option<i64>,
69}
70
71impl TryFrom<ProtoOaCtidTraderAccount> for Account {
72    type Error = ValueError;
73
74    fn try_from(account: ProtoOaCtidTraderAccount) -> Result<Self, Self::Error> {
75        let raw = account.ctid_trader_account_id;
76        let id = i64::try_from(raw).map_err(|_| ValueError::InvalidId {
77            kind: "account id",
78            value: raw.to_string(),
79        })?;
80        Ok(Self {
81            id: AccountId::new(id)?,
82            is_live: account.is_live.unwrap_or(false),
83            login: account.trader_login,
84        })
85    }
86}
87
88fn account_key(account: AccountId) -> ReplayKey {
89    ReplayKey::new(ReplayStage::Account, account.to_string())
90}
91
92fn spot_key(account: AccountId, symbol: SymbolId) -> ReplayKey {
93    ReplayKey::new(
94        ReplayStage::Subscription,
95        format!("spots/{account}/{symbol}"),
96    )
97}
98
99#[derive(Debug)]
100struct Tokens {
101    access: AccessToken,
102    refresh: Option<RefreshToken>,
103    accounts: BTreeSet<AccountId>,
104}
105
106#[derive(Debug, Default)]
107struct Subscriptions {
108    spots: BTreeSet<(AccountId, SymbolId)>,
109    trendbars: BTreeSet<(AccountId, SymbolId, Period)>,
110}
111
112/// Cloneable client of the Open API.
113#[derive(Debug, Clone)]
114pub struct OpenApiClient {
115    connection: Connection,
116    configuration: Arc<ConfigurationOpenApi>,
117    tokens: Arc<Mutex<Tokens>>,
118    subscriptions: Arc<Mutex<Subscriptions>>,
119}
120
121impl OpenApiClient {
122    /// Connects over TLS to the host named by the configuration.
123    ///
124    /// # Errors
125    ///
126    /// Returns [`ConnectorError::Transport`] when the connection cannot be established.
127    pub async fn connect(configuration: ConfigurationOpenApi) -> Result<Self, ConnectorError> {
128        let options = ConnectionOptions::from(&configuration);
129        Self::connect_with(configuration, Tls::new()?, options).await
130    }
131
132    /// Connects through the given connector with the given connection options.
133    ///
134    /// # Errors
135    ///
136    /// Returns [`ConnectorError::Transport`] when the connection cannot be established.
137    pub async fn connect_with<C: Connect>(
138        configuration: ConfigurationOpenApi,
139        connector: C,
140        options: ConnectionOptions,
141    ) -> Result<Self, ConnectorError> {
142        let connection = Connection::open(
143            connector,
144            configuration.host(),
145            configuration.port(),
146            options,
147        )
148        .await?;
149        Ok(Self {
150            connection,
151            tokens: Arc::new(Mutex::new(Tokens {
152                access: configuration.access_token().clone(),
153                refresh: configuration.refresh_token().cloned(),
154                accounts: BTreeSet::new(),
155            })),
156            subscriptions: Arc::default(),
157            configuration: Arc::new(configuration),
158        })
159    }
160
161    /// Returns the connection the client sends its requests over.
162    #[must_use]
163    pub const fn connection(&self) -> &Connection {
164        &self.connection
165    }
166
167    /// Returns the configuration the client was built from.
168    #[must_use]
169    pub fn configuration(&self) -> &ConfigurationOpenApi {
170        &self.configuration
171    }
172
173    /// Subscribes to the events of the connection.
174    #[must_use]
175    pub fn events(&self) -> broadcast::Receiver<Event> {
176        self.connection.events()
177    }
178
179    /// Authorises the application with its client id and secret.
180    ///
181    /// This must succeed before any other request is sent.
182    ///
183    /// # Errors
184    ///
185    /// Returns [`ConnectorError::Server`] when the credentials are refused, and the errors of
186    /// [`Connection::request`] otherwise.
187    pub async fn authorise_application(&self) -> Result<(), ConnectorError> {
188        let request = ProtoOaApplicationAuthReq {
189            payload_type: None,
190            client_id: self.configuration.client_id().as_str().to_owned(),
191            client_secret: self.configuration.client_secret().expose().to_owned(),
192        };
193        self.connection.request(&request).await?;
194        let key = ReplayKey::new(ReplayStage::Application, "application");
195        self.connection.register_replay(key, &request).await
196    }
197
198    /// Lists the trading accounts the access token grants access to.
199    ///
200    /// # Errors
201    ///
202    /// Returns [`ConnectorError::Server`] when the token is refused,
203    /// [`ConnectorError::Value`] when the server reports an account id out of range, and the
204    /// errors of [`Connection::request`] otherwise.
205    pub async fn accounts(&self) -> Result<Vec<Account>, ConnectorError> {
206        let request = ProtoOaGetAccountListByAccessTokenReq {
207            payload_type: None,
208            access_token: self.access_token().expose().to_owned(),
209        };
210        let response = self.connection.request(&request).await?;
211        response
212            .ctid_trader_account
213            .into_iter()
214            .map(|account| Account::try_from(account).map_err(ConnectorError::from))
215            .collect()
216    }
217
218    /// Authorises a trading account with the access token.
219    ///
220    /// This also starts a new session for an account whose authorisation the server ended.
221    ///
222    /// # Errors
223    ///
224    /// Returns [`ConnectorError::Server`] when the token or the account is refused, and the
225    /// errors of [`Connection::request`] otherwise.
226    pub async fn authorise_account(&self, account: AccountId) -> Result<(), ConnectorError> {
227        let request = ProtoOaAccountAuthReq {
228            payload_type: None,
229            ctid_trader_account_id: account.get(),
230            access_token: self.access_token().expose().to_owned(),
231        };
232        self.connection.request(&request).await?;
233        self.tokens().accounts.insert(account);
234        self.connection
235            .register_replay(account_key(account), &request)
236            .await
237    }
238
239    /// Returns the access token in use, which differs from the configured one after a refresh.
240    #[must_use]
241    pub fn access_token(&self) -> AccessToken {
242        self.tokens().access.clone()
243    }
244
245    /// Replaces the token pair the client uses for its next requests.
246    ///
247    /// The accounts authorised so far are authorised with the new access token after a
248    /// reconnection.
249    pub async fn set_tokens(&self, pair: &TokenPair) {
250        let accounts: Vec<AccountId> = {
251            let mut tokens = self.tokens();
252            tokens.access = pair.access.clone();
253            tokens.refresh = Some(pair.refresh.clone());
254            tokens.accounts.iter().copied().collect()
255        };
256        for account in accounts {
257            let request = ProtoOaAccountAuthReq {
258                payload_type: None,
259                ctid_trader_account_id: account.get(),
260                access_token: pair.access.expose().to_owned(),
261            };
262            let _ = self
263                .connection
264                .register_replay(account_key(account), &request)
265                .await;
266        }
267    }
268
269    /// Exchanges the refresh token for a new pair over the connection.
270    ///
271    /// The old pair stops working once the server has answered and the client uses the new one
272    /// from then on. Accounts authorised earlier stay authorised on this connection. Store the
273    /// returned pair before doing anything else: it is the only copy.
274    ///
275    /// # Errors
276    ///
277    /// Returns [`TokenError::NoRefreshToken`] when no refresh token is known,
278    /// [`ConnectorError::Server`] when the server refuses the refresh,
279    /// [`TokenError::Malformed`] when the response lacks a token, and the errors of
280    /// [`Connection::request`] otherwise.
281    pub async fn refresh_token(&self) -> Result<TokenPair, ConnectorError> {
282        let request = ProtoOaRefreshTokenReq {
283            payload_type: None,
284            refresh_token: self.current_refresh_token()?.expose().to_owned(),
285        };
286        let pair = TokenPair::try_from(self.connection.request(&request).await?)?;
287        self.set_tokens(&pair).await;
288        Ok(pair)
289    }
290
291    /// Exchanges the refresh token for a new pair at the token endpoint, over TLS.
292    ///
293    /// Behaves like [`OpenApiClient::refresh_token`] but does not use the connection.
294    ///
295    /// # Errors
296    ///
297    /// Fails like [`OpenApiClient::refresh_token_over_http_with`].
298    pub async fn refresh_token_over_http(&self) -> Result<TokenPair, ConnectorError> {
299        self.refresh_token_over_http_with(&Tls::new()?).await
300    }
301
302    /// Exchanges the refresh token for a new pair at the token endpoint through `connector`.
303    ///
304    /// # Errors
305    ///
306    /// Returns [`TokenError::NoRefreshToken`] when no refresh token is known and the errors of
307    /// [`refresh_over_http`] otherwise.
308    pub async fn refresh_token_over_http_with<C: Connect>(
309        &self,
310        connector: &C,
311    ) -> Result<TokenPair, ConnectorError> {
312        let refresh = self.current_refresh_token()?;
313        let pair = refresh_over_http(connector, &self.configuration, &refresh).await?;
314        self.set_tokens(&pair).await;
315        Ok(pair)
316    }
317
318    fn tokens(&self) -> std::sync::MutexGuard<'_, Tokens> {
319        self.tokens.lock().unwrap_or_else(PoisonError::into_inner)
320    }
321
322    fn current_refresh_token(&self) -> Result<RefreshToken, TokenError> {
323        self.tokens()
324            .refresh
325            .clone()
326            .ok_or(TokenError::NoRefreshToken)
327    }
328
329    /// Subscribes to the spot prices of the given symbols on an authorised account.
330    ///
331    /// The prices arrive as events carrying a
332    /// [`ProtoOaSpotEvent`](crate::open_api::messages::ProtoOaSpotEvent). The subscription is
333    /// restored after a reconnection.
334    ///
335    /// # Errors
336    ///
337    /// Returns [`ConnectorError::Server`] when the server refuses the subscription, and the
338    /// errors of [`Connection::request`] otherwise.
339    pub async fn subscribe_spots(
340        &self,
341        account: AccountId,
342        symbols: &[SymbolId],
343    ) -> Result<(), ConnectorError> {
344        let request = |symbols: &[SymbolId]| ProtoOaSubscribeSpotsReq {
345            payload_type: None,
346            ctid_trader_account_id: account.get(),
347            symbol_id: symbols.iter().map(|symbol| symbol.get()).collect(),
348            subscribe_to_spot_timestamp: Some(true),
349        };
350        self.connection.request(&request(symbols)).await?;
351        for symbol in symbols {
352            self.connection
353                .register_replay(spot_key(account, *symbol), &request(&[*symbol]))
354                .await?;
355        }
356        self.subscriptions()
357            .spots
358            .extend(symbols.iter().map(|symbol| (account, *symbol)));
359        Ok(())
360    }
361
362    /// Ends the subscription to the spot prices of the given symbols.
363    ///
364    /// # Errors
365    ///
366    /// Returns [`ConnectorError::Server`] when the server refuses the request, and the errors
367    /// of [`Connection::request`] otherwise.
368    pub async fn unsubscribe_spots(
369        &self,
370        account: AccountId,
371        symbols: &[SymbolId],
372    ) -> Result<(), ConnectorError> {
373        let request = ProtoOaUnsubscribeSpotsReq {
374            payload_type: None,
375            ctid_trader_account_id: account.get(),
376            symbol_id: symbols.iter().map(|symbol| symbol.get()).collect(),
377        };
378        self.connection.request(&request).await?;
379        for symbol in symbols {
380            self.connection
381                .remove_replay(spot_key(account, *symbol))
382                .await?;
383        }
384        let dropped: Vec<(SymbolId, Period)> = {
385            let mut subscriptions = self.subscriptions();
386            for symbol in symbols {
387                subscriptions.spots.remove(&(account, *symbol));
388            }
389            let dropped = subscriptions
390                .trendbars
391                .iter()
392                .filter(|(owner, symbol, _)| *owner == account && symbols.contains(symbol))
393                .map(|(_, symbol, period)| (*symbol, *period))
394                .collect();
395            subscriptions
396                .trendbars
397                .retain(|(owner, symbol, _)| *owner != account || !symbols.contains(symbol));
398            dropped
399        };
400        for (symbol, period) in dropped {
401            self.connection
402                .remove_replay(trendbar_key(account, symbol, period))
403                .await?;
404        }
405        Ok(())
406    }
407
408    fn subscriptions(&self) -> MutexGuard<'_, Subscriptions> {
409        self.subscriptions
410            .lock()
411            .unwrap_or_else(PoisonError::into_inner)
412    }
413
414    /// Tells whether this client holds the spot subscription of the symbol.
415    pub(crate) fn has_spots(&self, account: AccountId, symbol: SymbolId) -> bool {
416        self.subscriptions().spots.contains(&(account, symbol))
417    }
418
419    /// Records that the live bars of the symbol and period are subscribed, or no longer are.
420    pub(crate) fn track_trendbars(
421        &self,
422        account: AccountId,
423        symbol: SymbolId,
424        period: Period,
425        active: bool,
426    ) {
427        let key = (account, symbol, period);
428        let mut subscriptions = self.subscriptions();
429        if active {
430            subscriptions.trendbars.insert(key);
431        } else {
432            subscriptions.trendbars.remove(&key);
433        }
434    }
435
436    /// Asks the server for the version of the protocol it speaks.
437    ///
438    /// # Errors
439    ///
440    /// Fails like [`Connection::request`].
441    pub async fn version(&self) -> Result<String, ConnectorError> {
442        let response = self
443            .connection
444            .request(&ProtoOaVersionReq { payload_type: None })
445            .await?;
446        Ok(response.version)
447    }
448
449    /// Stops the connection task; see [`Connection::shutdown`].
450    pub async fn shutdown(&self) {
451        self.connection.shutdown().await;
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::Account;
458    use crate::common::errors::ValueError;
459    use crate::common::ids::AccountId;
460    use crate::open_api::messages::ProtoOaCtidTraderAccount;
461
462    fn wire(id: u64) -> ProtoOaCtidTraderAccount {
463        ProtoOaCtidTraderAccount {
464            ctid_trader_account_id: id,
465            is_live: Some(true),
466            trader_login: Some(9),
467            last_closing_deal_timestamp: None,
468            last_balance_update_timestamp: None,
469        }
470    }
471
472    #[test]
473    fn account_is_parsed_from_the_wire() {
474        let account = Account::try_from(wire(42)).expect("account");
475        assert_eq!(account.id, AccountId::new(42).expect("id"));
476        assert!(account.is_live);
477        assert_eq!(account.login, Some(9));
478    }
479
480    #[test]
481    fn account_ids_out_of_range_are_rejected() {
482        for id in [0, u64::MAX] {
483            assert_eq!(
484                Account::try_from(wire(id)),
485                Err(ValueError::InvalidId {
486                    kind: "account id",
487                    value: id.to_string(),
488                })
489            );
490        }
491    }
492}