ctrader_connector/open_api/executions.rs
1//! Stream of the execution events of an account.
2//!
3//! The server sends the events of every authorised account by itself; nothing is subscribed
4//! to. The stream also delivers the events that answer the requests of this client, such as
5//! the acceptance [`OpenApiClient::place_order`] returns, so the life of an order is read from
6//! one place and in the order the server reported it.
7//!
8//! ```no_run
9//! use ctrader_connector::common::config::ConfigurationOpenApi;
10//! use ctrader_connector::open_api::client::OpenApiClient;
11//! use ctrader_connector::open_api::executions::TradeEvent;
12//!
13//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
14//! let client = OpenApiClient::connect(ConfigurationOpenApi::from_env()?).await?;
15//! client.authorise_application().await?;
16//! let account = client.accounts().await?[0].id;
17//! client.authorise_account(account).await?;
18//! let mut executions = client.executions(account);
19//! loop {
20//! match executions.next().await? {
21//! TradeEvent::Execution(execution) => println!("{:?}", execution.kind),
22//! TradeEvent::OrderError(error) => println!("refused: {}", error.code),
23//! _ => {}
24//! }
25//! }
26//! # }
27//! ```
28
29use crate::common::errors::{ConnectorError, ErrorCode, ValueError};
30use crate::common::ids::{AccountId, OrderId, PositionId};
31use crate::open_api::client::OpenApiClient;
32use crate::open_api::messages::{ProtoOaExecutionEvent, ProtoOaOrderErrorEvent};
33use crate::open_api::stream::Feed;
34use crate::open_api::trading::Execution;
35
36/// Refusal of a request that trades, as the server reports it in an order error event.
37#[derive(Debug, Clone, PartialEq, Eq, Hash)]
38#[non_exhaustive]
39pub struct OrderError {
40 /// Account the refused request was made for.
41 pub account: AccountId,
42 /// Reason of the refusal.
43 pub code: ErrorCode,
44 /// Order the refused request was about.
45 pub order: Option<OrderId>,
46 /// Position the refused request was about.
47 pub position: Option<PositionId>,
48 /// Explanation the server gives.
49 pub description: Option<String>,
50}
51
52impl TryFrom<ProtoOaOrderErrorEvent> for OrderError {
53 type Error = ValueError;
54
55 fn try_from(event: ProtoOaOrderErrorEvent) -> Result<Self, Self::Error> {
56 Ok(Self {
57 account: AccountId::new(event.ctid_trader_account_id)?,
58 code: ErrorCode::from_wire(&event.error_code),
59 order: event.order_id.map(OrderId::new).transpose()?,
60 position: event.position_id.map(PositionId::new).transpose()?,
61 description: event.description,
62 })
63 }
64}
65
66/// One event of the trading of an account.
67#[derive(Debug, Clone, PartialEq, Eq, Hash)]
68#[non_exhaustive]
69pub enum TradeEvent {
70 /// Something happened to an order, a position or the money of the account; the
71 /// [`Execution::kind`] tells what.
72 Execution(Box<Execution>),
73 /// The server refused a request that trades.
74 OrderError(OrderError),
75}
76
77impl TradeEvent {
78 /// Returns the execution when the event is one.
79 #[must_use]
80 pub fn execution(&self) -> Option<&Execution> {
81 match self {
82 Self::Execution(execution) => Some(execution),
83 Self::OrderError(_) => None,
84 }
85 }
86
87 /// Returns the order the event is about, when it names one.
88 #[must_use]
89 pub fn order(&self) -> Option<OrderId> {
90 match self {
91 Self::Execution(execution) => execution.order.as_ref().map(|order| order.id),
92 Self::OrderError(error) => error.order,
93 }
94 }
95}
96
97/// Execution events and order error events of one account, in the order the server sent them.
98///
99/// The stream starts with the first event that arrives after it was created and goes on
100/// across reconnections; events the server sent while the connection was down are not sent
101/// again, so after a reconnection the state of the account is read anew with
102/// [`OpenApiClient::reconcile`].
103///
104/// A stream that is read too slowly loses events: the connection holds a limited number of
105/// them, set with
106/// [`ConnectionOptions::event_capacity`](crate::open_api::connection::ConnectionOptions::event_capacity).
107/// The loss is reported once by [`ExecutionStream::next`] with [`ConnectorError::Lagged`] and
108/// the stream then goes on with the oldest event still held.
109#[derive(Debug)]
110pub struct ExecutionStream {
111 feed: Feed,
112 account: AccountId,
113}
114
115impl ExecutionStream {
116 /// Returns the account the events belong to.
117 #[must_use]
118 pub const fn account(&self) -> AccountId {
119 self.account
120 }
121
122 /// Waits for the next event of the account.
123 ///
124 /// # Errors
125 ///
126 /// Returns [`ConnectorError::Closed`] when the connection is shut down,
127 /// [`ConnectorError::SessionEnded`] when the server ended the authorisation of the account,
128 /// [`ConnectorError::Lagged`] when events were dropped because the stream was read too
129 /// slowly, and [`ConnectorError::Value`] when the server sends a value out of range; the
130 /// stream can be read on after the last two.
131 pub async fn next(&mut self) -> Result<TradeEvent, ConnectorError> {
132 loop {
133 let event = self.feed.next().await?;
134 if let Some(execution) = event.decode::<ProtoOaExecutionEvent>() {
135 if execution.ctid_trader_account_id == self.account.get() {
136 let execution = Execution::try_from(execution)?;
137 return Ok(TradeEvent::Execution(Box::new(execution)));
138 }
139 } else if let Some(error) = event.decode::<ProtoOaOrderErrorEvent>() {
140 if error.ctid_trader_account_id == self.account.get() {
141 return Ok(TradeEvent::OrderError(OrderError::try_from(error)?));
142 }
143 }
144 }
145 }
146}
147
148impl OpenApiClient {
149 /// Starts to read the execution events and order error events of an authorised account.
150 ///
151 /// Nothing is sent: the server delivers these events for every account authorised on the
152 /// connection. Create the stream before the request whose events are to be read.
153 #[must_use]
154 pub fn executions(&self, account: AccountId) -> ExecutionStream {
155 ExecutionStream {
156 feed: Feed::new(self.connection(), account),
157 account,
158 }
159 }
160}