1use rust_decimal::Decimal;
37use rust_decimal::prelude::ToPrimitive;
38
39use crate::common::decimals::{PRICE_SCALE, Price, Volume};
40use crate::common::errors::{ConnectorError, ErrorCode, ServerError, ValueError};
41use crate::common::ids::{AccountId, DealId, OrderId, PositionId, SymbolId};
42use crate::common::time::Timestamp;
43use crate::open_api::client::OpenApiClient;
44use crate::open_api::history::CashFlow;
45use crate::open_api::messages::{
46 ProtoMessage, ProtoOaAmendOrderReq, ProtoOaAmendPositionSltpReq, ProtoOaCancelOrderReq,
47 ProtoOaClosePositionDetail, ProtoOaClosePositionReq, ProtoOaDeal, ProtoOaDealStatus,
48 ProtoOaExecutionEvent, ProtoOaExecutionType, ProtoOaNewOrderReq, ProtoOaOrder,
49 ProtoOaOrderErrorEvent, ProtoOaOrderStatus, ProtoOaOrderType, ProtoOaPosition,
50 ProtoOaPositionStatus, ProtoOaReconcileReq, ProtoOaReconcileRes, ProtoOaTimeInForce,
51 ProtoOaTradeSide,
52};
53use crate::open_api::payload::Payload;
54use crate::open_api::symbols::Symbol;
55
56pub const MAX_LABEL_LENGTH: usize = 100;
58pub const MAX_COMMENT_LENGTH: usize = 512;
60
61pub(crate) const DEFAULT_MONEY_DIGITS: u32 = 2;
62
63const LABEL: &str = "label";
64const COMMENT: &str = "comment";
65const VOLUME: &str = "volume";
66const PRICE: &str = "price";
67const MONEY: &str = "amount of money";
68const DISTANCE: &str = "distance of the protection";
69const SYMBOL: &str = "symbol of the order";
70const TRADE_SIDE: &str = "trade side";
71const ORDER_TYPE: &str = "order type";
72const ORDER_STATUS: &str = "order status";
73const TIME_IN_FORCE: &str = "time in force";
74const EXPIRY: &str = "expiry of the order";
75const POSITION_STATUS: &str = "position status";
76const DEAL_STATUS: &str = "deal status";
77const EXECUTION_TYPE: &str = "execution type";
78const SLIPPAGE: &str = "slippage in points";
79const PROTECTION: &str = "protection given as a price";
80const AMENDMENT: &str = "amendment of an order that does not wait at a price";
81
82macro_rules! text {
83 ($(#[$doc:meta])* $name:ident, $kind:expr, $limit:expr) => {
84 $(#[$doc])*
85 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
86 pub struct $name(String);
87
88 impl $name {
89 pub fn new(text: impl Into<String>) -> Result<Self, ValueError> {
96 let text = text.into();
97 let length = text.chars().count();
98 if length > $limit {
99 return Err(ValueError::TooLong {
100 kind: $kind,
101 length,
102 limit: $limit,
103 });
104 }
105 Ok(Self(text))
106 }
107
108 #[must_use]
110 pub fn as_str(&self) -> &str {
111 &self.0
112 }
113 }
114
115 impl std::fmt::Display for $name {
116 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 formatter.write_str(&self.0)
118 }
119 }
120 };
121}
122
123text!(
124 Label,
127 LABEL,
128 MAX_LABEL_LENGTH
129);
130text!(
131 Comment,
134 COMMENT,
135 MAX_COMMENT_LENGTH
136);
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
140pub enum TradeSide {
141 Buy,
143 Sell,
145}
146
147impl TradeSide {
148 #[must_use]
150 pub const fn opposite(self) -> Self {
151 match self {
152 Self::Buy => Self::Sell,
153 Self::Sell => Self::Buy,
154 }
155 }
156
157 const fn to_wire(self) -> ProtoOaTradeSide {
158 match self {
159 Self::Buy => ProtoOaTradeSide::Buy,
160 Self::Sell => ProtoOaTradeSide::Sell,
161 }
162 }
163
164 fn from_wire(raw: i32) -> Result<Self, ValueError> {
165 match ProtoOaTradeSide::try_from(raw) {
166 Ok(ProtoOaTradeSide::Buy) => Ok(Self::Buy),
167 Ok(ProtoOaTradeSide::Sell) => Ok(Self::Sell),
168 Err(_) => Err(ValueError::OutOfRange { kind: TRADE_SIDE }),
169 }
170 }
171}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175#[non_exhaustive]
176pub enum OrderType {
177 Market,
179 Limit,
181 Stop,
183 StopLossTakeProfit,
185 MarketRange,
187 StopLimit,
189}
190
191impl OrderType {
192 fn from_wire(raw: i32) -> Result<Self, ValueError> {
193 match ProtoOaOrderType::try_from(raw) {
194 Ok(ProtoOaOrderType::Market) => Ok(Self::Market),
195 Ok(ProtoOaOrderType::Limit) => Ok(Self::Limit),
196 Ok(ProtoOaOrderType::Stop) => Ok(Self::Stop),
197 Ok(ProtoOaOrderType::StopLossTakeProfit) => Ok(Self::StopLossTakeProfit),
198 Ok(ProtoOaOrderType::MarketRange) => Ok(Self::MarketRange),
199 Ok(ProtoOaOrderType::StopLimit) => Ok(Self::StopLimit),
200 Err(_) => Err(ValueError::OutOfRange { kind: ORDER_TYPE }),
201 }
202 }
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
207#[non_exhaustive]
208pub enum OrderStatus {
209 Accepted,
211 Filled,
213 Rejected,
215 Expired,
217 Cancelled,
219}
220
221impl OrderStatus {
222 fn from_wire(raw: i32) -> Result<Self, ValueError> {
223 match ProtoOaOrderStatus::try_from(raw) {
224 Ok(ProtoOaOrderStatus::OrderStatusAccepted) => Ok(Self::Accepted),
225 Ok(ProtoOaOrderStatus::OrderStatusFilled) => Ok(Self::Filled),
226 Ok(ProtoOaOrderStatus::OrderStatusRejected) => Ok(Self::Rejected),
227 Ok(ProtoOaOrderStatus::OrderStatusExpired) => Ok(Self::Expired),
228 Ok(ProtoOaOrderStatus::OrderStatusCancelled) => Ok(Self::Cancelled),
229 Err(_) => Err(ValueError::OutOfRange { kind: ORDER_STATUS }),
230 }
231 }
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
236#[non_exhaustive]
237pub enum TimeInForce {
238 GoodTillDate(Timestamp),
240 GoodTillCancel,
242 ImmediateOrCancel,
244 FillOrKill,
246 MarketOnOpen,
248}
249
250impl TimeInForce {
251 fn from_wire(raw: Option<i32>, expiry: Option<i64>) -> Result<Self, ValueError> {
252 let wire = raw.map_or(Ok(ProtoOaTimeInForce::ImmediateOrCancel), |raw| {
253 ProtoOaTimeInForce::try_from(raw)
254 });
255 match wire {
256 Ok(ProtoOaTimeInForce::GoodTillDate) => expiry
257 .ok_or(ValueError::Missing { kind: EXPIRY })
258 .and_then(Timestamp::from_millis)
259 .map(Self::GoodTillDate),
260 Ok(ProtoOaTimeInForce::GoodTillCancel) => Ok(Self::GoodTillCancel),
261 Ok(ProtoOaTimeInForce::ImmediateOrCancel) => Ok(Self::ImmediateOrCancel),
262 Ok(ProtoOaTimeInForce::FillOrKill) => Ok(Self::FillOrKill),
263 Ok(ProtoOaTimeInForce::MarketOnOpen) => Ok(Self::MarketOnOpen),
264 Err(_) => Err(ValueError::OutOfRange {
265 kind: TIME_IN_FORCE,
266 }),
267 }
268 }
269}
270
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
273#[non_exhaustive]
274pub enum PositionStatus {
275 Open,
277 Closed,
279 Created,
281 Error,
283}
284
285impl PositionStatus {
286 fn from_wire(raw: i32) -> Result<Self, ValueError> {
287 match ProtoOaPositionStatus::try_from(raw) {
288 Ok(ProtoOaPositionStatus::PositionStatusOpen) => Ok(Self::Open),
289 Ok(ProtoOaPositionStatus::PositionStatusClosed) => Ok(Self::Closed),
290 Ok(ProtoOaPositionStatus::PositionStatusCreated) => Ok(Self::Created),
291 Ok(ProtoOaPositionStatus::PositionStatusError) => Ok(Self::Error),
292 Err(_) => Err(ValueError::OutOfRange {
293 kind: POSITION_STATUS,
294 }),
295 }
296 }
297}
298
299#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
301#[non_exhaustive]
302pub enum DealStatus {
303 Filled,
305 PartiallyFilled,
307 Rejected,
309 InternallyRejected,
311 Error,
313 Missed,
315}
316
317impl DealStatus {
318 fn from_wire(raw: i32) -> Result<Self, ValueError> {
319 match ProtoOaDealStatus::try_from(raw) {
320 Ok(ProtoOaDealStatus::Filled) => Ok(Self::Filled),
321 Ok(ProtoOaDealStatus::PartiallyFilled) => Ok(Self::PartiallyFilled),
322 Ok(ProtoOaDealStatus::Rejected) => Ok(Self::Rejected),
323 Ok(ProtoOaDealStatus::InternallyRejected) => Ok(Self::InternallyRejected),
324 Ok(ProtoOaDealStatus::Error) => Ok(Self::Error),
325 Ok(ProtoOaDealStatus::Missed) => Ok(Self::Missed),
326 Err(_) => Err(ValueError::OutOfRange { kind: DEAL_STATUS }),
327 }
328 }
329}
330
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
333#[non_exhaustive]
334pub enum ExecutionType {
335 Accepted,
337 Filled,
339 Replaced,
341 Cancelled,
343 Expired,
345 Rejected,
347 CancelRejected,
349 Swap,
351 DepositWithdraw,
353 PartiallyFilled,
355 BonusDepositWithdraw,
357}
358
359impl ExecutionType {
360 fn from_wire(raw: i32) -> Result<Self, ValueError> {
361 match ProtoOaExecutionType::try_from(raw) {
362 Ok(ProtoOaExecutionType::OrderAccepted) => Ok(Self::Accepted),
363 Ok(ProtoOaExecutionType::OrderFilled) => Ok(Self::Filled),
364 Ok(ProtoOaExecutionType::OrderReplaced) => Ok(Self::Replaced),
365 Ok(ProtoOaExecutionType::OrderCancelled) => Ok(Self::Cancelled),
366 Ok(ProtoOaExecutionType::OrderExpired) => Ok(Self::Expired),
367 Ok(ProtoOaExecutionType::OrderRejected) => Ok(Self::Rejected),
368 Ok(ProtoOaExecutionType::OrderCancelRejected) => Ok(Self::CancelRejected),
369 Ok(ProtoOaExecutionType::Swap) => Ok(Self::Swap),
370 Ok(ProtoOaExecutionType::DepositWithdraw) => Ok(Self::DepositWithdraw),
371 Ok(ProtoOaExecutionType::OrderPartialFill) => Ok(Self::PartiallyFilled),
372 Ok(ProtoOaExecutionType::BonusDepositWithdraw) => Ok(Self::BonusDepositWithdraw),
373 Err(_) => Err(ValueError::OutOfRange {
374 kind: EXECUTION_TYPE,
375 }),
376 }
377 }
378}
379
380pub(crate) fn double_price(raw: f64) -> Result<Price, ValueError> {
382 let value = Decimal::try_from(raw).map_err(|_| ValueError::OutOfRange { kind: PRICE })?;
383 Price::new(value.round_dp(PRICE_SCALE))
384}
385
386fn optional_price(raw: Option<f64>) -> Result<Option<Price>, ValueError> {
387 raw.map(double_price).transpose()
388}
389
390fn relative_price(raw: Option<i64>) -> Result<Option<Price>, ValueError> {
391 raw.map(|raw| {
392 u64::try_from(raw)
393 .map_err(|_| ValueError::OutOfRange { kind: DISTANCE })
394 .and_then(|raw| Price::from_wire(raw, PRICE_SCALE))
395 })
396 .transpose()
397}
398
399pub(crate) fn money(raw: i64, digits: Option<u32>) -> Result<Decimal, ValueError> {
401 Decimal::try_new(raw, digits.unwrap_or(DEFAULT_MONEY_DIGITS))
402 .map_err(|_| ValueError::OutOfRange { kind: MONEY })
403}
404
405fn moment(raw: Option<i64>) -> Result<Option<Timestamp>, ValueError> {
406 raw.map(Timestamp::from_millis).transpose()
407}
408
409#[derive(Debug, Clone, PartialEq, Eq, Hash)]
411#[non_exhaustive]
412pub struct Order {
413 pub id: OrderId,
415 pub symbol: SymbolId,
417 pub side: TradeSide,
419 pub volume: Volume,
421 pub kind: OrderType,
423 pub status: OrderStatus,
425 pub time_in_force: TimeInForce,
427 pub limit_price: Option<Price>,
429 pub stop_price: Option<Price>,
431 pub stop_loss: Option<Price>,
433 pub take_profit: Option<Price>,
435 pub relative_stop_loss: Option<Price>,
437 pub relative_take_profit: Option<Price>,
439 pub slippage_points: Option<u32>,
441 pub executed_volume: Option<Volume>,
443 pub execution_price: Option<Price>,
445 pub position: Option<PositionId>,
447 pub label: Option<String>,
449 pub comment: Option<String>,
451 pub client_order_id: Option<String>,
453 pub closing: bool,
455 pub trailing_stop_loss: bool,
457 pub opened: Option<Timestamp>,
459 pub updated: Option<Timestamp>,
461}
462
463impl TryFrom<ProtoOaOrder> for Order {
464 type Error = ValueError;
465
466 fn try_from(order: ProtoOaOrder) -> Result<Self, Self::Error> {
467 let data = order.trade_data;
468 Ok(Self {
469 id: OrderId::new(order.order_id)?,
470 symbol: SymbolId::new(data.symbol_id)?,
471 side: TradeSide::from_wire(data.trade_side)?,
472 volume: Volume::from_wire(data.volume)?,
473 kind: OrderType::from_wire(order.order_type)?,
474 status: OrderStatus::from_wire(order.order_status)?,
475 time_in_force: TimeInForce::from_wire(order.time_in_force, order.expiration_timestamp)?,
476 limit_price: optional_price(order.limit_price)?,
477 stop_price: optional_price(order.stop_price)?,
478 stop_loss: optional_price(order.stop_loss)?,
479 take_profit: optional_price(order.take_profit)?,
480 relative_stop_loss: relative_price(order.relative_stop_loss)?,
481 relative_take_profit: relative_price(order.relative_take_profit)?,
482 slippage_points: order
483 .slippage_in_points
484 .map(|points| {
485 u32::try_from(points).map_err(|_| ValueError::OutOfRange { kind: SLIPPAGE })
486 })
487 .transpose()?,
488 executed_volume: order.executed_volume.map(Volume::from_wire).transpose()?,
489 execution_price: optional_price(order.execution_price)?,
490 position: order
491 .position_id
492 .filter(|id| *id != 0)
493 .map(PositionId::new)
494 .transpose()?,
495 label: data.label,
496 comment: data.comment,
497 client_order_id: order.client_order_id,
498 closing: order.closing_order.unwrap_or(false),
499 trailing_stop_loss: order.trailing_stop_loss.unwrap_or(false),
500 opened: moment(data.open_timestamp)?,
501 updated: moment(order.utc_last_update_timestamp)?,
502 })
503 }
504}
505
506#[derive(Debug, Clone, PartialEq, Eq, Hash)]
508#[non_exhaustive]
509pub struct Position {
510 pub id: PositionId,
512 pub symbol: SymbolId,
514 pub side: TradeSide,
516 pub volume: Volume,
518 pub status: PositionStatus,
520 pub price: Option<Price>,
522 pub stop_loss: Option<Price>,
524 pub take_profit: Option<Price>,
526 pub swap: Decimal,
528 pub commission: Option<Decimal>,
530 pub used_margin: Option<Decimal>,
532 pub label: Option<String>,
534 pub comment: Option<String>,
536 pub guaranteed_stop_loss: bool,
538 pub trailing_stop_loss: bool,
540 pub opened: Option<Timestamp>,
542 pub updated: Option<Timestamp>,
544}
545
546impl TryFrom<ProtoOaPosition> for Position {
547 type Error = ValueError;
548
549 fn try_from(position: ProtoOaPosition) -> Result<Self, Self::Error> {
550 let data = position.trade_data;
551 let digits = position.money_digits;
552 Ok(Self {
553 id: PositionId::new(position.position_id)?,
554 symbol: SymbolId::new(data.symbol_id)?,
555 side: TradeSide::from_wire(data.trade_side)?,
556 volume: Volume::from_wire(data.volume)?,
557 status: PositionStatus::from_wire(position.position_status)?,
558 price: optional_price(position.price)?,
559 stop_loss: optional_price(position.stop_loss)?,
560 take_profit: optional_price(position.take_profit)?,
561 swap: money(position.swap, digits)?,
562 commission: position
563 .commission
564 .map(|raw| money(raw, digits))
565 .transpose()?,
566 used_margin: position
567 .used_margin
568 .map(|raw| {
569 i64::try_from(raw)
570 .map_err(|_| ValueError::OutOfRange { kind: MONEY })
571 .and_then(|raw| money(raw, digits))
572 })
573 .transpose()?,
574 label: data.label,
575 comment: data.comment,
576 guaranteed_stop_loss: position.guaranteed_stop_loss.unwrap_or(false),
577 trailing_stop_loss: position.trailing_stop_loss.unwrap_or(false),
578 opened: moment(data.open_timestamp)?,
579 updated: moment(position.utc_last_update_timestamp)?,
580 })
581 }
582}
583
584#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
586#[non_exhaustive]
587pub struct ClosingDetail {
588 pub entry_price: Price,
590 pub gross_profit: Decimal,
592 pub swap: Decimal,
594 pub commission: Decimal,
596 pub balance: Decimal,
598 pub closed_volume: Option<Volume>,
600}
601
602impl TryFrom<ProtoOaClosePositionDetail> for ClosingDetail {
603 type Error = ValueError;
604
605 fn try_from(detail: ProtoOaClosePositionDetail) -> Result<Self, Self::Error> {
606 let digits = detail.money_digits;
607 Ok(Self {
608 entry_price: double_price(detail.entry_price)?,
609 gross_profit: money(detail.gross_profit, digits)?,
610 swap: money(detail.swap, digits)?,
611 commission: money(detail.commission, digits)?,
612 balance: money(detail.balance, digits)?,
613 closed_volume: detail.closed_volume.map(Volume::from_wire).transpose()?,
614 })
615 }
616}
617
618#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
620#[non_exhaustive]
621pub struct Deal {
622 pub id: DealId,
624 pub order: OrderId,
626 pub position: PositionId,
628 pub symbol: SymbolId,
630 pub side: TradeSide,
632 pub volume: Volume,
634 pub filled_volume: Volume,
636 pub status: DealStatus,
638 pub created: Timestamp,
640 pub executed: Timestamp,
642 pub execution_price: Option<Price>,
644 pub commission: Option<Decimal>,
646 pub closing: Option<ClosingDetail>,
648}
649
650impl TryFrom<ProtoOaDeal> for Deal {
651 type Error = ValueError;
652
653 fn try_from(deal: ProtoOaDeal) -> Result<Self, Self::Error> {
654 let digits = deal.money_digits;
655 Ok(Self {
656 id: DealId::new(deal.deal_id)?,
657 order: OrderId::new(deal.order_id)?,
658 position: PositionId::new(deal.position_id)?,
659 symbol: SymbolId::new(deal.symbol_id)?,
660 side: TradeSide::from_wire(deal.trade_side)?,
661 volume: Volume::from_wire(deal.volume)?,
662 filled_volume: Volume::from_wire(deal.filled_volume)?,
663 status: DealStatus::from_wire(deal.deal_status)?,
664 created: Timestamp::from_millis(deal.create_timestamp)?,
665 executed: Timestamp::from_millis(deal.execution_timestamp)?,
666 execution_price: optional_price(deal.execution_price)?,
667 commission: deal.commission.map(|raw| money(raw, digits)).transpose()?,
668 closing: deal
669 .close_position_detail
670 .map(ClosingDetail::try_from)
671 .transpose()?,
672 })
673 }
674}
675
676#[derive(Debug, Clone, PartialEq, Eq, Hash)]
678#[non_exhaustive]
679pub struct Execution {
680 pub account: AccountId,
682 pub kind: ExecutionType,
684 pub order: Option<Order>,
686 pub position: Option<Position>,
688 pub deal: Option<Deal>,
690 pub cash_flow: Option<CashFlow>,
692 pub error_code: Option<ErrorCode>,
694 pub server_event: bool,
697}
698
699impl TryFrom<ProtoOaExecutionEvent> for Execution {
700 type Error = ValueError;
701
702 fn try_from(event: ProtoOaExecutionEvent) -> Result<Self, Self::Error> {
703 Ok(Self {
704 account: AccountId::new(event.ctid_trader_account_id)?,
705 kind: ExecutionType::from_wire(event.execution_type)?,
706 order: event.order.map(Order::try_from).transpose()?,
707 position: event.position.map(Position::try_from).transpose()?,
708 deal: event.deal.map(Deal::try_from).transpose()?,
709 cash_flow: event.deposit_withdraw.map(CashFlow::try_from).transpose()?,
710 error_code: event.error_code.as_deref().map(ErrorCode::from_wire),
711 server_event: event.is_server_event.unwrap_or(false),
712 })
713 }
714}
715
716#[derive(Debug, Clone, PartialEq, Eq, Hash)]
718#[non_exhaustive]
719pub struct Reconciliation {
720 pub account: AccountId,
722 pub positions: Vec<Position>,
724 pub orders: Vec<Order>,
727}
728
729impl TryFrom<ProtoOaReconcileRes> for Reconciliation {
730 type Error = ValueError;
731
732 fn try_from(answer: ProtoOaReconcileRes) -> Result<Self, Self::Error> {
733 Ok(Self {
734 account: AccountId::new(answer.ctid_trader_account_id)?,
735 positions: answer
736 .position
737 .into_iter()
738 .map(Position::try_from)
739 .collect::<Result<_, _>>()?,
740 orders: answer
741 .order
742 .into_iter()
743 .map(Order::try_from)
744 .collect::<Result<_, _>>()?,
745 })
746 }
747}
748
749impl From<ProtoOaOrderErrorEvent> for ServerError {
750 fn from(event: ProtoOaOrderErrorEvent) -> Self {
751 let error = Self::new(ErrorCode::from_wire(&event.error_code));
752 let error = match event.description {
753 Some(description) => error.with_description(description),
754 None => error,
755 };
756 match AccountId::new(event.ctid_trader_account_id) {
757 Ok(account) => error.with_account_id(account),
758 Err(_) => error,
759 }
760 }
761}
762
763fn refusal(execution: &Execution) -> ServerError {
764 let code = execution
765 .error_code
766 .clone()
767 .unwrap_or(ErrorCode::UnknownError);
768 let what = match execution.kind {
769 ExecutionType::CancelRejected => "the request to cancel the order was refused",
770 _ => "the order was refused",
771 };
772 ServerError::new(code)
773 .with_description(what)
774 .with_account_id(execution.account)
775}
776
777fn traded(message: &ProtoMessage) -> Result<Execution, ConnectorError> {
779 if message.payload_type == ProtoOaOrderErrorEvent::PAYLOAD_TYPE {
780 return Err(ProtoOaOrderErrorEvent::from_message(message)
781 .map_or_else(|error| error, |event| ServerError::from(event).into()));
782 }
783 let execution = Execution::try_from(ProtoOaExecutionEvent::from_message(message)?)?;
784 match execution.kind {
785 ExecutionType::Rejected | ExecutionType::CancelRejected => Err(refusal(&execution).into()),
786 _ => Ok(execution),
787 }
788}
789
790fn checked_volume(volume: Volume, symbol: &Symbol) -> Result<i64, ValueError> {
791 let value = volume.value();
792 let smallest = Decimal::new(1, crate::common::decimals::VOLUME_SCALE);
793 let minimum = symbol.min_volume.map_or(smallest, Volume::value);
794 if value < minimum || value.is_zero() {
795 return Err(ValueError::BelowMinimum {
796 kind: VOLUME,
797 value,
798 minimum,
799 });
800 }
801 if let Some(maximum) = symbol.max_volume.map(Volume::value) {
802 if value > maximum {
803 return Err(ValueError::AboveMaximum {
804 kind: VOLUME,
805 value,
806 maximum,
807 });
808 }
809 }
810 on_step(value, symbol)?;
811 volume.to_wire()
812}
813
814fn on_step(value: Decimal, symbol: &Symbol) -> Result<(), ValueError> {
815 if let Some(step) = symbol.step_volume.map(Volume::value) {
816 let aligned = value.checked_rem(step).is_some_and(|rest| rest.is_zero());
817 if !step.is_zero() && !aligned {
818 return Err(ValueError::OffStep {
819 kind: VOLUME,
820 value,
821 step,
822 });
823 }
824 }
825 Ok(())
826}
827
828fn closing_volume(volume: Volume, position: &Position, symbol: &Symbol) -> Result<i64, ValueError> {
829 if symbol.id != position.symbol {
830 return Err(ValueError::Mismatch { kind: SYMBOL });
831 }
832 let value = volume.value();
833 if value.is_zero() {
834 return Err(ValueError::BelowMinimum {
835 kind: VOLUME,
836 value,
837 minimum: Decimal::new(1, crate::common::decimals::VOLUME_SCALE),
838 });
839 }
840 let whole = position.volume.value();
841 if value > whole {
842 return Err(ValueError::AboveMaximum {
843 kind: VOLUME,
844 value,
845 maximum: whole,
846 });
847 }
848 if value < whole {
849 on_step(value, symbol)?;
850 }
851 volume.to_wire()
852}
853
854fn checked_digits(price: Price, kind: &'static str, symbol: &Symbol) -> Result<Price, ValueError> {
855 let value = price.value();
856 if value.normalize().scale() > symbol.digits {
857 return Err(ValueError::TooFine {
858 kind,
859 value,
860 digits: symbol.digits,
861 });
862 }
863 Ok(price)
864}
865
866fn checked_slippage(points: u32, stop: Option<Price>, symbol: &Symbol) -> Result<i32, ValueError> {
867 let value = Decimal::from(points);
868 if points == 0 {
869 return Err(ValueError::BelowMinimum {
870 kind: SLIPPAGE,
871 value,
872 minimum: Decimal::ONE,
873 });
874 }
875 let point = Decimal::new(1, symbol.digits.min(PRICE_SCALE));
876 let furthest = stop
877 .and_then(|stop| stop.value().checked_div(point))
878 .map_or(Decimal::from(i32::MAX), |furthest| {
879 furthest.floor().min(Decimal::from(i32::MAX))
880 });
881 if value > furthest {
882 return Err(ValueError::AboveMaximum {
883 kind: SLIPPAGE,
884 value,
885 maximum: furthest,
886 });
887 }
888 i32::try_from(points).map_err(|_| ValueError::OutOfRange { kind: SLIPPAGE })
889}
890
891fn checked_distance(distance: Price, symbol: &Symbol) -> Result<i64, ValueError> {
892 let distance = checked_digits(distance, DISTANCE, symbol)?;
893 if distance.value().is_zero() {
894 return Err(ValueError::BelowMinimum {
895 kind: DISTANCE,
896 value: distance.value(),
897 minimum: Decimal::new(1, symbol.digits.min(PRICE_SCALE)),
898 });
899 }
900 i64::try_from(distance.to_wire()?).map_err(|_| ValueError::Unrepresentable {
901 kind: DISTANCE,
902 value: distance.value(),
903 })
904}
905
906fn checked_price(price: Price, kind: &'static str, symbol: &Symbol) -> Result<f64, ValueError> {
907 let value = checked_digits(price, kind, symbol)?.value();
908 if value.is_zero() {
909 return Err(ValueError::BelowMinimum {
910 kind,
911 value,
912 minimum: Decimal::new(1, symbol.digits.min(PRICE_SCALE)),
913 });
914 }
915 value
916 .to_f64()
917 .ok_or(ValueError::Unrepresentable { kind, value })
918}
919
920#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
921enum Terms {
922 Market,
923 Limit(Price),
924 Stop(Price),
925 StopLimit { stop: Price, slippage: u32 },
926}
927
928#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
929enum Protection {
930 At(Price),
931 Away(Price),
932}
933
934impl Protection {
935 fn price(self, market: bool, symbol: &Symbol) -> Result<Option<f64>, ValueError> {
936 match self {
937 Self::At(_) if market => Err(ValueError::Unsupported { kind: PROTECTION }),
938 Self::At(price) => checked_price(price, PROTECTION, symbol).map(Some),
939 Self::Away(_) => Ok(None),
940 }
941 }
942
943 fn distance(self, symbol: &Symbol) -> Result<Option<i64>, ValueError> {
944 match self {
945 Self::At(_) => Ok(None),
946 Self::Away(distance) => checked_distance(distance, symbol).map(Some),
947 }
948 }
949}
950
951#[derive(Debug, Clone, PartialEq, Eq, Hash)]
962#[must_use]
963pub struct NewOrder {
964 account: AccountId,
965 symbol: SymbolId,
966 side: TradeSide,
967 volume: Volume,
968 terms: Terms,
969 expiry: Option<Timestamp>,
970 label: Option<Label>,
971 comment: Option<Comment>,
972 stop_loss: Option<Protection>,
973 take_profit: Option<Protection>,
974}
975
976impl NewOrder {
977 const fn new(
978 account: AccountId,
979 symbol: SymbolId,
980 side: TradeSide,
981 volume: Volume,
982 terms: Terms,
983 ) -> Self {
984 Self {
985 account,
986 symbol,
987 side,
988 volume,
989 terms,
990 expiry: None,
991 label: None,
992 comment: None,
993 stop_loss: None,
994 take_profit: None,
995 }
996 }
997
998 pub const fn market(
1000 account: AccountId,
1001 symbol: SymbolId,
1002 side: TradeSide,
1003 volume: Volume,
1004 ) -> Self {
1005 Self::new(account, symbol, side, volume, Terms::Market)
1006 }
1007
1008 pub const fn limit(
1010 account: AccountId,
1011 symbol: SymbolId,
1012 side: TradeSide,
1013 volume: Volume,
1014 price: Price,
1015 ) -> Self {
1016 Self::new(account, symbol, side, volume, Terms::Limit(price))
1017 }
1018
1019 pub const fn stop(
1021 account: AccountId,
1022 symbol: SymbolId,
1023 side: TradeSide,
1024 volume: Volume,
1025 price: Price,
1026 ) -> Self {
1027 Self::new(account, symbol, side, volume, Terms::Stop(price))
1028 }
1029
1030 pub const fn stop_limit(
1040 account: AccountId,
1041 symbol: SymbolId,
1042 side: TradeSide,
1043 volume: Volume,
1044 stop: Price,
1045 slippage: u32,
1046 ) -> Self {
1047 Self::new(
1048 account,
1049 symbol,
1050 side,
1051 volume,
1052 Terms::StopLimit { stop, slippage },
1053 )
1054 }
1055
1056 pub const fn good_till(mut self, expiry: Timestamp) -> Self {
1060 self.expiry = Some(expiry);
1061 self
1062 }
1063
1064 pub fn label(mut self, label: Label) -> Self {
1066 self.label = Some(label);
1067 self
1068 }
1069
1070 pub fn comment(mut self, comment: Comment) -> Self {
1072 self.comment = Some(comment);
1073 self
1074 }
1075
1076 pub const fn stop_loss(mut self, price: Price) -> Self {
1080 self.stop_loss = Some(Protection::At(price));
1081 self
1082 }
1083
1084 pub const fn take_profit(mut self, price: Price) -> Self {
1088 self.take_profit = Some(Protection::At(price));
1089 self
1090 }
1091
1092 pub const fn stop_loss_distance(mut self, distance: Price) -> Self {
1095 self.stop_loss = Some(Protection::Away(distance));
1096 self
1097 }
1098
1099 pub const fn take_profit_distance(mut self, distance: Price) -> Self {
1102 self.take_profit = Some(Protection::Away(distance));
1103 self
1104 }
1105
1106 #[must_use]
1108 pub const fn account(&self) -> AccountId {
1109 self.account
1110 }
1111
1112 #[must_use]
1114 pub const fn symbol(&self) -> SymbolId {
1115 self.symbol
1116 }
1117
1118 #[must_use]
1120 pub const fn side(&self) -> TradeSide {
1121 self.side
1122 }
1123
1124 #[must_use]
1126 pub const fn volume(&self) -> Volume {
1127 self.volume
1128 }
1129
1130 #[must_use]
1132 pub const fn kind(&self) -> OrderType {
1133 match self.terms {
1134 Terms::Market => OrderType::Market,
1135 Terms::Limit(_) => OrderType::Limit,
1136 Terms::Stop(_) => OrderType::Stop,
1137 Terms::StopLimit { .. } => OrderType::StopLimit,
1138 }
1139 }
1140
1141 fn to_wire(&self, symbol: &Symbol) -> Result<ProtoOaNewOrderReq, ValueError> {
1142 if symbol.id != self.symbol {
1143 return Err(ValueError::Mismatch { kind: SYMBOL });
1144 }
1145 let market = matches!(self.terms, Terms::Market);
1146 if market && self.expiry.is_some() {
1147 return Err(ValueError::Unsupported { kind: EXPIRY });
1148 }
1149 let (kind, limit_price, stop_price, slippage) = match self.terms {
1150 Terms::Market => (ProtoOaOrderType::Market, None, None, None),
1151 Terms::Limit(price) => (
1152 ProtoOaOrderType::Limit,
1153 Some(checked_price(price, PRICE, symbol)?),
1154 None,
1155 None,
1156 ),
1157 Terms::Stop(price) => (
1158 ProtoOaOrderType::Stop,
1159 None,
1160 Some(checked_price(price, PRICE, symbol)?),
1161 None,
1162 ),
1163 Terms::StopLimit { stop, slippage } => (
1164 ProtoOaOrderType::StopLimit,
1165 None,
1166 Some(checked_price(stop, PRICE, symbol)?),
1167 Some(checked_slippage(slippage, Some(stop), symbol)?),
1168 ),
1169 };
1170 let time_in_force = match (market, self.expiry) {
1171 (true, _) => None,
1172 (false, Some(_)) => Some(ProtoOaTimeInForce::GoodTillDate),
1173 (false, None) => Some(ProtoOaTimeInForce::GoodTillCancel),
1174 };
1175 let price = |protection: Option<Protection>| {
1176 protection.map_or(Ok(None), |protection| protection.price(market, symbol))
1177 };
1178 let distance = |protection: Option<Protection>| {
1179 protection.map_or(Ok(None), |protection| protection.distance(symbol))
1180 };
1181 Ok(ProtoOaNewOrderReq {
1182 ctid_trader_account_id: self.account.get(),
1183 symbol_id: self.symbol.get(),
1184 order_type: i32::from(kind),
1185 trade_side: i32::from(self.side.to_wire()),
1186 volume: checked_volume(self.volume, symbol)?,
1187 limit_price,
1188 stop_price,
1189 slippage_in_points: slippage,
1190 time_in_force: time_in_force.map(i32::from),
1191 expiration_timestamp: self.expiry.map(Timestamp::as_millis),
1192 label: self.label.as_ref().map(|label| label.as_str().to_owned()),
1193 comment: self
1194 .comment
1195 .as_ref()
1196 .map(|comment| comment.as_str().to_owned()),
1197 stop_loss: price(self.stop_loss)?,
1198 take_profit: price(self.take_profit)?,
1199 relative_stop_loss: distance(self.stop_loss)?,
1200 relative_take_profit: distance(self.take_profit)?,
1201 ..ProtoOaNewOrderReq::default()
1202 })
1203 }
1204}
1205
1206#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1212#[must_use]
1213pub struct OrderAmendment {
1214 account: AccountId,
1215 order: OrderId,
1216 symbol: SymbolId,
1217 kind: OrderType,
1218 volume: Volume,
1219 price: Option<Price>,
1220 expiry: Option<Timestamp>,
1221 stop_loss: Option<Protection>,
1222 take_profit: Option<Protection>,
1223 slippage: Option<u32>,
1224}
1225
1226impl OrderAmendment {
1227 pub fn of(account: AccountId, order: &Order) -> Self {
1229 let protection = |price: Option<Price>, distance: Option<Price>| {
1230 price
1231 .map(Protection::At)
1232 .or_else(|| distance.map(Protection::Away))
1233 };
1234 Self {
1235 account,
1236 order: order.id,
1237 symbol: order.symbol,
1238 kind: order.kind,
1239 volume: order.volume,
1240 price: match order.kind {
1241 OrderType::Limit => order.limit_price,
1242 _ => order.stop_price,
1243 },
1244 expiry: match order.time_in_force {
1245 TimeInForce::GoodTillDate(expiry) => Some(expiry),
1246 _ => None,
1247 },
1248 stop_loss: protection(order.stop_loss, order.relative_stop_loss),
1249 take_profit: protection(order.take_profit, order.relative_take_profit),
1250 slippage: order.slippage_points,
1251 }
1252 }
1253
1254 pub const fn volume(mut self, volume: Volume) -> Self {
1256 self.volume = volume;
1257 self
1258 }
1259
1260 pub const fn price(mut self, price: Price) -> Self {
1263 self.price = Some(price);
1264 self
1265 }
1266
1267 pub const fn good_till(mut self, expiry: Timestamp) -> Self {
1269 self.expiry = Some(expiry);
1270 self
1271 }
1272
1273 pub const fn good_till_cancelled(mut self) -> Self {
1275 self.expiry = None;
1276 self
1277 }
1278
1279 pub fn stop_loss(mut self, price: Option<Price>) -> Self {
1281 self.stop_loss = price.map(Protection::At);
1282 self
1283 }
1284
1285 pub fn take_profit(mut self, price: Option<Price>) -> Self {
1287 self.take_profit = price.map(Protection::At);
1288 self
1289 }
1290
1291 pub const fn slippage(mut self, points: u32) -> Self {
1296 self.slippage = Some(points);
1297 self
1298 }
1299
1300 #[must_use]
1302 pub const fn order(&self) -> OrderId {
1303 self.order
1304 }
1305
1306 fn to_wire(&self, symbol: &Symbol) -> Result<ProtoOaAmendOrderReq, ValueError> {
1307 if symbol.id != self.symbol {
1308 return Err(ValueError::Mismatch { kind: SYMBOL });
1309 }
1310 let price = self
1311 .price
1312 .map(|price| checked_price(price, PRICE, symbol))
1313 .transpose()?;
1314 let (limit_price, stop_price, slippage) = match self.kind {
1315 OrderType::Limit => (price, None, None),
1316 OrderType::Stop => (None, price, None),
1317 OrderType::StopLimit => (None, price, self.slippage),
1318 _ => return Err(ValueError::Unsupported { kind: AMENDMENT }),
1319 };
1320 let at = |protection: Option<Protection>| {
1321 protection.map_or(Ok(None), |protection| protection.price(false, symbol))
1322 };
1323 let away = |protection: Option<Protection>| {
1324 protection.map_or(Ok(None), |protection| protection.distance(symbol))
1325 };
1326 Ok(ProtoOaAmendOrderReq {
1327 payload_type: None,
1328 ctid_trader_account_id: self.account.get(),
1329 order_id: self.order.get(),
1330 volume: Some(checked_volume(self.volume, symbol)?),
1331 limit_price,
1332 stop_price,
1333 expiration_timestamp: self.expiry.map(Timestamp::as_millis),
1334 stop_loss: at(self.stop_loss)?,
1335 take_profit: at(self.take_profit)?,
1336 slippage_in_points: slippage
1337 .map(|points| checked_slippage(points, self.price, symbol))
1338 .transpose()?,
1339 relative_stop_loss: away(self.stop_loss)?,
1340 relative_take_profit: away(self.take_profit)?,
1341 guaranteed_stop_loss: None,
1342 trailing_stop_loss: None,
1343 stop_trigger_method: None,
1344 })
1345 }
1346}
1347
1348#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1353#[must_use]
1354pub struct PositionAmendment {
1355 account: AccountId,
1356 position: PositionId,
1357 symbol: SymbolId,
1358 stop_loss: Option<Price>,
1359 take_profit: Option<Price>,
1360}
1361
1362impl PositionAmendment {
1363 pub const fn of(account: AccountId, position: &Position) -> Self {
1365 Self {
1366 account,
1367 position: position.id,
1368 symbol: position.symbol,
1369 stop_loss: position.stop_loss,
1370 take_profit: position.take_profit,
1371 }
1372 }
1373
1374 pub const fn stop_loss(mut self, price: Option<Price>) -> Self {
1376 self.stop_loss = price;
1377 self
1378 }
1379
1380 pub const fn take_profit(mut self, price: Option<Price>) -> Self {
1382 self.take_profit = price;
1383 self
1384 }
1385
1386 #[must_use]
1388 pub const fn position(&self) -> PositionId {
1389 self.position
1390 }
1391
1392 fn to_wire(self, symbol: &Symbol) -> Result<ProtoOaAmendPositionSltpReq, ValueError> {
1393 if symbol.id != self.symbol {
1394 return Err(ValueError::Mismatch { kind: SYMBOL });
1395 }
1396 let price = |price: Option<Price>| {
1397 price
1398 .map(|price| checked_price(price, PROTECTION, symbol))
1399 .transpose()
1400 };
1401 Ok(ProtoOaAmendPositionSltpReq {
1402 payload_type: None,
1403 ctid_trader_account_id: self.account.get(),
1404 position_id: self.position.get(),
1405 stop_loss: price(self.stop_loss)?,
1406 take_profit: price(self.take_profit)?,
1407 guaranteed_stop_loss: None,
1408 trailing_stop_loss: None,
1409 stop_loss_trigger_method: None,
1410 })
1411 }
1412}
1413
1414impl OpenApiClient {
1415 pub(crate) async fn trade<R: Payload>(&self, request: &R) -> Result<Execution, ConnectorError> {
1416 let message = self
1417 .connection()
1418 .request_once(R::PAYLOAD_TYPE, request.encode_to_vec())
1419 .await?;
1420 traded(&message)
1421 }
1422
1423 pub async fn place_order(
1450 &self,
1451 order: &NewOrder,
1452 symbol: &Symbol,
1453 ) -> Result<Execution, ConnectorError> {
1454 let request = order.to_wire(symbol)?;
1455 self.trade(&request).await
1456 }
1457
1458 pub async fn amend_order(
1472 &self,
1473 amendment: &OrderAmendment,
1474 symbol: &Symbol,
1475 ) -> Result<Execution, ConnectorError> {
1476 let request = amendment.to_wire(symbol)?;
1477 self.trade(&request).await
1478 }
1479
1480 pub async fn amend_position(
1495 &self,
1496 amendment: &PositionAmendment,
1497 symbol: &Symbol,
1498 ) -> Result<Execution, ConnectorError> {
1499 let request = amendment.to_wire(symbol)?;
1500 self.trade(&request).await
1501 }
1502
1503 pub async fn cancel_order(
1519 &self,
1520 account: AccountId,
1521 order: OrderId,
1522 ) -> Result<Execution, ConnectorError> {
1523 self.trade(&ProtoOaCancelOrderReq {
1524 payload_type: None,
1525 ctid_trader_account_id: account.get(),
1526 order_id: order.get(),
1527 })
1528 .await
1529 }
1530
1531 pub async fn reconcile(&self, account: AccountId) -> Result<Reconciliation, ConnectorError> {
1543 let answer = self
1544 .connection()
1545 .request(&ProtoOaReconcileReq {
1546 payload_type: None,
1547 ctid_trader_account_id: account.get(),
1548 return_protection_orders: Some(true),
1549 })
1550 .await?;
1551 Ok(Reconciliation::try_from(answer)?)
1552 }
1553
1554 pub async fn close_position(
1574 &self,
1575 account: AccountId,
1576 position: &Position,
1577 volume: Volume,
1578 symbol: &Symbol,
1579 ) -> Result<Execution, ConnectorError> {
1580 let request = ProtoOaClosePositionReq {
1581 payload_type: None,
1582 ctid_trader_account_id: account.get(),
1583 position_id: position.id.get(),
1584 volume: closing_volume(volume, position, symbol)?,
1585 };
1586 self.trade(&request).await
1587 }
1588}
1589
1590#[cfg(test)]
1591mod tests {
1592 use rust_decimal::Decimal;
1593
1594 use super::{
1595 ClosingDetail, Comment, Deal, DealStatus, Execution, ExecutionType, Label,
1596 MAX_COMMENT_LENGTH, MAX_LABEL_LENGTH, Order, OrderStatus, OrderType, Position,
1597 PositionStatus, TimeInForce, TradeSide, double_price, money, relative_price, traded,
1598 };
1599 use crate::common::errors::{ConnectorError, ErrorCode, ValueError};
1600 use crate::common::time::Timestamp;
1601 use crate::open_api::messages::{
1602 ProtoOaClosePositionDetail, ProtoOaDeal, ProtoOaExecutionEvent, ProtoOaOrder,
1603 ProtoOaOrderErrorEvent, ProtoOaPosition, ProtoOaTradeData,
1604 };
1605 use crate::open_api::payload::Payload;
1606
1607 fn out_of_range(kind: &'static str) -> ValueError {
1608 ValueError::OutOfRange { kind }
1609 }
1610
1611 fn data() -> ProtoOaTradeData {
1612 ProtoOaTradeData {
1613 symbol_id: 7,
1614 volume: 250,
1615 trade_side: 2,
1616 open_timestamp: Some(1_700_000_000_000),
1617 label: Some("run".to_owned()),
1618 comment: Some("note".to_owned()),
1619 ..ProtoOaTradeData::default()
1620 }
1621 }
1622
1623 fn order() -> ProtoOaOrder {
1624 ProtoOaOrder {
1625 order_id: 9,
1626 trade_data: data(),
1627 order_type: 6,
1628 order_status: 1,
1629 expiration_timestamp: Some(1_800_000_000_000),
1630 execution_price: Some(101.5),
1631 executed_volume: Some(100),
1632 utc_last_update_timestamp: Some(1_700_000_000_500),
1633 slippage_in_points: Some(30),
1634 closing_order: Some(true),
1635 limit_price: Some(100.123_45),
1636 stop_price: Some(99.5),
1637 stop_loss: Some(90.0),
1638 take_profit: Some(120.25),
1639 client_order_id: Some("mine".to_owned()),
1640 time_in_force: Some(1),
1641 position_id: Some(0),
1642 relative_stop_loss: Some(150_000),
1643 relative_take_profit: Some(300_000),
1644 trailing_stop_loss: Some(true),
1645 ..ProtoOaOrder::default()
1646 }
1647 }
1648
1649 fn position() -> ProtoOaPosition {
1650 ProtoOaPosition {
1651 position_id: 5,
1652 trade_data: data(),
1653 position_status: 1,
1654 swap: -1_234,
1655 price: Some(100.5),
1656 stop_loss: Some(90.0),
1657 take_profit: Some(120.0),
1658 utc_last_update_timestamp: Some(1_700_000_000_900),
1659 commission: Some(-7),
1660 guaranteed_stop_loss: Some(true),
1661 used_margin: Some(2_500),
1662 money_digits: Some(3),
1663 trailing_stop_loss: Some(true),
1664 ..ProtoOaPosition::default()
1665 }
1666 }
1667
1668 fn deal() -> ProtoOaDeal {
1669 ProtoOaDeal {
1670 deal_id: 3,
1671 order_id: 9,
1672 position_id: 5,
1673 volume: 250,
1674 filled_volume: 100,
1675 symbol_id: 7,
1676 create_timestamp: 1_700_000_000_000,
1677 execution_timestamp: 1_700_000_000_010,
1678 execution_price: Some(101.5),
1679 trade_side: 1,
1680 deal_status: 3,
1681 commission: Some(-12),
1682 close_position_detail: Some(ProtoOaClosePositionDetail {
1683 entry_price: 100.5,
1684 gross_profit: 1_000,
1685 swap: -10,
1686 commission: -24,
1687 balance: 1_000_966,
1688 closed_volume: Some(100),
1689 money_digits: None,
1690 ..ProtoOaClosePositionDetail::default()
1691 }),
1692 money_digits: Some(2),
1693 ..ProtoOaDeal::default()
1694 }
1695 }
1696
1697 fn decimal(text: &str) -> Decimal {
1698 text.parse().expect("decimal")
1699 }
1700
1701 #[test]
1702 fn texts_are_limited_in_characters() {
1703 let label = Label::new("é".repeat(MAX_LABEL_LENGTH)).expect("label");
1704 assert_eq!(label.as_str().chars().count(), MAX_LABEL_LENGTH);
1705 assert_eq!(Label::new("run-7").expect("label").to_string(), "run-7");
1706 assert_eq!(
1707 Label::new("x".repeat(MAX_LABEL_LENGTH + 1)),
1708 Err(ValueError::TooLong {
1709 kind: "label",
1710 length: 101,
1711 limit: 100,
1712 })
1713 );
1714 assert_eq!(
1715 Comment::new("y".repeat(MAX_COMMENT_LENGTH))
1716 .expect("comment")
1717 .as_str()
1718 .len(),
1719 MAX_COMMENT_LENGTH
1720 );
1721 assert_eq!(Comment::new("note").expect("comment").to_string(), "note");
1722 assert_eq!(
1723 Comment::new("y".repeat(MAX_COMMENT_LENGTH + 1)),
1724 Err(ValueError::TooLong {
1725 kind: "comment",
1726 length: 513,
1727 limit: 512,
1728 })
1729 );
1730 }
1731
1732 #[test]
1733 fn rejections_of_an_order_read_as_sentences() {
1734 let one = Decimal::ONE;
1735 let cases = [
1736 (
1737 ValueError::TooLong {
1738 kind: "label",
1739 length: 101,
1740 limit: 100,
1741 },
1742 "label has 101 characters, more than the 100 allowed",
1743 ),
1744 (
1745 ValueError::BelowMinimum {
1746 kind: "volume",
1747 value: Decimal::ZERO,
1748 minimum: one,
1749 },
1750 "volume must be at least 1, got 0",
1751 ),
1752 (
1753 ValueError::AboveMaximum {
1754 kind: "volume",
1755 value: Decimal::TEN,
1756 maximum: one,
1757 },
1758 "volume must be at most 1, got 10",
1759 ),
1760 (
1761 ValueError::OffStep {
1762 kind: "volume",
1763 value: decimal("1.5"),
1764 step: one,
1765 },
1766 "volume must be a multiple of 1, got 1.5",
1767 ),
1768 (
1769 ValueError::TooFine {
1770 kind: "price",
1771 value: decimal("1.005"),
1772 digits: 2,
1773 },
1774 "price must have at most 2 decimal places, got 1.005",
1775 ),
1776 (
1777 ValueError::Mismatch {
1778 kind: "symbol of the order",
1779 },
1780 "symbol of the order does not match",
1781 ),
1782 (
1783 ValueError::Unsupported {
1784 kind: "expiry of the order",
1785 },
1786 "expiry of the order is not supported here",
1787 ),
1788 ];
1789 for (error, text) in cases {
1790 assert_eq!(error.to_string(), text);
1791 }
1792 }
1793
1794 #[test]
1795 fn enumerations_follow_the_wire_numbers() {
1796 assert_eq!(TradeSide::from_wire(1), Ok(TradeSide::Buy));
1797 assert_eq!(TradeSide::from_wire(2), Ok(TradeSide::Sell));
1798 assert_eq!(TradeSide::from_wire(3), Err(out_of_range("trade side")));
1799 assert_eq!(TradeSide::Buy.opposite(), TradeSide::Sell);
1800 assert_eq!(TradeSide::Sell.opposite(), TradeSide::Buy);
1801 assert_eq!(TradeSide::Buy.to_wire() as i32, 1);
1802 assert_eq!(TradeSide::Sell.to_wire() as i32, 2);
1803 let kinds = [
1804 OrderType::Market,
1805 OrderType::Limit,
1806 OrderType::Stop,
1807 OrderType::StopLossTakeProfit,
1808 OrderType::MarketRange,
1809 OrderType::StopLimit,
1810 ];
1811 for (raw, kind) in (1..).zip(kinds) {
1812 assert_eq!(OrderType::from_wire(raw), Ok(kind));
1813 }
1814 assert_eq!(OrderType::from_wire(0), Err(out_of_range("order type")));
1815 let statuses = [
1816 OrderStatus::Accepted,
1817 OrderStatus::Filled,
1818 OrderStatus::Rejected,
1819 OrderStatus::Expired,
1820 OrderStatus::Cancelled,
1821 ];
1822 for (raw, status) in (1..).zip(statuses) {
1823 assert_eq!(OrderStatus::from_wire(raw), Ok(status));
1824 }
1825 assert_eq!(OrderStatus::from_wire(6), Err(out_of_range("order status")));
1826 let positions = [
1827 PositionStatus::Open,
1828 PositionStatus::Closed,
1829 PositionStatus::Created,
1830 PositionStatus::Error,
1831 ];
1832 for (raw, status) in (1..).zip(positions) {
1833 assert_eq!(PositionStatus::from_wire(raw), Ok(status));
1834 }
1835 assert_eq!(
1836 PositionStatus::from_wire(5),
1837 Err(out_of_range("position status"))
1838 );
1839 let deals = [
1840 DealStatus::Filled,
1841 DealStatus::PartiallyFilled,
1842 DealStatus::Rejected,
1843 DealStatus::InternallyRejected,
1844 DealStatus::Error,
1845 DealStatus::Missed,
1846 ];
1847 for (raw, status) in (2..).zip(deals) {
1848 assert_eq!(DealStatus::from_wire(raw), Ok(status));
1849 }
1850 assert_eq!(DealStatus::from_wire(1), Err(out_of_range("deal status")));
1851 let executions = [
1852 ExecutionType::Accepted,
1853 ExecutionType::Filled,
1854 ExecutionType::Replaced,
1855 ExecutionType::Cancelled,
1856 ExecutionType::Expired,
1857 ExecutionType::Rejected,
1858 ExecutionType::CancelRejected,
1859 ExecutionType::Swap,
1860 ExecutionType::DepositWithdraw,
1861 ExecutionType::PartiallyFilled,
1862 ExecutionType::BonusDepositWithdraw,
1863 ];
1864 for (raw, kind) in (2..).zip(executions) {
1865 assert_eq!(ExecutionType::from_wire(raw), Ok(kind));
1866 }
1867 assert_eq!(
1868 ExecutionType::from_wire(13),
1869 Err(out_of_range("execution type"))
1870 );
1871 }
1872
1873 #[test]
1874 fn time_in_force_takes_its_moment_from_the_expiry() {
1875 let expiry = Timestamp::from_millis(1_800_000_000_000).expect("timestamp");
1876 assert_eq!(
1877 TimeInForce::from_wire(Some(1), Some(1_800_000_000_000)),
1878 Ok(TimeInForce::GoodTillDate(expiry))
1879 );
1880 assert_eq!(
1881 TimeInForce::from_wire(Some(1), None),
1882 Err(ValueError::Missing {
1883 kind: "expiry of the order"
1884 })
1885 );
1886 assert_eq!(
1887 TimeInForce::from_wire(Some(1), Some(-1)),
1888 Err(out_of_range("timestamp"))
1889 );
1890 assert_eq!(
1891 TimeInForce::from_wire(Some(2), Some(5)),
1892 Ok(TimeInForce::GoodTillCancel)
1893 );
1894 assert_eq!(
1895 TimeInForce::from_wire(Some(3), None),
1896 Ok(TimeInForce::ImmediateOrCancel)
1897 );
1898 assert_eq!(
1899 TimeInForce::from_wire(None, None),
1900 Ok(TimeInForce::ImmediateOrCancel)
1901 );
1902 assert_eq!(
1903 TimeInForce::from_wire(Some(4), None),
1904 Ok(TimeInForce::FillOrKill)
1905 );
1906 assert_eq!(
1907 TimeInForce::from_wire(Some(5), None),
1908 Ok(TimeInForce::MarketOnOpen)
1909 );
1910 assert_eq!(
1911 TimeInForce::from_wire(Some(6), None),
1912 Err(out_of_range("time in force"))
1913 );
1914 }
1915
1916 #[test]
1917 fn doubles_and_scaled_integers_become_exact_decimals() {
1918 assert_eq!(
1919 double_price(64_000.25).map(|price| price.to_string()),
1920 Ok("64000.25".to_owned())
1921 );
1922 assert_eq!(
1923 double_price(1.234_564_9).map(|price| price.to_string()),
1924 Ok("1.23456".to_owned())
1925 );
1926 assert_eq!(double_price(f64::NAN), Err(out_of_range("price")));
1927 assert_eq!(double_price(f64::INFINITY), Err(out_of_range("price")));
1928 assert!(matches!(
1929 double_price(-1.0),
1930 Err(ValueError::Negative { .. })
1931 ));
1932 assert_eq!(money(-12_345, Some(3)), Ok(decimal("-12.345")));
1933 assert_eq!(money(12_345, None), Ok(decimal("123.45")));
1934 assert_eq!(money(1, Some(40)), Err(out_of_range("amount of money")));
1935 assert_eq!(
1936 relative_price(Some(150_000)).map(|price| price.map(|price| price.to_string())),
1937 Ok(Some("1.50000".to_owned()))
1938 );
1939 assert_eq!(relative_price(None), Ok(None));
1940 assert_eq!(
1941 relative_price(Some(-1)),
1942 Err(out_of_range("distance of the protection"))
1943 );
1944 }
1945
1946 #[test]
1947 fn order_keeps_every_field_of_the_wire() {
1948 let order = Order::try_from(order()).expect("order");
1949 assert_eq!(order.id.get(), 9);
1950 assert_eq!(order.symbol.get(), 7);
1951 assert_eq!(order.side, TradeSide::Sell);
1952 assert_eq!(order.volume.to_string(), "2.50");
1953 assert_eq!(order.kind, OrderType::StopLimit);
1954 assert_eq!(order.status, OrderStatus::Accepted);
1955 assert_eq!(
1956 order.time_in_force,
1957 TimeInForce::GoodTillDate(Timestamp::from_millis(1_800_000_000_000).expect("moment"))
1958 );
1959 let text = |price: Option<crate::common::decimals::Price>| {
1960 price.map(|price| price.value().normalize().to_string())
1961 };
1962 assert_eq!(text(order.limit_price), Some("100.12345".to_owned()));
1963 assert_eq!(text(order.stop_price), Some("99.5".to_owned()));
1964 assert_eq!(text(order.stop_loss), Some("90".to_owned()));
1965 assert_eq!(text(order.take_profit), Some("120.25".to_owned()));
1966 assert_eq!(text(order.relative_stop_loss), Some("1.5".to_owned()));
1967 assert_eq!(text(order.relative_take_profit), Some("3".to_owned()));
1968 assert_eq!(text(order.execution_price), Some("101.5".to_owned()));
1969 assert_eq!(order.slippage_points, Some(30));
1970 assert_eq!(
1971 order.executed_volume.map(|volume| volume.to_string()),
1972 Some("1.00".to_owned())
1973 );
1974 assert_eq!(order.position, None);
1975 assert_eq!(order.label.as_deref(), Some("run"));
1976 assert_eq!(order.comment.as_deref(), Some("note"));
1977 assert_eq!(order.client_order_id.as_deref(), Some("mine"));
1978 assert!(order.closing);
1979 assert!(order.trailing_stop_loss);
1980 assert_eq!(
1981 order.opened.map(Timestamp::as_millis),
1982 Some(1_700_000_000_000)
1983 );
1984 assert_eq!(
1985 order.updated.map(Timestamp::as_millis),
1986 Some(1_700_000_000_500)
1987 );
1988 }
1989
1990 #[test]
1991 fn order_with_a_value_out_of_range_is_refused() {
1992 let broken = |change: fn(&mut ProtoOaOrder)| {
1993 let mut order = order();
1994 change(&mut order);
1995 Order::try_from(order).err()
1996 };
1997 assert!(matches!(
1998 broken(|order| order.order_id = 0),
1999 Some(ValueError::InvalidId { .. })
2000 ));
2001 assert!(matches!(
2002 broken(|order| order.trade_data.symbol_id = 0),
2003 Some(ValueError::InvalidId { .. })
2004 ));
2005 assert_eq!(
2006 broken(|order| order.trade_data.trade_side = 0),
2007 Some(out_of_range("trade side"))
2008 );
2009 assert!(broken(|order| order.trade_data.volume = -1).is_some());
2010 assert_eq!(
2011 broken(|order| order.order_type = 0),
2012 Some(out_of_range("order type"))
2013 );
2014 assert_eq!(
2015 broken(|order| order.order_status = 0),
2016 Some(out_of_range("order status"))
2017 );
2018 assert_eq!(
2019 broken(|order| order.time_in_force = Some(0)),
2020 Some(out_of_range("time in force"))
2021 );
2022 assert_eq!(
2023 broken(|order| order.limit_price = Some(f64::NAN)),
2024 Some(out_of_range("price"))
2025 );
2026 assert_eq!(
2027 broken(|order| order.slippage_in_points = Some(-1)),
2028 Some(out_of_range("slippage in points"))
2029 );
2030 assert!(matches!(
2031 broken(|order| order.position_id = Some(-4)),
2032 Some(ValueError::InvalidId { .. })
2033 ));
2034 assert_eq!(
2035 broken(|order| order.utc_last_update_timestamp = Some(-1)),
2036 Some(out_of_range("timestamp"))
2037 );
2038 }
2039
2040 #[test]
2041 fn position_scales_its_money_by_its_own_digits() {
2042 let position = Position::try_from(position()).expect("position");
2043 assert_eq!(position.id.get(), 5);
2044 assert_eq!(position.symbol.get(), 7);
2045 assert_eq!(position.side, TradeSide::Sell);
2046 assert_eq!(position.volume.to_string(), "2.50");
2047 assert_eq!(position.status, PositionStatus::Open);
2048 assert_eq!(
2049 position.price.map(|price| price.value().normalize()),
2050 Some(decimal("100.5"))
2051 );
2052 assert_eq!(
2053 position.stop_loss.map(|price| price.value().normalize()),
2054 Some(decimal("90"))
2055 );
2056 assert_eq!(
2057 position.take_profit.map(|price| price.value().normalize()),
2058 Some(decimal("120"))
2059 );
2060 assert_eq!(position.swap, decimal("-1.234"));
2061 assert_eq!(position.commission, Some(decimal("-0.007")));
2062 assert_eq!(position.used_margin, Some(decimal("2.500")));
2063 assert_eq!(position.label.as_deref(), Some("run"));
2064 assert_eq!(position.comment.as_deref(), Some("note"));
2065 assert!(position.guaranteed_stop_loss);
2066 assert!(position.trailing_stop_loss);
2067 assert_eq!(
2068 position.opened.map(Timestamp::as_millis),
2069 Some(1_700_000_000_000)
2070 );
2071 assert_eq!(
2072 position.updated.map(Timestamp::as_millis),
2073 Some(1_700_000_000_900)
2074 );
2075 let mut huge = self::position();
2076 huge.used_margin = Some(u64::MAX);
2077 assert_eq!(
2078 Position::try_from(huge),
2079 Err(out_of_range("amount of money"))
2080 );
2081 let mut unknown = self::position();
2082 unknown.position_status = 9;
2083 assert_eq!(
2084 Position::try_from(unknown),
2085 Err(out_of_range("position status"))
2086 );
2087 }
2088
2089 #[test]
2090 fn deal_carries_what_closing_did_to_the_account() {
2091 let deal = Deal::try_from(deal()).expect("deal");
2092 assert_eq!(deal.id.get(), 3);
2093 assert_eq!(deal.order.get(), 9);
2094 assert_eq!(deal.position.get(), 5);
2095 assert_eq!(deal.symbol.get(), 7);
2096 assert_eq!(deal.side, TradeSide::Buy);
2097 assert_eq!(deal.volume.to_string(), "2.50");
2098 assert_eq!(deal.filled_volume.to_string(), "1.00");
2099 assert_eq!(deal.status, DealStatus::PartiallyFilled);
2100 assert_eq!(deal.created.as_millis(), 1_700_000_000_000);
2101 assert_eq!(deal.executed.as_millis(), 1_700_000_000_010);
2102 assert_eq!(
2103 deal.execution_price.map(|price| price.value().normalize()),
2104 Some(decimal("101.5"))
2105 );
2106 assert_eq!(deal.commission, Some(decimal("-0.12")));
2107 let closing: ClosingDetail = deal.closing.expect("closing detail");
2108 assert_eq!(closing.entry_price.value().normalize(), decimal("100.5"));
2109 assert_eq!(closing.gross_profit, decimal("10.00"));
2110 assert_eq!(closing.swap, decimal("-0.10"));
2111 assert_eq!(closing.commission, decimal("-0.24"));
2112 assert_eq!(closing.balance, decimal("10009.66"));
2113 assert_eq!(
2114 closing.closed_volume.map(|volume| volume.to_string()),
2115 Some("1.00".to_owned())
2116 );
2117 let mut unknown = self::deal();
2118 unknown.deal_status = 1;
2119 assert_eq!(Deal::try_from(unknown), Err(out_of_range("deal status")));
2120 }
2121
2122 #[test]
2123 fn first_answer_to_a_trade_is_an_execution_or_a_typed_refusal() {
2124 let event = ProtoOaExecutionEvent {
2125 ctid_trader_account_id: 101,
2126 execution_type: 2,
2127 order: Some(order()),
2128 position: Some(position()),
2129 deal: Some(deal()),
2130 is_server_event: Some(true),
2131 ..ProtoOaExecutionEvent::default()
2132 };
2133 let execution = traded(&event.to_message(None)).expect("execution");
2134 assert_eq!(execution.kind, ExecutionType::Accepted);
2135 assert!(execution.server_event);
2136 assert!(execution.order.is_some() && execution.position.is_some());
2137 assert!(execution.deal.is_some());
2138 assert_eq!(
2139 Execution::try_from(ProtoOaExecutionEvent {
2140 ctid_trader_account_id: 0,
2141 ..event.clone()
2142 })
2143 .err()
2144 .map(|error| error.to_string()),
2145 Some("account id must be a positive integer, got 0".to_owned())
2146 );
2147 let rejected = ProtoOaExecutionEvent {
2148 execution_type: 7,
2149 error_code: Some("MARKET_CLOSED".to_owned()),
2150 ..event
2151 };
2152 match traded(&rejected.to_message(None)) {
2153 Err(ConnectorError::Server(error)) => {
2154 assert_eq!(error.code, ErrorCode::MarketClosed);
2155 assert_eq!(error.description.as_deref(), Some("the order was refused"));
2156 assert_eq!(
2157 error.account_id.map(crate::common::ids::AccountId::get),
2158 Some(101)
2159 );
2160 }
2161 other => panic!("unexpected outcome: {other:?}"),
2162 }
2163 let error = ProtoOaOrderErrorEvent {
2164 payload_type: None,
2165 ctid_trader_account_id: 101,
2166 error_code: "ORDER_NOT_FOUND".to_owned(),
2167 order_id: Some(9),
2168 position_id: None,
2169 description: Some("no such order".to_owned()),
2170 };
2171 match traded(&error.to_message(None)) {
2172 Err(ConnectorError::Server(error)) => {
2173 assert_eq!(error.code, ErrorCode::OrderNotFound);
2174 assert_eq!(error.description.as_deref(), Some("no such order"));
2175 }
2176 other => panic!("unexpected outcome: {other:?}"),
2177 }
2178 }
2179}