Skip to main content

ctrader_connector/open_api/
ticks.rs

1//! Tick history: every price change of one side of a symbol within a range of time.
2//!
3//! ```no_run
4//! use std::time::Duration;
5//!
6//! use ctrader_connector::common::config::ConfigurationOpenApi;
7//! use ctrader_connector::common::ids::SymbolId;
8//! use ctrader_connector::common::time::{TimeRange, Timestamp};
9//! use ctrader_connector::open_api::client::OpenApiClient;
10//! use ctrader_connector::open_api::quotes::QuoteSide;
11//! use ctrader_connector::open_api::ticks::TickDataParams;
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 minute = TimeRange::ending_at(Timestamp::now(), Duration::from_secs(60));
19//! let params = TickDataParams::new(account, SymbolId::new(1)?, QuoteSide::Bid, minute);
20//! for tick in client.tick_data(&params).await? {
21//!     println!("{} {}", tick.timestamp, tick.price);
22//! }
23//! # Ok(())
24//! # }
25//! ```
26
27use std::time::Duration;
28
29use crate::common::decimals::Price;
30use crate::common::errors::{ConnectorError, ValueError};
31use crate::common::ids::{AccountId, SymbolId};
32use crate::common::time::{TimeRange, Timestamp};
33use crate::open_api::client::OpenApiClient;
34use crate::open_api::messages::{ProtoOaGetTickDataReq, ProtoOaQuoteType, ProtoOaTickData};
35use crate::open_api::quotes::{QuoteSide, wire_price};
36
37const TICK_TIMESTAMP: &str = "tick timestamp";
38const TICK_PRICE: &str = "tick price";
39const MAX_RANGE_MILLIS: i64 = 604_800_000;
40
41/// One price change of one side of a symbol.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43#[non_exhaustive]
44pub struct Tick {
45    /// Moment the price changed.
46    pub timestamp: Timestamp,
47    /// Price from that moment on.
48    pub price: Price,
49}
50
51/// Parameters of [`OpenApiClient::tick_data`].
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53#[must_use]
54pub struct TickDataParams {
55    account: AccountId,
56    symbol: SymbolId,
57    side: QuoteSide,
58    range: TimeRange,
59    limit: Option<usize>,
60}
61
62impl TickDataParams {
63    /// Longest span of time the server accepts in one request: one week.
64    pub const MAX_RANGE: Duration = Duration::from_millis(MAX_RANGE_MILLIS.unsigned_abs());
65
66    /// Asks for the ticks of one side of the symbol that fall inside the range.
67    pub const fn new(
68        account: AccountId,
69        symbol: SymbolId,
70        side: QuoteSide,
71        range: TimeRange,
72    ) -> Self {
73        Self {
74            account,
75            symbol,
76            side,
77            range,
78            limit: None,
79        }
80    }
81
82    /// Limits the answer to the latest `limit` ticks of the range.
83    pub const fn limit(mut self, limit: usize) -> Self {
84        self.limit = Some(limit);
85        self
86    }
87
88    /// Returns the account the ticks are asked for.
89    #[must_use]
90    pub const fn account(&self) -> AccountId {
91        self.account
92    }
93
94    /// Returns the symbol the ticks belong to.
95    #[must_use]
96    pub const fn symbol(&self) -> SymbolId {
97        self.symbol
98    }
99
100    /// Returns the side of the quote the ticks belong to.
101    #[must_use]
102    pub const fn side(&self) -> QuoteSide {
103        self.side
104    }
105
106    /// Returns the range of time the ticks fall inside.
107    #[must_use]
108    pub const fn range(&self) -> TimeRange {
109        self.range
110    }
111
112    /// Returns the largest number of ticks in the answer, when one is set.
113    #[must_use]
114    pub const fn max_ticks(&self) -> Option<usize> {
115        self.limit
116    }
117}
118
119const fn wire_side(side: QuoteSide) -> ProtoOaQuoteType {
120    match side {
121        QuoteSide::Bid => ProtoOaQuoteType::Bid,
122        QuoteSide::Ask => ProtoOaQuoteType::Ask,
123    }
124}
125
126fn decode(page: &[ProtoOaTickData]) -> Result<Vec<Tick>, ValueError> {
127    let mut ticks = Vec::with_capacity(page.len());
128    let (mut millis, mut raw) = (0_i64, 0_i64);
129    for wire in page {
130        millis = millis
131            .checked_add(wire.timestamp)
132            .ok_or(ValueError::OutOfRange {
133                kind: TICK_TIMESTAMP,
134            })?;
135        raw = raw
136            .checked_add(wire.tick)
137            .ok_or(ValueError::OutOfRange { kind: TICK_PRICE })?;
138        let timestamp = Timestamp::from_millis(millis).map_err(|_| ValueError::OutOfRange {
139            kind: TICK_TIMESTAMP,
140        })?;
141        let price = u64::try_from(raw)
142            .map_err(|_| ValueError::OutOfRange { kind: TICK_PRICE })
143            .and_then(wire_price)?;
144        ticks.push(Tick { timestamp, price });
145    }
146    Ok(ticks)
147}
148
149impl OpenApiClient {
150    /// Fetches the ticks of one side of a symbol inside a range of time, oldest first.
151    ///
152    /// Both ends of the range are included. On the wire a request covers the milliseconds from
153    /// `fromTimestamp` up to, but not including, `toTimestamp`, so every request ends one
154    /// millisecond after the last one it asks for.
155    ///
156    /// The server answers with a limited number of ticks per request, latest first, and accepts
157    /// at most [`TickDataParams::MAX_RANGE`] per request. A longer or busier range is fetched
158    /// with several requests, latest part first, each of which counts against the limit for
159    /// historical data. An answer that announces more ticks may have cut its oldest
160    /// millisecond short, so the ticks it brought of that millisecond are set aside and the
161    /// next request ends with that millisecond, which is then taken whole from the answer to
162    /// it. Every tick of the range is thus returned, and returned once. With a limit the
163    /// latest ticks are returned; which of several ticks sharing the oldest millisecond
164    /// returned are left out is not defined.
165    ///
166    /// # Errors
167    ///
168    /// Returns [`ConnectorError::Server`] when the server refuses a request,
169    /// [`ConnectorError::Value`] when a tick carries a value out of range or the range ends at
170    /// the last moment a timestamp can name, [`ConnectorError::Incomplete`] when the server
171    /// announces more ticks than it sends and the rest cannot be asked for, either because the
172    /// answer is empty or because all of it lies inside the millisecond the request ends with,
173    /// in which case no part of the range is returned, and the errors of
174    /// [`Connection::request`](crate::open_api::connection::Connection::request) otherwise.
175    pub async fn tick_data(&self, params: &TickDataParams) -> Result<Vec<Tick>, ConnectorError> {
176        let from = params.range.from().as_millis();
177        let wanted = params.limit.unwrap_or(usize::MAX);
178        let mut end = params.range.to().as_millis();
179        let mut ticks: Vec<Tick> = Vec::new();
180        while ticks.len() < wanted {
181            let start = end.saturating_sub(MAX_RANGE_MILLIS - 1).max(from);
182            let request = ProtoOaGetTickDataReq {
183                payload_type: None,
184                ctid_trader_account_id: params.account.get(),
185                symbol_id: params.symbol.get(),
186                r#type: i32::from(wire_side(params.side)),
187                from_timestamp: start,
188                to_timestamp: end.checked_add(1).ok_or(ValueError::OutOfRange {
189                    kind: TICK_TIMESTAMP,
190                })?,
191            };
192            let response = self.connection().request(&request).await?;
193            let mut page = decode(&response.tick_data)?;
194            page.retain(|tick| (start..=end).contains(&tick.timestamp.as_millis()));
195            let last = if response.has_more {
196                let oldest = page.iter().map(|tick| tick.timestamp.as_millis()).min();
197                let Some(oldest) = oldest.filter(|oldest| *oldest < end) else {
198                    return Err(ConnectorError::Incomplete {
199                        from: Timestamp::from_millis(start)?,
200                        to: Timestamp::from_millis(end)?,
201                    });
202                };
203                page.retain(|tick| tick.timestamp.as_millis() > oldest);
204                end = oldest;
205                false
206            } else if start > from {
207                end = start.saturating_sub(1);
208                false
209            } else {
210                true
211            };
212            ticks.append(&mut page);
213            if last {
214                break;
215            }
216        }
217        ticks.sort_by_key(|tick| std::cmp::Reverse(tick.timestamp));
218        ticks.truncate(wanted);
219        ticks.reverse();
220        Ok(ticks)
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use std::time::Duration;
227
228    use super::{Tick, TickDataParams, decode, wire_side};
229    use crate::common::errors::ValueError;
230    use crate::common::ids::{AccountId, SymbolId};
231    use crate::common::time::{TimeRange, Timestamp};
232    use crate::open_api::messages::{ProtoOaQuoteType, ProtoOaTickData};
233    use crate::open_api::quotes::QuoteSide;
234
235    fn wire(timestamp: i64, tick: i64) -> ProtoOaTickData {
236        ProtoOaTickData { timestamp, tick }
237    }
238
239    #[test]
240    fn ticks_after_the_first_are_differences_to_the_one_before() {
241        let ticks = decode(&[wire(1_000, 108_500), wire(-10, 3), wire(-5, -8)]).expect("ticks");
242        let seen: Vec<(i64, String)> = ticks
243            .iter()
244            .map(|tick: &Tick| (tick.timestamp.as_millis(), tick.price.to_string()))
245            .collect();
246        assert_eq!(
247            seen,
248            [
249                (1_000, "1.08500".to_owned()),
250                (990, "1.08503".to_owned()),
251                (985, "1.08495".to_owned())
252            ]
253        );
254        assert_eq!(decode(&[]), Ok(Vec::new()));
255    }
256
257    #[test]
258    fn ticks_that_leave_the_range_of_values_are_rejected() {
259        let timestamp = Err(ValueError::OutOfRange {
260            kind: "tick timestamp",
261        });
262        let price = Err(ValueError::OutOfRange { kind: "tick price" });
263        assert_eq!(decode(&[wire(-1, 1)]), timestamp);
264        assert_eq!(decode(&[wire(5, 1), wire(-6, 0)]), timestamp);
265        assert_eq!(decode(&[wire(i64::MAX, 1), wire(1, 0)]), timestamp);
266        assert_eq!(decode(&[wire(5, -1)]), price);
267        assert_eq!(decode(&[wire(5, 1), wire(0, -2)]), price);
268        assert_eq!(decode(&[wire(5, i64::MAX), wire(0, 1)]), price);
269    }
270
271    #[test]
272    fn parameters_keep_what_they_were_built_from() {
273        let account = AccountId::new(7).expect("account id");
274        let symbol = SymbolId::new(1).expect("symbol id");
275        let at = |millis| Timestamp::from_millis(millis).expect("timestamp");
276        let range = TimeRange::new(at(10), at(20)).expect("range");
277        let params = TickDataParams::new(account, symbol, QuoteSide::Ask, range);
278        assert_eq!(params.account(), account);
279        assert_eq!(params.symbol(), symbol);
280        assert_eq!(params.side(), QuoteSide::Ask);
281        assert_eq!(params.range(), range);
282        assert_eq!(params.max_ticks(), None);
283        assert_eq!(params.limit(3).max_ticks(), Some(3));
284        assert_eq!(TickDataParams::MAX_RANGE, Duration::from_secs(7 * 86_400));
285        assert_eq!(wire_side(QuoteSide::Bid), ProtoOaQuoteType::Bid);
286        assert_eq!(wire_side(QuoteSide::Ask), ProtoOaQuoteType::Ask);
287    }
288}