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
//! Prices of the quote session: spot prices and the depth of the market.
//!
//! A subscription is a stream of its own. A [`SpotStream`] yields the best bid and offer of a
//! symbol each time the server reports them; a [`DepthStream`] keeps the [`Book`] of a symbol
//! up to date and yields it after every change. The server tags every report with the
//! identifier of the subscription it belongs to, so that streams of the same symbol do not
//! mix. It sends the best prices as full snapshots, and the depth as an empty snapshot
//! followed by changes.
//!
//! A stream outlives a lost connection: it reports the loss once as an error, and when the
//! session is logged on again it subscribes anew, since the server has forgotten the
//! subscription. The depth then starts over from an empty book.
//!
//! ```no_run
//! use ctrader_connector::common::config::ConfigurationFix;
//! use ctrader_connector::common::ids::SymbolId;
//! use ctrader_connector::fix::client::FixClient;
//! use ctrader_connector::fix::session::SessionKind;
//!
//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
//! let client = FixClient::connect(ConfigurationFix::from_env()?, SessionKind::Quote).await?;
//! let mut spots = client.subscribe_spot(SymbolId::new(1)?).await?;
//! let quote = spots.next().await?;
//! println!("{:?} / {:?}", quote.bid, quote.offer);
//! spots.unsubscribe().await?;
//! client.logout().await?;
//! # Ok(())
//! # }
//! ```

use std::collections::BTreeMap;

use tokio::sync::broadcast;
use tokio::sync::broadcast::error::RecvError;
use tokio::time::timeout;

use crate::common::decimals::{Price, Volume};
use crate::common::errors::{ConnectorError, FixError, TransportError};
use crate::common::ids::SymbolId;
use crate::fix::client::FixClient;
use crate::fix::messages::{
    BookSide, BookUpdate, MarketDataRequest, MarketDataSnapshot, MarketDepth, Message,
};
use crate::fix::session::Event;

const REQUEST_PREFIX: &str = "md";

/// Best prices of a symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpotQuote {
    /// Symbol the prices belong to.
    pub symbol: SymbolId,
    /// Best bid, absent while the server reports none.
    pub bid: Option<Price>,
    /// Best offer, absent while the server reports none.
    pub offer: Option<Price>,
}

/// One entry of a book.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BookEntry {
    /// Identifier of the entry, by which the server removes it.
    pub id: String,
    /// Side of the entry.
    pub side: BookSide,
    /// Price.
    pub price: Price,
    /// Quantity offered at the price.
    pub size: Option<Volume>,
}

/// Depth of the market of one symbol.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Book {
    symbol: SymbolId,
    entries: BTreeMap<String, BookEntry>,
}

impl Book {
    /// Creates the empty book of a symbol.
    #[must_use]
    pub const fn new(symbol: SymbolId) -> Self {
        Self {
            symbol,
            entries: BTreeMap::new(),
        }
    }

    /// Returns the symbol the book belongs to.
    #[must_use]
    pub const fn symbol(&self) -> SymbolId {
        self.symbol
    }

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

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

    /// Returns the bids, the highest price first.
    #[must_use]
    pub fn bids(&self) -> Vec<&BookEntry> {
        let mut bids = self.side(BookSide::Bid);
        bids.sort_by(|a, b| b.price.cmp(&a.price));
        bids
    }

    /// Returns the offers, the lowest price first.
    #[must_use]
    pub fn offers(&self) -> Vec<&BookEntry> {
        let mut offers = self.side(BookSide::Offer);
        offers.sort_by(|a, b| a.price.cmp(&b.price));
        offers
    }

    fn side(&self, side: BookSide) -> Vec<&BookEntry> {
        self.entries
            .values()
            .filter(|entry| entry.side == side)
            .collect()
    }

    /// Replaces the content of the book by a snapshot of the same symbol; a snapshot of
    /// another symbol is ignored.
    pub fn replace(&mut self, snapshot: &MarketDataSnapshot) {
        if snapshot.symbol != self.symbol {
            return;
        }
        self.entries.clear();
        for (position, entry) in snapshot.entries.iter().enumerate() {
            let id = entry
                .id
                .clone()
                .unwrap_or_else(|| format!("{}{position}", entry.side.as_str()));
            self.entries.insert(
                id.clone(),
                BookEntry {
                    id,
                    side: entry.side,
                    price: entry.price,
                    size: entry.size,
                },
            );
        }
    }

