ctrader-connector 0.3.10

Client library for the cTrader Open API and the cTrader FIX 4.4 API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Client that authorises an application and its trading accounts over one connection.
//!
//! ```no_run
//! use ctrader_connector::common::config::ConfigurationOpenApi;
//! use ctrader_connector::open_api::client::OpenApiClient;
//!
//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
//! let client = OpenApiClient::connect(ConfigurationOpenApi::from_env()?).await?;
//! client.authorise_application().await?;
//! for account in client.accounts().await? {
//!     client.authorise_account(account.id).await?;
//! }
//! client.shutdown().await;
//! # Ok(())
//! # }
//! ```
//!
//! # When the server ends an authorisation
//!
//! The server can end the authorisation of a session while the connection stays up. It
//! announces that the access token of some accounts is no longer valid, which happens to every
//! session opened with a token once the pair it belongs to was refreshed; that it dropped the
//! session of an account; or that it ends the session of the application. Each is reported as
//! [`Event::SessionEnded`] to the readers of [`OpenApiClient::events`] and as
//! [`ConnectorError::SessionEnded`] by the typed streams of the account, and every later request
//! of the session fails with [`ConnectorError::SessionEnded`], which names the account and the
//! cause, without being sent. Nothing of the session is replayed after a reconnection.
//!
//! To continue on the same client, authorise the session again:
//!
//! - after an invalidated or refused token, hand the client a valid pair with
//!   [`OpenApiClient::set_tokens`], or obtain one with [`OpenApiClient::refresh_token`], and
//!   call [`OpenApiClient::authorise_account`];
//! - after a dropped account session, call [`OpenApiClient::authorise_account`];
//! - after the end of the application session, call
//!   [`OpenApiClient::authorise_application`] and then
//!   [`OpenApiClient::authorise_account`] for every account.
//!
//! Subscriptions of the session are not restored by this: subscribe again afterwards.

use std::collections::BTreeSet;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

use tokio::sync::broadcast;

use crate::common::config::{AccessToken, ConfigurationOpenApi, RefreshToken};
use crate::common::errors::{ConnectorError, TokenError, ValueError};
use crate::common::ids::{AccountId, SymbolId};
use crate::open_api::connection::{Connection, ConnectionOptions, Event, ReplayKey, ReplayStage};
use crate::open_api::messages::{
    ProtoOaAccountAuthReq, ProtoOaApplicationAuthReq, ProtoOaCtidTraderAccount,
    ProtoOaGetAccountListByAccessTokenReq, ProtoOaRefreshTokenReq, ProtoOaSubscribeSpotsReq,
    ProtoOaUnsubscribeSpotsReq, ProtoOaVersionReq,
};
use crate::open_api::token::{TokenPair, refresh_over_http};
use crate::open_api::transport::{Connect, Tls};
use crate::open_api::trendbars::{Period, trendbar_key};

/// Trading account an access token grants access to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Account {
    /// Identifier of the account.
    pub id: AccountId,
    /// Tells whether the account belongs to the live environment.
    pub is_live: bool,
    /// Login number of the account at the broker, when the server reports it.
    pub login: Option<i64>,
}

impl TryFrom<ProtoOaCtidTraderAccount> for Account {
    type Error = ValueError;

    fn try_from(account: ProtoOaCtidTraderAccount) -> Result<Self, Self::Error> {
        let raw = account.ctid_trader_account_id;
        let id = i64::try_from(raw).map_err(|_| ValueError::InvalidId {
            kind: "account id",
            value: raw.to_string(),
        })?;
        Ok(Self {
            id: AccountId::new(id)?,
            is_live: account.is_live.unwrap_or(false),
            login: account.trader_login,
        })
    }
}

fn account_key(account: AccountId) -> ReplayKey {
    ReplayKey::new(ReplayStage::Account, account.to_string())
}

fn spot_key(account: AccountId, symbol: SymbolId) -> ReplayKey {
    ReplayKey::new(
        ReplayStage::Subscription,
        format!("spots/{account}/{symbol}"),
    )
}

#[derive(Debug)]
struct Tokens {
    access: AccessToken,
    refresh: Option<RefreshToken>,
    accounts: BTreeSet<AccountId>,
}

