ctrader_connector/open_api/
client.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61#[non_exhaustive]
62pub struct Account {
63 pub id: AccountId,
65 pub is_live: bool,
67 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#[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 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 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 #[must_use]
163 pub const fn connection(&self) -> &Connection {
164 &self.connection
165 }
166
167 #[must_use]
169 pub fn configuration(&self) -> &ConfigurationOpenApi {
170 &self.configuration
171 }
172
173 #[must_use]
175 pub fn events(&self) -> broadcast::Receiver<Event> {
176 self.connection.events()
177 }
178
179 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 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 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 #[must_use]
241 pub fn access_token(&self) -> AccessToken {
242 self.tokens().access.clone()
243 }
244
245 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 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 pub async fn refresh_token_over_http(&self) -> Result<TokenPair, ConnectorError> {
299 self.refresh_token_over_http_with(&Tls::new()?).await
300 }
301
302 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 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 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 pub(crate) fn has_spots(&self, account: AccountId, symbol: SymbolId) -> bool {
416 self.subscriptions().spots.contains(&(account, symbol))
417 }
418
419 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 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 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}