    /// Applies one change; a change of another symbol is ignored.
    pub fn apply(&mut self, update: &BookUpdate) {
        match update {
            BookUpdate::New {
                side,
                id,
                symbol,
                price,
                size,
            } if *symbol == self.symbol => {
                self.entries.insert(
                    id.clone(),
                    BookEntry {
                        id: id.clone(),
                        side: *side,
                        price: *price,
                        size: *size,
                    },
                );
            }
            BookUpdate::Delete { id, symbol } if *symbol == self.symbol => {
                self.entries.remove(id);
            }
            _ => {}
        }
    }
}

enum Step {
    Snapshot(MarketDataSnapshot),
    Changes(Vec<BookUpdate>),
}

#[derive(Debug)]
struct Feed {
    client: FixClient,
    events: broadcast::Receiver<Event>,
    md_req_id: String,
    symbol: SymbolId,
    depth: MarketDepth,
    seq: u64,
    ended: bool,
}

impl Feed {
    fn request(&self, subscribe: bool) -> Message {
        MarketDataRequest {
            md_req_id: self.md_req_id.clone(),
            subscribe,
            depth: self.depth,
            symbols: vec![self.symbol],
            sides: vec![BookSide::Bid, BookSide::Offer],
        }
        .into()
    }

    async fn open(
        client: &FixClient,
        symbol: SymbolId,
        depth: MarketDepth,
    ) -> Result<Self, ConnectorError> {
        let mut feed = Self {
            client: client.clone(),
            events: client.events(),
            md_req_id: client.next_id(REQUEST_PREFIX),
            symbol,
            depth,
            seq: 0,
            ended: false,
        };
        feed.seq = client.send(feed.request(true)).await?;
        Ok(feed)
    }

    fn mine(&self, md_req_id: Option<&str>) -> bool {
        md_req_id == Some(self.md_req_id.as_str())
    }

    async fn step(&mut self) -> Result<Step, ConnectorError> {
        if self.ended {
            return Err(ConnectorError::Closed);
        }
        loop {
            let inbound = match self.events.recv().await {
                Ok(Event::Message(inbound)) => inbound,
                Ok(Event::Disconnected(error)) => return Err(error.into()),
                Ok(Event::LoggedOut { .. } | Event::Ended) | Err(RecvError::Closed) => {
                    self.ended = true;
                    return Err(TransportError::Closed.into());
                }
                Ok(Event::Reconnected { .. }) => {
                    self.seq = self.client.send(self.request(true)).await?;
                    continue;
                }
                Ok(_) => continue,
                Err(RecvError::Lagged(skipped)) => {
                    return Err(ConnectorError::Lagged { skipped });
                }
            };
            match inbound.message {
                Message::MarketDataSnapshot(snapshot)
                    if self.mine(snapshot.md_req_id.as_deref())
                        && snapshot.symbol == self.symbol =>
                {
                    return Ok(Step::Snapshot(snapshot));
                }
                Message::MarketDataIncremental(changes)
                    if self.mine(changes.md_req_id.as_deref()) =>
                {
                    return Ok(Step::Changes(changes.entries));
                }
                Message::MarketDataReject(reject) if reject.md_req_id == self.md_req_id => {
                    return Err(FixError::MarketDataRejected {
                        reason: reject.reason,
                        text: reject.text,
                    }
                    .into());
                }
                Message::Reject(reject) if reject.ref_seq_num == self.seq => {
                    return Err(FixError::Rejected {
                        ref_seq_num: self.seq,
                        tag: reject.ref_tag_id,
                        reason: reject.reason,
                        text: reject.text,
                    }
                    .into());
                }
                Message::BusinessReject(reject)
                    if reject.ref_seq_num == Some(self.seq)
                        || reject.ref_id.as_deref() == Some(self.md_req_id.as_str()) =>
                {
                    return Err(FixError::BusinessRejected {
                        ref_id: reject.ref_id,
                        reason: reject.reason,
                        text: reject.text,
                    }
                    .into());
                }
                _ => {}
            }
        }
    }

    async fn first(&mut self) -> Result<Step, ConnectorError> {
        let limit = self.client.timeout();
        timeout(limit, self.step())
            .await
            .map_err(|_| ConnectorError::Timeout(limit))?
    }

    async fn close(&self) -> Result<(), ConnectorError> {
        self.client.send(self.request(false)).await.map(|_| ())
    }
}

/// Stream of the best prices of one symbol.
#[derive(Debug)]
pub struct SpotStream {
    feed: Feed,
    last: SpotQuote,
}

impl SpotStream {
    /// Returns the symbol the stream reports.
    #[must_use]
    pub const fn symbol(&self) -> SymbolId {
        self.feed.symbol
    }