#[derive(Debug, Default)]
struct Subscriptions {
    spots: BTreeSet<(AccountId, SymbolId)>,
    trendbars: BTreeSet<(AccountId, SymbolId, Period)>,
}

/// Cloneable client of the Open API.
#[derive(Debug, Clone)]
pub struct OpenApiClient {
    connection: Connection,
    configuration: Arc<ConfigurationOpenApi>,
    tokens: Arc<Mutex<Tokens>>,
    subscriptions: Arc<Mutex<Subscriptions>>,
}

impl OpenApiClient {
    /// Connects over TLS to the host named by the configuration.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Transport`] when the connection cannot be established.
    pub async fn connect(configuration: ConfigurationOpenApi) -> Result<Self, ConnectorError> {
        let options = ConnectionOptions::from(&configuration);
        Self::connect_with(configuration, Tls::new()?, options).await
    }

    /// Connects through the given connector with the given connection options.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Transport`] when the connection cannot be established.
    pub async fn connect_with<C: Connect>(
        configuration: ConfigurationOpenApi,
        connector: C,
        options: ConnectionOptions,
    ) -> Result<Self, ConnectorError> {
        let connection = Connection::open(
            connector,
            configuration.host(),
            configuration.port(),
            options,
        )
        .await?;
        Ok(Self {
            connection,
            tokens: Arc::new(Mutex::new(Tokens {
                access: configuration.access_token().clone(),
                refresh: configuration.refresh_token().cloned(),
                accounts: BTreeSet::new(),
            })),
            subscriptions: Arc::default(),
            configuration: Arc::new(configuration),
        })
    }

    /// Returns the connection the client sends its requests over.
    #[must_use]
    pub const fn connection(&self) -> &Connection {
        &self.connection
    }

    /// Returns the configuration the client was built from.
    #[must_use]
    pub fn configuration(&self) -> &ConfigurationOpenApi {
        &self.configuration
    }

    /// Subscribes to the events of the connection.
    #[must_use]
    pub fn events(&self) -> broadcast::Receiver<Event> {
        self.connection.events()
    }

    /// Authorises the application with its client id and secret.
    ///
    /// This must succeed before any other request is sent.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Server`] when the credentials are refused, and the errors of
    /// [`Connection::request`] otherwise.
    pub async fn authorise_application(&self) -> Result<(), ConnectorError> {
        let request = ProtoOaApplicationAuthReq {
            payload_type: None,
            client_id: self.configuration.client_id().as_str().to_owned(),
            client_secret: self.configuration.client_secret().expose().to_owned(),
        };
        self.connection.request(&request).await?;
        let key = ReplayKey::new(ReplayStage::Application, "application");
        self.connection.register_replay(key, &request).await
    }

    /// Lists the trading accounts the access token grants access to.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Server`] when the token is refused,
    /// [`ConnectorError::Value`] when the server reports an account id out of range, and the
    /// errors of [`Connection::request`] otherwise.
    pub async fn accounts(&self) -> Result<Vec<Account>, ConnectorError> {
        let request = ProtoOaGetAccountListByAccessTokenReq {
            payload_type: None,
            access_token: self.access_token().expose().to_owned(),
        };
        let response = self.connection.request(&request).await?;
        response
            .ctid_trader_account
            .into_iter()
            .map(|account| Account::try_from(account).map_err(ConnectorError::from))
            .collect()
    }

    /// Authorises a trading account with the access token.
    ///
    /// This also starts a new session for an account whose authorisation the server ended.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Server`] when the token or the account is refused, and the
    /// errors of [`Connection::request`] otherwise.
    pub async fn authorise_account(&self, account: AccountId) -> Result<(), ConnectorError> {
        let request = ProtoOaAccountAuthReq {
            payload_type: None,
            ctid_trader_account_id: account.get(),
            access_token: self.access_token().expose().to_owned(),
        };
        self.connection.request(&request).await?;
        self.tokens().accounts.insert(account);
        self.connection
            .register_replay(account_key(account), &request)
            .await
    }

