1use std::collections::BTreeMap;
24use std::time::Duration;
25
26use rust_decimal::Decimal;
27
28use crate::common::errors::{ConnectorError, ValueError};
29use crate::common::ids::{AccountId, CashFlowId};
30use crate::common::time::{TimeRange, Timestamp};
31use crate::open_api::client::OpenApiClient;
32use crate::open_api::messages::{
33 ProtoOaCashFlowHistoryListReq, ProtoOaChangeBalanceType, ProtoOaDealListReq,
34 ProtoOaDepositWithdraw, ProtoOaOrderListReq,
35};
36use crate::open_api::trading::{Deal, Order, money};
37
38const MAX_RANGE_MILLIS: i64 = 604_800_000;
39
40const HISTORY_TIMESTAMP: &str = "end of the range of history";
41const CASH_FLOW_KIND: &str = "kind of cash flow";
42
43pub const MAX_HISTORY_RANGE: Duration = Duration::from_millis(MAX_RANGE_MILLIS.unsigned_abs());
45
46#[derive(Debug)]
52pub(crate) struct Windows {
53 pending: Vec<(i64, i64)>,
54}
55
56impl Windows {
57 pub(crate) fn new(range: TimeRange) -> Result<Self, ValueError> {
59 let (from, to) = (range.from().as_millis(), range.to().as_millis());
60 let mut pending = Vec::new();
61 let mut start = from;
62 loop {
63 let end = start.saturating_add(MAX_RANGE_MILLIS).min(to);
64 pending.push(widened(start, end)?);
65 if end >= to {
66 break;
67 }
68 start = end.saturating_add(1);
69 }
70 Ok(Self { pending })
71 }
72
73 pub(crate) fn next(&mut self) -> Option<(i64, i64)> {
75 self.pending.pop()
76 }
77
78 pub(crate) fn split(&mut self, (from, to): (i64, i64)) -> Result<(), ConnectorError> {
83 let middle = to
84 .checked_sub(from)
85 .map(|length| length / 2)
86 .and_then(|half| from.checked_add(half))
87 .filter(|middle| from < *middle && *middle < to);
88 let Some(middle) = middle else {
89 return Err(ConnectorError::Incomplete {
90 from: Timestamp::from_millis(from)?,
91 to: Timestamp::from_millis(to)?,
92 });
93 };
94 self.pending.push((from, middle));
95 self.pending.push((middle, to));
96 Ok(())
97 }
98}
99
100fn inside(range: TimeRange, updated: Option<i64>) -> bool {
102 updated.is_none_or(|at| range.from().as_millis() <= at && at <= range.to().as_millis())
103}
104
105fn widened(start: i64, end: i64) -> Result<(i64, i64), ValueError> {
106 if start < end {
107 return Ok((start, end));
108 }
109 match start.checked_sub(1).filter(|before| *before >= 0) {
110 Some(before) => Ok((before, end)),
111 None => end
112 .checked_add(1)
113 .map(|after| (start, after))
114 .ok_or(ValueError::OutOfRange {
115 kind: HISTORY_TIMESTAMP,
116 }),
117 }
118}
119
120macro_rules! cash_flow_kinds {
121 ($($(#[$doc:meta])* $name:ident => $wire:ident, $deposit:literal;)*) => {
122 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
124 #[non_exhaustive]
125 pub enum CashFlowKind {
126 $($(#[$doc])* $name,)*
127 }
128
129 impl CashFlowKind {
130 fn from_wire(raw: i32) -> Result<Self, ValueError> {
131 match ProtoOaChangeBalanceType::try_from(raw) {
132 $(Ok(ProtoOaChangeBalanceType::$wire) => Ok(Self::$name),)*
133 Err(_) => Err(ValueError::OutOfRange { kind: CASH_FLOW_KIND }),
134 }
135 }
136
137 #[must_use]
140 pub const fn is_deposit(self) -> bool {
141 match self {
142 $(Self::$name => $deposit,)*
143 }
144 }
145 }
146 };
147}
148
149cash_flow_kinds! {
150 Deposit => BalanceDeposit, true;
152 Withdraw => BalanceWithdraw, false;
154 DepositStrategyCommissionInner => BalanceDepositStrategyCommissionInner, true;
156 WithdrawStrategyCommissionInner => BalanceWithdrawStrategyCommissionInner, false;
158 DepositIbCommissions => BalanceDepositIbCommissions, true;
160 WithdrawIbSharedPercentage => BalanceWithdrawIbSharedPercentage, false;
162 DepositIbSharedPercentageFromSubIb => BalanceDepositIbSharedPercentageFromSubIb, true;
164 DepositIbSharedPercentageFromBroker => BalanceDepositIbSharedPercentageFromBroker, true;
166 DepositRebate => BalanceDepositRebate, true;
168 WithdrawRebate => BalanceWithdrawRebate, false;
170 DepositStrategyCommissionOuter => BalanceDepositStrategyCommissionOuter, true;
172 WithdrawStrategyCommissionOuter => BalanceWithdrawStrategyCommissionOuter, false;
174 WithdrawBonusCompensation => BalanceWithdrawBonusCompensation, false;
176 WithdrawIbSharedPercentageToBroker => BalanceWithdrawIbSharedPercentageToBroker, false;
178 DepositDividends => BalanceDepositDividends, true;
180 WithdrawDividends => BalanceWithdrawDividends, false;
182 WithdrawGslCharge => BalanceWithdrawGslCharge, false;
184 WithdrawRollover => BalanceWithdrawRollover, false;
186 DepositNonwithdrawableBonus => BalanceDepositNonwithdrawableBonus, true;
188 WithdrawNonwithdrawableBonus => BalanceWithdrawNonwithdrawableBonus, false;
190 DepositSwap => BalanceDepositSwap, true;
192 WithdrawSwap => BalanceWithdrawSwap, false;
194 DepositManagementFee => BalanceDepositManagementFee, true;
196 WithdrawManagementFee => BalanceWithdrawManagementFee, false;
198 DepositPerformanceFee => BalanceDepositPerformanceFee, true;
200 WithdrawForSubaccount => BalanceWithdrawForSubaccount, false;
202 DepositToSubaccount => BalanceDepositToSubaccount, true;
204 WithdrawFromSubaccount => BalanceWithdrawFromSubaccount, false;
206 DepositFromSubaccount => BalanceDepositFromSubaccount, true;
208 WithdrawCopyFee => BalanceWithdrawCopyFee, false;
210 WithdrawInactivityFee => BalanceWithdrawInactivityFee, false;
212 DepositTransfer => BalanceDepositTransfer, true;
214 WithdrawTransfer => BalanceWithdrawTransfer, false;
216 DepositConvertedBonus => BalanceDepositConvertedBonus, true;
218 DepositNegativeBalanceProtection => BalanceDepositNegativeBalanceProtection, true;
220}
221
222#[derive(Debug, Clone, PartialEq, Eq, Hash)]
225#[non_exhaustive]
226pub struct CashFlow {
227 pub id: CashFlowId,
229 pub kind: CashFlowKind,
231 pub amount: Decimal,
234 pub balance: Decimal,
236 pub equity: Option<Decimal>,
238 pub at: Timestamp,
240 pub note: Option<String>,
242 pub balance_version: Option<i64>,
244}
245
246impl TryFrom<ProtoOaDepositWithdraw> for CashFlow {
247 type Error = ValueError;
248
249 fn try_from(change: ProtoOaDepositWithdraw) -> Result<Self, Self::Error> {
250 let digits = change.money_digits;
251 Ok(Self {
252 id: CashFlowId::new(change.balance_history_id)?,
253 kind: CashFlowKind::from_wire(change.operation_type)?,
254 amount: money(change.delta, digits)?,
255 balance: money(change.balance, digits)?,
256 equity: change.equity.map(|raw| money(raw, digits)).transpose()?,
257 at: Timestamp::from_millis(change.change_balance_timestamp)?,
258 note: change.external_note,
259 balance_version: change.balance_version,
260 })
261 }
262}
263
264impl OpenApiClient {
265 pub async fn deal_history(
287 &self,
288 account: AccountId,
289 range: TimeRange,
290 ) -> Result<Vec<Deal>, ConnectorError> {
291 let mut windows = Windows::new(range)?;
292 let mut deals = BTreeMap::new();
293 while let Some((from, to)) = windows.next() {
294 let request = ProtoOaDealListReq {
295 payload_type: None,
296 ctid_trader_account_id: account.get(),
297 from_timestamp: from,
298 to_timestamp: to,
299 max_rows: None,
300 };
301 let response = self.connection().request(&request).await?;
302 if response.has_more {
303 windows.split((from, to))?;
304 continue;
305 }
306 for deal in response.deal {
307 let updated = deal.utc_last_update_timestamp;
308 let deal = Deal::try_from(deal)?;
309 if inside(range, updated) {
310 deals.insert(deal.id, deal);
311 }
312 }
313 }
314 let mut deals: Vec<Deal> = deals.into_values().collect();
315 deals.sort_by_key(|deal| (deal.executed, deal.id));
316 Ok(deals)
317 }
318
319 pub async fn order_history(
330 &self,
331 account: AccountId,
332 range: TimeRange,
333 ) -> Result<Vec<Order>, ConnectorError> {
334 let mut windows = Windows::new(range)?;
335 let mut orders = BTreeMap::new();
336 while let Some((from, to)) = windows.next() {
337 let request = ProtoOaOrderListReq {
338 payload_type: None,
339 ctid_trader_account_id: account.get(),
340 from_timestamp: from,
341 to_timestamp: to,
342 };
343 let response = self.connection().request(&request).await?;
344 if response.has_more {
345 windows.split((from, to))?;
346 continue;
347 }
348 for order in response.order {
349 let updated = order.utc_last_update_timestamp;
350 let order = Order::try_from(order)?;
351 if inside(range, updated) {
352 orders.insert(order.id, order);
353 }
354 }
355 }
356 let mut orders: Vec<Order> = orders.into_values().collect();
357 orders.sort_by_key(|order| (order.updated, order.id));
358 Ok(orders)
359 }
360
361 pub async fn cash_flow_history(
376 &self,
377 account: AccountId,
378 range: TimeRange,
379 ) -> Result<Vec<CashFlow>, ConnectorError> {
380 let mut windows = Windows::new(range)?;
381 let mut changes = BTreeMap::new();
382 while let Some((from, to)) = windows.next() {
383 let request = ProtoOaCashFlowHistoryListReq {
384 payload_type: None,
385 ctid_trader_account_id: account.get(),
386 from_timestamp: from,
387 to_timestamp: to,
388 };
389 let response = self.connection().request(&request).await?;
390 for change in response.deposit_withdraw {
391 let change = CashFlow::try_from(change)?;
392 if inside(range, Some(change.at.as_millis())) {
393 changes.insert(change.id, change);
394 }
395 }
396 }
397 let mut changes: Vec<CashFlow> = changes.into_values().collect();
398 changes.sort_by_key(|change| (change.at, change.id));
399 Ok(changes)
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use std::time::Duration;
406
407 use super::{CashFlow, CashFlowKind, MAX_HISTORY_RANGE, MAX_RANGE_MILLIS, Windows, widened};
408 use crate::common::errors::{ConnectorError, ValueError};
409 use crate::common::time::{TimeRange, Timestamp};
410 use crate::open_api::messages::{
411 ProtoOaChangeBalanceType, ProtoOaDepositWithdraw, ProtoOaExecutionEvent,
412 };
413 use crate::open_api::trading::{Execution, ExecutionType};
414
415 fn range(from: i64, to: i64) -> TimeRange {
416 let at = |millis| Timestamp::from_millis(millis).expect("timestamp");
417 TimeRange::new(at(from), at(to)).expect("range")
418 }
419
420 fn all(mut windows: Windows) -> Vec<(i64, i64)> {
421 std::iter::from_fn(|| windows.next()).collect()
422 }
423
424 #[test]
425 fn range_is_cut_into_parts_the_server_accepts_latest_first() {
426 assert_eq!(MAX_HISTORY_RANGE, Duration::from_secs(7 * 86_400));
427 let week = MAX_RANGE_MILLIS;
428 assert_eq!(
429 all(Windows::new(range(10, 20)).expect("windows")),
430 [(10, 20)]
431 );
432 assert_eq!(
433 all(Windows::new(range(10, 10 + week)).expect("windows")),
434 [(10, 10 + week)]
435 );
436 assert_eq!(
437 all(Windows::new(range(10, 12 + 2 * week)).expect("windows")),
438 [
439 (11 + 2 * week, 12 + 2 * week),
440 (11 + week, 11 + 2 * week),
441 (10, 10 + week)
442 ]
443 );
444 }
445
446 #[test]
447 fn part_of_one_millisecond_is_widened_to_two() {
448 let week = MAX_RANGE_MILLIS;
449 assert_eq!(
450 all(Windows::new(range(10, 10)).expect("windows")),
451 [(9, 10)]
452 );
453 assert_eq!(all(Windows::new(range(0, 0)).expect("windows")), [(0, 1)]);
454 assert_eq!(
455 all(Windows::new(range(10, 11 + week)).expect("windows")),
456 [(10 + week, 11 + week), (10, 10 + week)]
457 );
458 assert_eq!(
459 widened(-5, -5),
460 Ok((-5, -4)),
461 "a moment before the epoch is widened forwards"
462 );
463 assert_eq!(
464 widened(i64::MAX, i64::MAX).map_err(|error| error.to_string()),
465 Ok((i64::MAX - 1, i64::MAX))
466 );
467 assert_eq!(
468 widened(-1, i64::MAX).map_err(|error| error.to_string()),
469 Ok((-1, i64::MAX))
470 );
471 assert!(matches!(
472 widened(i64::MIN, i64::MIN),
473 Ok((i64::MIN, end)) if end == i64::MIN + 1
474 ));
475 }
476
477 #[test]
478 fn part_is_halved_until_it_is_too_short() {
479 let mut windows = Windows::new(range(10, 20)).expect("windows");
480 let whole = windows.next().expect("window");
481 windows.split(whole).expect("halves");
482 assert_eq!(windows.next(), Some((15, 20)));
483 assert_eq!(windows.next(), Some((10, 15)));
484 windows.split((10, 12)).expect("halves");
485 assert_eq!(all(windows), [(11, 12), (10, 11)]);
486 let mut windows = Windows::new(range(10, 11)).expect("windows");
487 let at = |millis| Timestamp::from_millis(millis).expect("timestamp");
488 assert_eq!(
489 windows.split((10, 11)),
490 Err(ConnectorError::Incomplete {
491 from: at(10),
492 to: at(11)
493 })
494 );
495 assert!(windows.split((i64::MIN, i64::MAX)).is_err());
496 }
497
498 #[test]
499 fn every_kind_of_cash_flow_of_the_wire_is_known_with_its_direction() {
500 let mut known = 0;
501 for raw in -1..=64 {
502 match ProtoOaChangeBalanceType::try_from(raw) {
503 Ok(wire) => {
504 let kind = CashFlowKind::from_wire(raw).expect("kind");
505 assert_eq!(
506 kind.is_deposit(),
507 wire.as_str_name().starts_with("BALANCE_DEPOSIT"),
508 "{}",
509 wire.as_str_name()
510 );
511 known += 1;
512 }
513 Err(_) => assert_eq!(
514 CashFlowKind::from_wire(raw),
515 Err(ValueError::OutOfRange {
516 kind: "kind of cash flow"
517 })
518 ),
519 }
520 }
521 assert_eq!(known, 35);
522 assert_eq!(CashFlowKind::from_wire(1), Ok(CashFlowKind::Withdraw));
523 }
524
525 #[test]
526 fn execution_event_carries_the_cash_flow_it_reports() {
527 let change = ProtoOaDepositWithdraw {
528 operation_type: 0,
529 balance_history_id: 77,
530 balance: 150_000,
531 delta: 100_000,
532 change_balance_timestamp: 1_000,
533 external_note: Some("first deposit".to_owned()),
534 balance_version: Some(3),
535 equity: Some(150_100),
536 money_digits: Some(2),
537 };
538 let event = ProtoOaExecutionEvent {
539 ctid_trader_account_id: 101,
540 execution_type: 10,
541 deposit_withdraw: Some(change.clone()),
542 ..ProtoOaExecutionEvent::default()
543 };
544 let execution = Execution::try_from(event).expect("execution");
545 assert_eq!(execution.kind, ExecutionType::DepositWithdraw);
546 let flow = execution.cash_flow.expect("cash flow");
547 assert_eq!(flow.id.get(), 77);
548 assert_eq!(flow.kind, CashFlowKind::Deposit);
549 assert_eq!(flow.amount.to_string(), "1000.00");
550 assert_eq!(flow.balance.to_string(), "1500.00");
551 assert_eq!(
552 flow.equity.map(|equity| equity.to_string()).as_deref(),
553 Some("1501.00")
554 );
555 assert_eq!(flow.at.as_millis(), 1_000);
556 assert_eq!(flow.note.as_deref(), Some("first deposit"));
557 assert_eq!(flow.balance_version, Some(3));
558 assert!(
559 CashFlow::try_from(ProtoOaDepositWithdraw {
560 balance_history_id: 0,
561 ..change
562 })
563 .is_err()
564 );
565 }
566}