    /// Returns the prices reported last.
    #[must_use]
    pub const fn last(&self) -> SpotQuote {
        self.last
    }

    fn take(&mut self, step: Step) -> Option<SpotQuote> {
        let Step::Snapshot(snapshot) = step else {
            return None;
        };
        let best = |side: BookSide| {
            snapshot
                .entries
                .iter()
                .find(|entry| entry.side == side)
                .map(|entry| entry.price)
        };
        self.last = SpotQuote {
            symbol: snapshot.symbol,
            bid: best(BookSide::Bid),
            offer: best(BookSide::Offer),
        };
        Some(self.last)
    }

    /// Waits for the next report of the prices.
    ///
    /// The wait has no deadline of its own: a market may stand still. The session notices a
    /// server that has gone silent and ends the wait with an error.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Transport`] when the connection is lost, after which the
    /// stream goes on once the session is logged on again, or when the session ends,
    /// [`ConnectorError::Closed`] when it has ended before,
    /// [`ConnectorError::Lagged`] when the reader fell behind and reports were skipped, and
    /// [`ConnectorError::Fix`] when the server refuses the subscription.
    pub async fn next(&mut self) -> Result<SpotQuote, ConnectorError> {
        loop {
            let step = self.feed.step().await?;
            if let Some(quote) = self.take(step) {
                return Ok(quote);
            }
        }
    }

    /// Ends the subscription.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Transport`] when the request cannot be written and
    /// [`ConnectorError::Closed`] when the session has ended already.
    pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
        self.feed.close().await
    }
}

/// Stream of the depth of the market of one symbol.
#[derive(Debug)]
pub struct DepthStream {
    feed: Feed,
    book: Book,
}

impl DepthStream {
    /// Returns the symbol the stream reports.
    #[must_use]
    pub const fn symbol(&self) -> SymbolId {
        self.feed.symbol
    }

    /// Returns the book as of the last change.
    #[must_use]
    pub const fn book(&self) -> &Book {
        &self.book
    }

    fn take(&mut self, step: &Step) {
        match step {
            Step::Snapshot(snapshot) => self.book.replace(snapshot),
            Step::Changes(changes) => {
                for change in changes {
                    self.book.apply(change);
                }
            }
        }
    }

    /// Waits for the next change and returns the book after it.
    ///
    /// The wait has no deadline of its own: a market may stand still. The session notices a
    /// server that has gone silent and ends the wait with an error.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Transport`] when the connection is lost, after which the
    /// stream goes on from an empty book once the session is logged on again, or when the
    /// session ends, [`ConnectorError::Closed`] when it has ended before,
    /// [`ConnectorError::Lagged`] when the reader fell behind, and [`ConnectorError::Fix`]
    /// when the server refuses the subscription. After changes were skipped the book is no
    /// longer that of the server; the subscription has to be opened anew.
    pub async fn next(&mut self) -> Result<&Book, ConnectorError> {
        let step = self.feed.step().await?;
        self.take(&step);
        Ok(&self.book)
    }

    /// Ends the subscription.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Transport`] when the request cannot be written and
    /// [`ConnectorError::Closed`] when the session has ended already.
    pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
        self.feed.close().await
    }
}

impl FixClient {
    /// Subscribes to the best prices of a symbol and waits for the first report.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Fix`] when the server refuses the subscription,
    /// [`ConnectorError::Timeout`] when no price arrives in time, and
    /// [`ConnectorError::Transport`] or [`ConnectorError::Closed`] when the session ends.
    pub async fn subscribe_spot(&self, symbol: SymbolId) -> Result<SpotStream, ConnectorError> {
        let mut stream = SpotStream {
            feed: Feed::open(self, symbol, MarketDepth::Spot).await?,
            last: SpotQuote {
                symbol,
                bid: None,
                offer: None,
            },
        };
        loop {
            let step = stream.feed.first().await?;
            if stream.take(step).is_some() {
                return Ok(stream);
            }
        }
    }

    /// Subscribes to the depth of the market of a symbol and waits for the first book, which
    /// the server sends empty; the entries follow as changes.
    ///
    /// # Errors
    ///
    /// Returns the errors of [`FixClient::subscribe_spot`].
    pub async fn subscribe_depth(&self, symbol: SymbolId) -> Result<DepthStream, ConnectorError> {
        let mut stream = DepthStream {
            feed: Feed::open(self, symbol, MarketDepth::Full).await?,
            book: Book::new(symbol),
        };
        let step = stream.feed.first().await?;
        stream.take(&step);
        Ok(stream)
    }
}