    /// Returns the access token in use, which differs from the configured one after a refresh.
    #[must_use]
    pub fn access_token(&self) -> AccessToken {
        self.tokens().access.clone()
    }

    /// Replaces the token pair the client uses for its next requests.
    ///
    /// The accounts authorised so far are authorised with the new access token after a
    /// reconnection.
    pub async fn set_tokens(&self, pair: &TokenPair) {
        let accounts: Vec<AccountId> = {
            let mut tokens = self.tokens();
            tokens.access = pair.access.clone();
            tokens.refresh = Some(pair.refresh.clone());
            tokens.accounts.iter().copied().collect()
        };
        for account in accounts {
            let request = ProtoOaAccountAuthReq {
                payload_type: None,
                ctid_trader_account_id: account.get(),
                access_token: pair.access.expose().to_owned(),
            };
            let _ = self
                .connection
                .register_replay(account_key(account), &request)
                .await;
        }
    }

    /// Exchanges the refresh token for a new pair over the connection.
    ///
    /// The old pair stops working once the server has answered and the client uses the new one
    /// from then on. Accounts authorised earlier stay authorised on this connection. Store the
    /// returned pair before doing anything else: it is the only copy.
    ///
    /// # Errors
    ///
    /// Returns [`TokenError::NoRefreshToken`] when no refresh token is known,
    /// [`ConnectorError::Server`] when the server refuses the refresh,
    /// [`TokenError::Malformed`] when the response lacks a token, and the errors of
    /// [`Connection::request`] otherwise.
    pub async fn refresh_token(&self) -> Result<TokenPair, ConnectorError> {
        let request = ProtoOaRefreshTokenReq {
            payload_type: None,
            refresh_token: self.current_refresh_token()?.expose().to_owned(),
        };
        let pair = TokenPair::try_from(self.connection.request(&request).await?)?;
        self.set_tokens(&pair).await;
        Ok(pair)
    }

    /// Exchanges the refresh token for a new pair at the token endpoint, over TLS.
    ///
    /// Behaves like [`OpenApiClient::refresh_token`] but does not use the connection.
    ///
    /// # Errors
    ///
    /// Fails like [`OpenApiClient::refresh_token_over_http_with`].
    pub async fn refresh_token_over_http(&self) -> Result<TokenPair, ConnectorError> {
        self.refresh_token_over_http_with(&Tls::new()?).await
    }

    /// Exchanges the refresh token for a new pair at the token endpoint through `connector`.
    ///
    /// # Errors
    ///
    /// Returns [`TokenError::NoRefreshToken`] when no refresh token is known and the errors of
    /// [`refresh_over_http`] otherwise.
    pub async fn refresh_token_over_http_with<C: Connect>(
        &self,
        connector: &C,
    ) -> Result<TokenPair, ConnectorError> {
        let refresh = self.current_refresh_token()?;
        let pair = refresh_over_http(connector, &self.configuration, &refresh).await?;
        self.set_tokens(&pair).await;
        Ok(pair)
    }

    fn tokens(&self) -> std::sync::MutexGuard<'_, Tokens> {
        self.tokens.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn current_refresh_token(&self) -> Result<RefreshToken, TokenError> {
        self.tokens()
            .refresh
            .clone()
            .ok_or(TokenError::NoRefreshToken)
    }

    /// Subscribes to the spot prices of the given symbols on an authorised account.
    ///
    /// The prices arrive as events carrying a
    /// [`ProtoOaSpotEvent`](crate::open_api::messages::ProtoOaSpotEvent). The subscription is
    /// restored after a reconnection.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Server`] when the server refuses the subscription, and the
    /// errors of [`Connection::request`] otherwise.
    pub async fn subscribe_spots(
        &self,
        account: AccountId,
        symbols: &[SymbolId],
    ) -> Result<(), ConnectorError> {
        let request = |symbols: &[SymbolId]| ProtoOaSubscribeSpotsReq {
            payload_type: None,
            ctid_trader_account_id: account.get(),
            symbol_id: symbols.iter().map(|symbol| symbol.get()).collect(),
            subscribe_to_spot_timestamp: Some(true),
        };
        self.connection.request(&request(symbols)).await?;
        for symbol in symbols {
            self.connection
                .register_replay(spot_key(account, *symbol), &request(&[*symbol]))
                .await?;
        }
        self.subscriptions()
            .spots
            .extend(symbols.iter().map(|symbol| (account, *symbol)));
        Ok(())
    }

