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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Stream of market depth and the order book rebuilt from it.
//!
//! ```no_run
//! use ctrader_connector::common::config::ConfigurationOpenApi;
//! use ctrader_connector::common::ids::SymbolId;
//! 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?;
//! let account = client.accounts().await?[0].id;
//! client.authorise_account(account).await?;
//! let symbol = SymbolId::new(1)?;
//! let mut depth = client.subscribe_depth(account, &[symbol]).await?;
//! depth.next().await?;
//! if let Some(book) = depth.book(symbol) {
//!     println!("{:?} / {:?}", book.best_bid(), book.best_ask());
//! }
//! depth.unsubscribe().await?;
//! # Ok(())
//! # }
//! ```

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use crate::common::decimals::{Price, Volume};
use crate::common::errors::{ConnectorError, ValueError};
use crate::common::ids::{AccountId, SymbolId};
use crate::open_api::client::OpenApiClient;
use crate::open_api::connection::{ReplayKey, ReplayStage};
use crate::open_api::messages::{
    ProtoOaDepthEvent, ProtoOaDepthQuote, ProtoOaSubscribeDepthQuotesReq,
    ProtoOaUnsubscribeDepthQuotesReq,
};
use crate::open_api::quotes::{QuoteSide, wire_price};
use crate::open_api::stream::{Feed, starts_replay};

const DEPTH_SIZE: &str = "depth size";
const DEPTH_SIDE: &str = "depth quote side";

/// Identifier of one entry of the market depth of a symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DepthQuoteId(u64);

impl DepthQuoteId {
    /// Wraps the identifier the server assigned.
    #[must_use]
    pub const fn new(id: u64) -> Self {
        Self(id)
    }

    /// Returns the identifier the server assigned.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }
}

impl fmt::Display for DepthQuoteId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(formatter)
    }
}

/// One entry of the market depth: a volume on offer at a price.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct DepthQuote {
    /// Identifier of the entry, unique within the depth of its symbol.
    pub id: DepthQuoteId,
    /// Side of the book the entry belongs to.
    pub side: QuoteSide,
    /// Price of the entry.
    pub price: Price,
    /// Volume on offer at the price.
    pub size: Volume,
}

impl TryFrom<ProtoOaDepthQuote> for DepthQuote {
    type Error = ValueError;

    fn try_from(quote: ProtoOaDepthQuote) -> Result<Self, Self::Error> {
        let (side, raw) = match (quote.bid, quote.ask) {
            (Some(bid), None) => (QuoteSide::Bid, bid),
            (None, Some(ask)) => (QuoteSide::Ask, ask),
            _ => return Err(ValueError::OutOfRange { kind: DEPTH_SIDE }),
        };
        let volume =
            i64::try_from(quote.size).map_err(|_| ValueError::OutOfRange { kind: DEPTH_SIZE })?;
        Ok(Self {
            id: DepthQuoteId(quote.id),
            side,
            price: wire_price(raw)?,
            size: Volume::from_wire(volume)?,
        })
    }
}

/// Change of the market depth of a symbol.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct DepthUpdate {
    /// Symbol the change belongs to.
    pub symbol: SymbolId,
    /// Entries that are new or replace the entry with the same identifier.
    pub new_quotes: Vec<DepthQuote>,
    /// Identifiers of the entries that are gone.
    pub deleted_quotes: Vec<DepthQuoteId>,
}

impl DepthUpdate {
    fn parse(symbol: SymbolId, event: ProtoOaDepthEvent) -> Result<Self, ValueError> {
        Ok(Self {
            symbol,
            new_quotes: event
                .new_quotes
                .into_iter()
                .map(DepthQuote::try_from)
                .collect::<Result<_, _>>()?,
            deleted_quotes: event.deleted_quotes.into_iter().map(DepthQuoteId).collect(),
        })
    }
}

/// Order book of a symbol, rebuilt from the changes of its market depth.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DepthBook {
    quotes: BTreeMap<DepthQuoteId, DepthQuote>,
}

impl DepthBook {
    /// Creates an empty book.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Applies a change: drops the deleted entries, then stores the new ones.
    pub fn apply(&mut self, update: &DepthUpdate) {
        for id in &update.deleted_quotes {
            self.quotes.remove(id);
        }
        for quote in &update.new_quotes {
            self.quotes.insert(quote.id, *quote);
        }
    }

