ctrader_connector/open_api/
ticks.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43#[non_exhaustive]
44pub struct Tick {
45 pub timestamp: Timestamp,
47 pub price: Price,
49}
50
51#[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 pub const MAX_RANGE: Duration = Duration::from_millis(MAX_RANGE_MILLIS.unsigned_abs());
65
66 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 pub const fn limit(mut self, limit: usize) -> Self {
84 self.limit = Some(limit);
85 self
86 }
87
88 #[must_use]
90 pub const fn account(&self) -> AccountId {
91 self.account
92 }
93
94 #[must_use]
96 pub const fn symbol(&self) -> SymbolId {
97 self.symbol
98 }
99
100 #[must_use]
102 pub const fn side(&self) -> QuoteSide {
103 self.side
104 }
105
106 #[must_use]
108 pub const fn range(&self) -> TimeRange {
109 self.range
110 }
111
112 #[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 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}