    /// Ends the subscription to the spot prices of the given symbols.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Server`] when the server refuses the request, and the errors
    /// of [`Connection::request`] otherwise.
    pub async fn unsubscribe_spots(
        &self,
        account: AccountId,
        symbols: &[SymbolId],
    ) -> Result<(), ConnectorError> {
        let request = ProtoOaUnsubscribeSpotsReq {
            payload_type: None,
            ctid_trader_account_id: account.get(),
            symbol_id: symbols.iter().map(|symbol| symbol.get()).collect(),
        };
        self.connection.request(&request).await?;
        for symbol in symbols {
            self.connection
                .remove_replay(spot_key(account, *symbol))
                .await?;
        }
        let dropped: Vec<(SymbolId, Period)> = {
            let mut subscriptions = self.subscriptions();
            for symbol in symbols {
                subscriptions.spots.remove(&(account, *symbol));
            }
            let dropped = subscriptions
                .trendbars
                .iter()
                .filter(|(owner, symbol, _)| *owner == account && symbols.contains(symbol))
                .map(|(_, symbol, period)| (*symbol, *period))
                .collect();
            subscriptions
                .trendbars
                .retain(|(owner, symbol, _)| *owner != account || !symbols.contains(symbol));
            dropped
        };
        for (symbol, period) in dropped {
            self.connection
                .remove_replay(trendbar_key(account, symbol, period))
                .await?;
        }
        Ok(())
    }

    fn subscriptions(&self) -> MutexGuard<'_, Subscriptions> {
        self.subscriptions
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    /// Tells whether this client holds the spot subscription of the symbol.
    pub(crate) fn has_spots(&self, account: AccountId, symbol: SymbolId) -> bool {
        self.subscriptions().spots.contains(&(account, symbol))
    }

    /// Records that the live bars of the symbol and period are subscribed, or no longer are.
    pub(crate) fn track_trendbars(
        &self,
        account: AccountId,
        symbol: SymbolId,
        period: Period,
        active: bool,
    ) {
        let key = (account, symbol, period);
        let mut subscriptions = self.subscriptions();
        if active {
            subscriptions.trendbars.insert(key);
        } else {
            subscriptions.trendbars.remove(&key);
        }
    }

    /// Asks the server for the version of the protocol it speaks.
    ///
    /// # Errors
    ///
    /// Fails like [`Connection::request`].
    pub async fn version(&self) -> Result<String, ConnectorError> {
        let response = self
            .connection
            .request(&ProtoOaVersionReq { payload_type: None })
            .await?;
        Ok(response.version)
    }

    /// Stops the connection task; see [`Connection::shutdown`].
    pub async fn shutdown(&self) {
        self.connection.shutdown().await;
    }
}

#[cfg(test)]
mod tests {
    use super::Account;
    use crate::common::errors::ValueError;
    use crate::common::ids::AccountId;
    use crate::open_api::messages::ProtoOaCtidTraderAccount;

    fn wire(id: u64) -> ProtoOaCtidTraderAccount {
        ProtoOaCtidTraderAccount {
            ctid_trader_account_id: id,
            is_live: Some(true),
            trader_login: Some(9),
            last_closing_deal_timestamp: None,
            last_balance_update_timestamp: None,
        }
    }

    #[test]
    fn account_is_parsed_from_the_wire() {
        let account = Account::try_from(wire(42)).expect("account");
        assert_eq!(account.id, AccountId::new(42).expect("id"));
        assert!(account.is_live);
        assert_eq!(account.login, Some(9));
    }

    #[test]
    fn account_ids_out_of_range_are_rejected() {
        for id in [0, u64::MAX] {
            assert_eq!(
                Account::try_from(wire(id)),
                Err(ValueError::InvalidId {
                    kind: "account id",
                    value: id.to_string(),
                })
            );
        }
    }
}