    fn side(&self, side: QuoteSide) -> Vec<DepthQuote> {
        let mut quotes: Vec<DepthQuote> = self
            .quotes
            .values()
            .filter(|quote| quote.side == side)
            .copied()
            .collect();
        quotes.sort_by_key(|quote| (quote.price, quote.id));
        quotes
    }

    /// Returns the bids, best (highest) price first.
    #[must_use]
    pub fn bids(&self) -> Vec<DepthQuote> {
        let mut bids = self.side(QuoteSide::Bid);
        bids.reverse();
        bids
    }

    /// Returns the asks, best (lowest) price first.
    #[must_use]
    pub fn asks(&self) -> Vec<DepthQuote> {
        self.side(QuoteSide::Ask)
    }

    fn prices(&self, side: QuoteSide) -> impl Iterator<Item = Price> + '_ {
        self.quotes
            .values()
            .filter(move |quote| quote.side == side)
            .map(|quote| quote.price)
    }

    /// Returns the highest bid.
    #[must_use]
    pub fn best_bid(&self) -> Option<Price> {
        self.prices(QuoteSide::Bid).max()
    }

    /// Returns the lowest ask.
    #[must_use]
    pub fn best_ask(&self) -> Option<Price> {
        self.prices(QuoteSide::Ask).min()
    }

    /// Returns the number of entries on both sides.
    #[must_use]
    pub fn len(&self) -> usize {
        self.quotes.len()
    }

    /// Tells whether the book holds no entry.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.quotes.is_empty()
    }
}

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

/// Changes of the market depth of the symbols of one account, with the books they build.
///
/// The subscription behind the stream is restored after a reconnection. The books are emptied
/// the moment the loss of the connection is reported, which is before anything the server sends
/// for the restored subscription, so the whole depth the server then sends anew builds them
/// afresh.
///
/// A stream that is read too slowly loses events: the connection holds a limited number of
/// them, set with
/// [`ConnectionOptions::event_capacity`](crate::open_api::connection::ConnectionOptions::event_capacity).
/// A book that missed a change is wrong and cannot be repaired from later changes, so the loss
/// is reported once by [`DepthStream::next`] with [`ConnectorError::Lagged`] and the books are
/// dropped. From then on [`DepthStream::book`] returns nothing and the changes the stream goes
/// on to deliver are not applied, until the server sends the whole depth anew: after
/// [`DepthStream::resync`], or after a reconnection the stream has read from its start.
#[derive(Debug)]
pub struct DepthStream {
    client: OpenApiClient,
    feed: Feed,
    account: AccountId,
    symbols: BTreeSet<SymbolId>,
    books: BTreeMap<SymbolId, DepthBook>,
    stale: bool,
}

impl DepthStream {
    /// Returns the account the depth belongs to.
    #[must_use]
    pub const fn account(&self) -> AccountId {
        self.account
    }

