Skip to main content

ctrader_connector/open_api/
mod.rs

1//! Client for the cTrader Open API, which exchanges Protobuf messages over TLS.
2//!
3//! [`client::OpenApiClient`] is the entry point: it opens one connection, authorises the
4//! application and its trading accounts on it, and carries every request. The other modules
5//! hold the requests of one group each and the values they return.
6//!
7//! ```no_run
8//! use ctrader_connector::common::config::ConfigurationOpenApi;
9//! use ctrader_connector::open_api::client::OpenApiClient;
10//! use ctrader_connector::open_api::symbols::SymbolsParams;
11//!
12//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
13//! let client = OpenApiClient::connect(ConfigurationOpenApi::from_env()?).await?;
14//! client.authorise_application().await?;
15//! let account = client.accounts().await?[0].id;
16//! client.authorise_account(account).await?;
17//! let listed = client.symbols(SymbolsParams::new(account)).await?;
18//! println!("{} symbols", listed.symbols.len());
19//! client.shutdown().await;
20//! # Ok(())
21//! # }
22//! ```
23//!
24//! # Configuration
25//!
26//! [`ConfigurationOpenApi`](crate::common::config::ConfigurationOpenApi) is built with
27//! [`demo`](crate::common::config::ConfigurationOpenApi::demo),
28//! [`live`](crate::common::config::ConfigurationOpenApi::live) or read from the environment
29//! with [`from_env`](crate::common::config::ConfigurationOpenApi::from_env).
30//!
31//! | Variable | Builder option | Required | Default |
32//! |---|---|---|---|
33//! | `BROKER_CLIENT_ID` | `client_id` | yes | none |
34//! | `BROKER_CLIENT_SECRET` | `client_secret` | yes | none |
35//! | `BROKER_ACCESS_TOKEN` | `access_token` | yes | none |
36//! | `BROKER_REFRESH_TOKEN` | `refresh_token` | no | none; a refresh then fails |
37//! | `BROKER_ENVIRONMENT` | `demo()` or `live()` | no | `demo` |
38//! | `BROKER_DEMO_HOST` | `host` | no | `demo.ctraderapi.com`; read for demo only |
39//! | `BROKER_TOKEN_URL` | `token_url` | no | `https://connect.spotware.com/apps/token` |
40//! | none | `host` | no | `live.ctraderapi.com` for live |
41//! | none | `port` | no | 5035 |
42//! | none | `timeout` | no | 10 s for one response |
43//! | none | `retries` | no | 3 after a limit error |
44//! | none | `backoff` | no | 1 s before the first retry |
45//! | none | `reconnect_delay` | no | 5 s before the first attempt |
46//!
47//! An empty variable counts as absent. Secrets are held in types that do not print their
48//! value.
49//!
50//! [`OpenApiClient::connect_with`](client::OpenApiClient::connect_with) also takes
51//! [`ConnectionOptions`](connection::ConnectionOptions) for what the configuration does not
52//! cover:
53//!
54//! | Option | Default |
55//! |---|---|
56//! | `heartbeat_interval` | 10 s |
57//! | `inbound_timeout` | 75 s |
58//! | `reconnect_attempts` | unlimited |
59//! | `request_limit` | 50 per second |
60//! | `historical_limit` | 5 per second |
61//! | `command_capacity` | 64 requests waiting for the connection |
62//! | `event_capacity` | 1024 events held for a reader |
63//!
64//! # Connection lifecycle
65//!
66//! One task owns the socket; see [`connection`] for the whole account.
67//!
68//! - Heartbeat: the task sends one whenever nothing was written for the heartbeat interval.
69//! - Inbound silence: a server that sends nothing, not even its own heartbeat, for the
70//!   inbound timeout counts as lost, as does a write that does not complete in time.
71//! - Reconnect: after a loss the requests in flight fail,
72//!   [`Event::Disconnected`](connection::Event::Disconnected) is reported and the task
73//!   connects again, waiting twice as long before every further attempt, up to a minute or
74//!   the configured delay when that is longer.
75//! - Replay: once connected it authorises the application and the accounts again, restores
76//!   the subscriptions and reports [`Event::Reconnected`](connection::Event::Reconnected).
77//!   Requests made while the connection is down fail at once.
78//! - Never sent again: orders. A request that trades is written at most once; it is neither
79//!   retried after a limit error nor replayed after a reconnection.
80//! - [`OpenApiClient::shutdown`](client::OpenApiClient::shutdown) ends the task; later
81//!   requests fail with [`ConnectorError::Closed`](crate::common::errors::ConnectorError::Closed).
82//!
83//! # Error handling
84//!
85//! Every call returns [`ConnectorError`](crate::common::errors::ConnectorError).
86//!
87//! | Variant | Meaning | Reaction |
88//! |---|---|---|
89//! | `Config`, `Value` | Rejected before anything was sent. | Correct the input. |
90//! | `Server` | The server refused; the error carries its code and text. | Decide by the code. |
91//! | `Transport` | The connection failed or is down. | Wait for `Event::Reconnected`, then repeat a request that reads. |
92//! | `Timeout` | No answer in time to a request that may be repeated. | Repeat it. |
93//! | `OutcomeUnknown` | A request that trades was written and no answer came: the server may have acted on it. | Look the order up with [`reconcile`](client::OpenApiClient::reconcile) or by its label before placing it again. |
94//! | `SessionEnded` | The server ended the authorisation of the account or the application. | Authorise again, see [`client`]; then subscribe again. |
95//! | `Lagged` | A reader fell behind and events were dropped. | Go on reading; refresh the state from the server. |
96//! | `Incomplete` | The server announced more history than it sent. | Treat the range the error names as missing: it cannot be asked for in smaller parts. |
97//! | `Token` | A token refresh failed. | Obtain a new pair. |
98//! | `Closed` | The client was shut down. | Connect anew. |
99//!
100//! # Streams
101//!
102//! The typed streams are each read with `next`. A subscription returns the first three of
103//! them; the streams of executions and of margin events send no request and read what the
104//! server reports for an authorised account:
105//! [`QuoteStream`](quotes::QuoteStream), [`DepthStream`](depth::DepthStream),
106//! [`TrendbarStream`](trendbars::TrendbarStream),
107//! [`ExecutionStream`](executions::ExecutionStream) and
108//! [`MarginStream`](margin::MarginStream).
109//! [`OpenApiClient::events`](client::OpenApiClient::events) gives every event of the
110//! connection untyped. Streams are bounded: a stream read too slowly loses its oldest events
111//! and reports the loss once with `Lagged`, after which it goes on. Subscriptions are
112//! restored after a reconnection, and a stream reports `SessionEnded` when the
113//! authorisation of its account ends.
114//!
115//! # Rate limits
116//!
117//! The server accepts 50 requests per second on a connection and 5 per second for
118//! historical data. The task holds requests back so that neither limit is exceeded. When
119//! the server still answers that a limit was exceeded, the task pauses and sends the
120//! request again, up to the configured number of retries, with a pause that doubles up to
121//! thirty seconds, or up to the configured backoff when that is longer. Long ranges of bars
122//! and ticks take several requests, each counted.
123//!
124//! # Logging
125//!
126//! With the `logging` feature the connection task emits `tracing` events at debug level:
127//! connected, connection lost, reconnected, reconnection failed, replayed request failed,
128//! authorisation ended and limit exceeded. They carry no secret. Without the feature nothing
129//! is emitted and `tracing` is not compiled in. The application installs the subscriber.
130//!
131//! # Testing
132//!
133//! - Mock servers: the tests named `open_api_*_mock` and `open_api_mock` run against
134//!   scripted servers on the loopback interface, reached through
135//!   [`Plain`](crate::common::transport::Plain) and
136//!   [`connect_with`](client::OpenApiClient::connect_with). `open_api_clock_mock` runs over
137//!   a stream held in memory, on a paused clock. They need no credentials.
138//! - Live tests: `open_api_live` refuses any environment but the demo one; the host is the
139//!   one the configuration names. It reads the variables of the table above and
140//!   `BROKER_ENV_FILE`, the absolute
141//!   path of a file that holds the token pair as `export BROKER_ACCESS_TOKEN=` and
142//!   `export BROKER_REFRESH_TOKEN=` lines.
143//! - Token rotation: a refresh makes the old pair useless at once. The live test of the
144//!   refresh writes the new pair back to that file; a run that cannot write it loses the
145//!   pair, and a session opened with the old access token ends with `SessionEnded`.
146//! - Live tests trade the smallest volume, label what they create and remove it afterwards.
147//!
148//! # Protocol facts
149//!
150//! - Prices travel as integers in 1/100000 of a unit and volumes in 0.01 of a unit; the
151//!   library takes and returns decimals in units, see [`crate::common::decimals`].
152//! - Ticks: on the wire `toTimestamp` is exclusive. [`ticks`] takes a range with both ends
153//!   included and asks for one millisecond more.
154//! - Bars: on the wire `toTimestamp` is inclusive; [`trendbars`] returns the bars that
155//!   overlap the range, oldest first, without the bar still forming.
156//! - A stop-limit order is a stop price and a slippage in points, not two prices.
157//! - An order at market takes its stop loss and take profit as distances from the fill
158//!   price; absolute prices are refused before anything is sent.
159//! - A request that trades is answered by the first execution event for it, for an order at
160//!   market its acceptance; the fill follows on the [`executions`] stream.
161
162pub mod errors;
163
164#[allow(missing_docs, clippy::all, clippy::pedantic)]
165#[rustfmt::skip]
166pub mod messages;
167
168pub mod account;
169pub mod client;
170pub mod connection;
171pub mod depth;
172pub mod executions;
173pub mod history;
174pub mod margin;
175pub mod payload;
176pub mod quotes;
177mod stream;
178pub mod symbols;
179pub mod ticks;
180pub mod token;
181pub mod trading;
182pub mod transport;
183pub mod trendbars;
184
185#[cfg(test)]
186mod messages_tests;