    /// Returns the symbols the stream delivers the depth of, in ascending order.
    pub fn symbols(&self) -> impl Iterator<Item = SymbolId> + '_ {
        self.symbols.iter().copied()
    }

    /// Returns the book of the symbol as of the last change the stream delivered.
    ///
    /// Returns nothing before the first change of the symbol, and for every symbol from the
    /// moment [`DepthStream::next`] reports [`ConnectorError::Lagged`] until the whole depth has
    /// been sent anew.
    #[must_use]
    pub fn book(&self, symbol: SymbolId) -> Option<&DepthBook> {
        self.books.get(&symbol)
    }

    /// Tells whether the books are withheld because changes were lost; see
    /// [`DepthStream::resync`].
    #[must_use]
    pub const fn is_stale(&self) -> bool {
        self.stale
    }

    /// Subscribes to the depth of the symbols of the stream anew, so that the server sends the
    /// whole depth again and the books are valid from the first change delivered afterwards.
    ///
    /// The subscription is ended and requested again, and the changes that were waiting to be
    /// read are discarded. Meant to be called after [`DepthStream::next`] has reported
    /// [`ConnectorError::Lagged`].
    ///
    /// # Errors
    ///
    /// Fails like [`OpenApiClient::unsubscribe_depth`] and [`OpenApiClient::subscribe_depth`];
    /// the books stay withheld then.
    pub async fn resync(&mut self) -> Result<(), ConnectorError> {
        let symbols: Vec<SymbolId> = self.symbols.iter().copied().collect();
        self.stale = true;
        self.books.clear();
        self.client
            .unsubscribe_depth(self.account, &symbols)
            .await?;
        self.feed = Feed::new(self.client.connection(), self.account);
        self.client.request_depth(self.account, &symbols).await?;
        self.stale = false;
        Ok(())
    }

    /// Waits for the next change of the depth of one of the symbols and applies it to the book
    /// of its symbol.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Closed`] when the connection is shut down,
    /// [`ConnectorError::SessionEnded`] when the server ended the authorisation of the account,
    /// [`ConnectorError::Lagged`] when changes were dropped because the stream was read too
    /// slowly, and [`ConnectorError::Value`] when the server sends a value out of range.
    pub async fn next(&mut self) -> Result<DepthUpdate, ConnectorError> {
        loop {
            let event = match self.feed.next().await {
                Ok(event) => event,
                Err(error) => {
                    if matches!(error, ConnectorError::Lagged { .. }) {
                        self.books.clear();
                        self.stale = true;
                    }
                    return Err(error);
                }
            };
            if starts_replay(&event) {
                self.books.clear();
                self.stale = false;
                continue;
            }
            let Some(depth) = event.decode::<ProtoOaDepthEvent>() else {
                continue;
            };
            if depth.ctid_trader_account_id != self.account.get() {
                continue;
            }
            let Some(symbol) = self
                .symbols
                .iter()
                .copied()
                .find(|symbol| u64::try_from(symbol.get()) == Ok(depth.symbol_id))
            else {
                continue;
            };
            let update = DepthUpdate::parse(symbol, depth)?;
            if !self.stale {
                self.books.entry(symbol).or_default().apply(&update);
            }
            return Ok(update);
        }
    }

    /// Ends the subscription to the depth of the symbols of the stream.
    ///
    /// # Errors
    ///
    /// Fails like [`OpenApiClient::unsubscribe_depth`].
    pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
        let symbols: Vec<SymbolId> = self.symbols.into_iter().collect();
        self.client.unsubscribe_depth(self.account, &symbols).await
    }
}

impl OpenApiClient {
    /// Subscribes to the market depth of the given symbols on an authorised account and
    /// returns its changes as a stream.
    ///
    /// The stream starts to listen before the subscription is requested, so the first entries
    /// the server sends are not missed. The subscription is restored after a reconnection.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Server`] when the server refuses the subscription, and the
    /// errors of [`Connection::request`](crate::open_api::connection::Connection::request)
    /// otherwise.
    pub async fn subscribe_depth(
        &self,
        account: AccountId,
        symbols: &[SymbolId],
    ) -> Result<DepthStream, ConnectorError> {
        let stream = DepthStream {
            client: self.clone(),
            feed: Feed::new(self.connection(), account),
            account,
            symbols: symbols.iter().copied().collect(),
            books: BTreeMap::new(),
            stale: false,
        };
        self.request_depth(account, symbols).await?;
        Ok(stream)
    }

    async fn request_depth(
        &self,
        account: AccountId,
        symbols: &[SymbolId],
    ) -> Result<(), ConnectorError> {
        let request = |symbols: &[SymbolId]| ProtoOaSubscribeDepthQuotesReq {
            payload_type: None,
            ctid_trader_account_id: account.get(),
            symbol_id: symbols.iter().map(|symbol| symbol.get()).collect(),
        };
        self.connection().request(&request(symbols)).await?;
        for symbol in symbols {
            self.connection()
                .register_replay(depth_key(account, *symbol), &request(&[*symbol]))
                .await?;
        }
        Ok(())
    }

    /// Ends the subscription to the market depth of the given symbols.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Server`] when the server refuses the request, and the errors
    /// of [`Connection::request`](crate::open_api::connection::Connection::request) otherwise.
    pub async fn unsubscribe_depth(
        &self,
        account: AccountId,
        symbols: &[SymbolId],
    ) -> Result<(), ConnectorError> {
        let request = ProtoOaUnsubscribeDepthQuotesReq {
            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(depth_key(account, *symbol))
                .await?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{DepthBook, DepthQuote, DepthQuoteId, DepthUpdate};
    use crate::common::errors::ValueError;
    use crate::common::ids::SymbolId;
    use crate::open_api::messages::{ProtoOaDepthEvent, ProtoOaDepthQuote};
    use crate::open_api::quotes::QuoteSide;

    fn bid(id: u64, price: u64, size: u64) -> ProtoOaDepthQuote {
        ProtoOaDepthQuote {
            id,
            size,
            bid: Some(price),
            ask: None,
        }
    }

    fn ask(id: u64, price: u64, size: u64) -> ProtoOaDepthQuote {
        ProtoOaDepthQuote {
            id,
            size,
            bid: None,
            ask: Some(price),
        }
    }

    fn update(new: Vec<ProtoOaDepthQuote>, deleted: Vec<u64>) -> DepthUpdate {
        let event = ProtoOaDepthEvent {
            payload_type: None,
            ctid_trader_account_id: 7,
            symbol_id: 1,
            new_quotes: new,
            deleted_quotes: deleted,
        };
        DepthUpdate::parse(SymbolId::new(1).expect("symbol id"), event).expect("update")
    }

    #[test]
    fn depth_quote_is_parsed_from_the_wire() {
        let quote = DepthQuote::try_from(bid(3, 108_512, 150_000)).expect("quote");
        assert_eq!(quote.id, DepthQuoteId::new(3));
        assert_eq!(quote.id.get(), 3);
        assert_eq!(quote.id.to_string(), "3");
        assert_eq!(quote.side, QuoteSide::Bid);
        assert_eq!(quote.price.to_string(), "1.08512");
        assert_eq!(quote.size.to_string(), "1500.00");
        let quote = DepthQuote::try_from(ask(4, 108_520, 0)).expect("quote");
        assert_eq!(quote.side, QuoteSide::Ask);
        assert_eq!(quote.size.to_string(), "0.00");
    }

    #[test]
    fn depth_quotes_without_one_side_or_with_a_huge_size_are_rejected() {
        let side = Err(ValueError::OutOfRange {
            kind: "depth quote side",
        });
        let neither = ProtoOaDepthQuote {
            id: 1,
            size: 1,
            bid: None,
            ask: None,
        };
        assert_eq!(DepthQuote::try_from(neither), side);
        let both = ProtoOaDepthQuote {
            ask: Some(2),
            ..bid(1, 1, 1)
        };
        assert_eq!(DepthQuote::try_from(both), side);
        assert_eq!(
            DepthQuote::try_from(bid(1, 1, u64::MAX)),
            Err(ValueError::OutOfRange { kind: "depth size" })
        );
    }

    #[test]
    fn book_applies_new_replaced_and_deleted_entries() {
        let mut book = DepthBook::new();
        assert!(book.is_empty());
        assert_eq!(book.best_bid(), None);
        assert_eq!(book.best_ask(), None);
        book.apply(&update(
            vec![
                bid(1, 100, 10),
                bid(2, 99, 20),
                ask(3, 102, 30),
                ask(4, 103, 40),
            ],
            Vec::new(),
        ));
        assert_eq!(book.len(), 4);
        let ids = |quotes: Vec<DepthQuote>| quotes.iter().map(|q| q.id.get()).collect::<Vec<_>>();
        assert_eq!(ids(book.bids()), vec![1, 2]);
        assert_eq!(ids(book.asks()), vec![3, 4]);
        assert_eq!(
            book.best_bid().map(|p| p.to_string()).as_deref(),
            Some("0.00100")
        );
        assert_eq!(
            book.best_ask().map(|p| p.to_string()).as_deref(),
            Some("0.00102")
        );
        book.apply(&update(vec![bid(2, 101, 5), ask(5, 102, 1)], vec![3, 9]));
        assert_eq!(ids(book.bids()), vec![2, 1]);
        assert_eq!(ids(book.asks()), vec![5, 4]);
        assert_eq!(
            book.best_bid().map(|p| p.to_string()).as_deref(),
            Some("0.00101")
        );
        book.apply(&update(Vec::new(), vec![1, 2, 4, 5]));
        assert!(book.is_empty());
    }
}