1use crate::presentation::account::{
7 Account, AccountTransaction, Activity, ActivityMetadata, Position, TransactionMetadata,
8 WorkingOrder,
9};
10use crate::presentation::instrument::InstrumentType;
11use crate::presentation::market::{
12 Category, CategoryInstrument, CategoryInstrumentsMetadata, HistoricalPrice, MarketData,
13 MarketDetails, MarketNavigationNode, MarketNode, PriceAllowance,
14};
15use crate::presentation::order::{Direction, Status};
16use crate::utils::parsing::{deserialize_null_as_empty_vec, deserialize_nullable_status};
17use chrono::{DateTime, Utc};
18use pretty_simple_display::{DebugPretty, DisplaySimple};
19use serde::{Deserialize, Serialize};
20use std::collections::HashMap;
21
22#[derive(
24 DebugPretty, DisplaySimple, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Default,
25)]
26pub struct DBEntryResponse {
27 pub symbol: String,
29 pub epic: String,
31 pub name: String,
33 pub instrument_type: InstrumentType,
35 pub exchange: String,
37 pub expiry: String,
39 pub last_update: DateTime<Utc>,
41}
42
43impl From<MarketNode> for DBEntryResponse {
44 fn from(value: MarketNode) -> Self {
45 let mut entry = DBEntryResponse::default();
46 if !value.markets.is_empty() {
47 let market = &value.markets[0];
48 entry.symbol = market
49 .epic
50 .split('.')
51 .nth(2)
52 .unwrap_or_default()
53 .to_string();
54 entry.epic = market.epic.clone();
55 entry.name = market.instrument_name.clone();
56 entry.instrument_type = market.instrument_type;
57 entry.exchange = "IG".to_string();
58 entry.expiry = market.expiry.clone();
59 entry.last_update = Utc::now();
60 }
61 entry
62 }
63}
64
65impl From<MarketData> for DBEntryResponse {
66 fn from(market: MarketData) -> Self {
67 DBEntryResponse {
68 symbol: market
69 .epic
70 .split('.')
71 .nth(2)
72 .unwrap_or_default()
73 .to_string(),
74 epic: market.epic.clone(),
75 name: market.instrument_name.clone(),
76 instrument_type: market.instrument_type,
77 exchange: "IG".to_string(),
78 expiry: market.expiry.clone(),
79 last_update: Utc::now(),
80 }
81 }
82}
83
84impl From<&MarketNode> for DBEntryResponse {
85 fn from(value: &MarketNode) -> Self {
86 DBEntryResponse::from(value.clone())
87 }
88}
89
90impl From<&MarketData> for DBEntryResponse {
91 fn from(market: &MarketData) -> Self {
92 DBEntryResponse::from(market.clone())
93 }
94}
95
96#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
98pub struct MultipleMarketDetailsResponse {
99 #[serde(rename = "marketDetails")]
101 pub market_details: Vec<MarketDetails>,
102}
103
104impl MultipleMarketDetailsResponse {
105 #[must_use]
110 pub fn len(&self) -> usize {
111 self.market_details.len()
112 }
113
114 #[must_use]
119 pub fn is_empty(&self) -> bool {
120 self.market_details.is_empty()
121 }
122
123 #[must_use]
128 pub fn market_details(&self) -> &Vec<MarketDetails> {
129 &self.market_details
130 }
131
132 pub fn iter(&self) -> impl Iterator<Item = &MarketDetails> {
137 self.market_details.iter()
138 }
139}
140
141#[derive(DebugPretty, Clone, Serialize, Deserialize)]
143pub struct HistoricalPricesResponse {
144 pub prices: Vec<HistoricalPrice>,
146 #[serde(rename = "instrumentType")]
148 pub instrument_type: InstrumentType,
149 #[serde(rename = "allowance", skip_serializing_if = "Option::is_none", default)]
151 pub allowance: Option<PriceAllowance>,
152}
153
154impl HistoricalPricesResponse {
155 #[must_use]
160 pub fn len(&self) -> usize {
161 self.prices.len()
162 }
163
164 #[must_use]
169 pub fn is_empty(&self) -> bool {
170 self.prices.is_empty()
171 }
172
173 #[must_use]
178 pub fn prices(&self) -> &Vec<HistoricalPrice> {
179 &self.prices
180 }
181
182 pub fn iter(&self) -> impl Iterator<Item = &HistoricalPrice> {
187 self.prices.iter()
188 }
189}
190
191#[derive(DebugPretty, Clone, Serialize, Deserialize)]
193pub struct MarketSearchResponse {
194 pub markets: Vec<MarketData>,
196}
197
198impl MarketSearchResponse {
199 #[must_use]
204 pub fn len(&self) -> usize {
205 self.markets.len()
206 }
207
208 #[must_use]
213 pub fn is_empty(&self) -> bool {
214 self.markets.is_empty()
215 }
216
217 #[must_use]
222 pub fn markets(&self) -> &Vec<MarketData> {
223 &self.markets
224 }
225
226 pub fn iter(&self) -> impl Iterator<Item = &MarketData> {
231 self.markets.iter()
232 }
233}
234
235#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
237pub struct MarketNavigationResponse {
238 #[serde(default, deserialize_with = "deserialize_null_as_empty_vec")]
240 pub nodes: Vec<MarketNavigationNode>,
241 #[serde(default, deserialize_with = "deserialize_null_as_empty_vec")]
243 pub markets: Vec<MarketData>,
244}
245
246#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize, Default)]
248pub struct CategoriesResponse {
249 pub categories: Vec<Category>,
251}
252
253impl CategoriesResponse {
254 #[must_use]
259 pub fn len(&self) -> usize {
260 self.categories.len()
261 }
262
263 #[must_use]
268 pub fn is_empty(&self) -> bool {
269 self.categories.is_empty()
270 }
271
272 #[must_use]
277 pub fn categories(&self) -> &Vec<Category> {
278 &self.categories
279 }
280
281 pub fn iter(&self) -> impl Iterator<Item = &Category> {
286 self.categories.iter()
287 }
288}
289
290#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize, Default)]
292pub struct CategoryInstrumentsResponse {
293 pub instruments: Vec<CategoryInstrument>,
295 pub metadata: Option<CategoryInstrumentsMetadata>,
297}
298
299impl CategoryInstrumentsResponse {
300 #[must_use]
305 pub fn len(&self) -> usize {
306 self.instruments.len()
307 }
308
309 #[must_use]
314 pub fn is_empty(&self) -> bool {
315 self.instruments.is_empty()
316 }
317
318 #[must_use]
323 pub fn instruments(&self) -> &Vec<CategoryInstrument> {
324 &self.instruments
325 }
326
327 pub fn iter(&self) -> impl Iterator<Item = &CategoryInstrument> {
332 self.instruments.iter()
333 }
334}
335
336#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize, Default)]
338pub struct AccountsResponse {
339 pub accounts: Vec<Account>,
341}
342
343#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize, Default)]
345pub struct PositionsResponse {
346 pub positions: Vec<Position>,
348}
349
350impl PositionsResponse {
351 #[must_use]
362 pub fn compact_by_epic(positions: Vec<Position>) -> Vec<Position> {
363 let mut epic_map: HashMap<String, Position> = std::collections::HashMap::new();
364
365 for position in positions {
366 let epic = position.market.epic.clone();
367 epic_map
368 .entry(epic)
369 .and_modify(|existing| {
370 *existing = existing.clone() + position.clone();
371 })
372 .or_insert(position);
373 }
374
375 epic_map.into_values().collect()
376 }
377}
378
379#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
381pub struct WorkingOrdersResponse {
382 #[serde(rename = "workingOrders")]
384 pub working_orders: Vec<WorkingOrder>,
385}
386
387#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
389pub struct AccountActivityResponse {
390 pub activities: Vec<Activity>,
392 pub metadata: Option<ActivityMetadata>,
394}
395
396#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
398pub struct TransactionHistoryResponse {
399 pub transactions: Vec<AccountTransaction>,
401 pub metadata: TransactionMetadata,
403}
404
405#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
407pub struct CreateOrderResponse {
408 #[serde(rename = "dealReference")]
410 pub deal_reference: String,
411}
412
413#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
415pub struct ClosePositionResponse {
416 #[serde(rename = "dealReference")]
418 pub deal_reference: String,
419}
420
421#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
423pub struct UpdatePositionResponse {
424 #[serde(rename = "dealReference")]
426 pub deal_reference: String,
427}
428
429#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
431pub struct CreateWorkingOrderResponse {
432 #[serde(rename = "dealReference")]
434 pub deal_reference: String,
435}
436
437#[repr(u8)]
444#[derive(Debug, Clone, Copy, DisplaySimple, Serialize, Deserialize, PartialEq, Eq, Hash)]
445#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
446pub enum DealStatus {
447 Accepted,
449 Rejected,
451}
452
453#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
458pub struct AffectedDeal {
459 #[serde(rename = "dealId")]
461 pub deal_id: String,
462 #[serde(rename = "status")]
467 pub status: String,
468}
469
470#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
472pub struct OrderConfirmationResponse {
473 pub date: String,
475 #[serde(deserialize_with = "deserialize_nullable_status")]
478 pub status: Status,
479 pub reason: Option<String>,
481 #[serde(rename = "dealId")]
483 pub deal_id: Option<String>,
484 #[serde(rename = "dealReference")]
486 pub deal_reference: String,
487 #[serde(rename = "dealStatus")]
489 #[serde(default)]
490 pub deal_status: Option<DealStatus>,
491 pub epic: Option<String>,
493 #[serde(rename = "expiry")]
495 pub expiry: Option<String>,
496 #[serde(rename = "guaranteedStop")]
498 pub guaranteed_stop: Option<bool>,
499 #[serde(rename = "level")]
501 pub level: Option<f64>,
502 #[serde(rename = "limitDistance")]
504 pub limit_distance: Option<f64>,
505 #[serde(rename = "limitLevel")]
507 pub limit_level: Option<f64>,
508 pub size: Option<f64>,
510 #[serde(rename = "stopDistance")]
512 pub stop_distance: Option<f64>,
513 #[serde(rename = "stopLevel")]
515 pub stop_level: Option<f64>,
516 #[serde(rename = "trailingStop")]
518 pub trailing_stop: Option<bool>,
519 pub direction: Option<Direction>,
521 #[serde(rename = "affectedDeals")]
523 #[serde(default)]
524 pub affected_deals: Vec<AffectedDeal>,
525 #[serde(rename = "profit")]
527 #[serde(default)]
528 pub profit: Option<f64>,
529 #[serde(rename = "profitCurrency")]
531 #[serde(default)]
532 pub profit_currency: Option<String>,
533}
534
535impl std::fmt::Display for MultipleMarketDetailsResponse {
536 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537 use prettytable::format;
538 use prettytable::{Cell, Row, Table};
539
540 let mut table = Table::new();
541
542 table.set_format(*format::consts::FORMAT_BOX_CHARS);
544
545 table.add_row(Row::new(vec![
547 Cell::new("INSTRUMENT NAME"),
548 Cell::new("EPIC"),
549 Cell::new("BID"),
550 Cell::new("OFFER"),
551 Cell::new("MID"),
552 Cell::new("SPREAD"),
553 Cell::new("EXPIRY"),
554 Cell::new("HIGH/LOW"),
555 ]));
556
557 let mut sorted_details = self.market_details.clone();
559 sorted_details.sort_by(|a, b| {
560 a.instrument
561 .name
562 .to_lowercase()
563 .cmp(&b.instrument.name.to_lowercase())
564 });
565
566 for details in &sorted_details {
568 let bid = details
569 .snapshot
570 .bid
571 .map(|b| format!("{:.2}", b))
572 .unwrap_or_else(|| "-".to_string());
573
574 let offer = details
575 .snapshot
576 .offer
577 .map(|o| format!("{:.2}", o))
578 .unwrap_or_else(|| "-".to_string());
579
580 let mid = match (details.snapshot.bid, details.snapshot.offer) {
581 (Some(b), Some(o)) => format!("{:.2}", (b + o) / 2.0),
582 _ => "-".to_string(),
583 };
584
585 let spread = match (details.snapshot.bid, details.snapshot.offer) {
586 (Some(b), Some(o)) => format!("{:.2}", o - b),
587 _ => "-".to_string(),
588 };
589
590 let expiry = details
592 .instrument
593 .expiry_details
594 .as_ref()
595 .map(|ed| {
596 ed.last_dealing_date
598 .split('T')
599 .next()
600 .unwrap_or(&ed.last_dealing_date)
601 .to_string()
602 })
603 .unwrap_or_else(|| {
604 details
605 .instrument
606 .expiry
607 .split('T')
608 .next()
609 .unwrap_or(&details.instrument.expiry)
610 .to_string()
611 });
612
613 let high_low = format!(
614 "{}/{}",
615 details
616 .snapshot
617 .high
618 .map(|h| format!("{:.2}", h))
619 .unwrap_or_else(|| "-".to_string()),
620 details
621 .snapshot
622 .low
623 .map(|l| format!("{:.2}", l))
624 .unwrap_or_else(|| "-".to_string())
625 );
626
627 let name = if details.instrument.name.len() > 30 {
629 format!("{}...", &details.instrument.name[0..27])
630 } else {
631 details.instrument.name.clone()
632 };
633
634 let epic = details.instrument.epic.clone();
636
637 table.add_row(Row::new(vec![
638 Cell::new(&name),
639 Cell::new(&epic),
640 Cell::new(&bid),
641 Cell::new(&offer),
642 Cell::new(&mid),
643 Cell::new(&spread),
644 Cell::new(&expiry),
645 Cell::new(&high_low),
646 ]));
647 }
648
649 write!(f, "{}", table)
650 }
651}
652
653impl std::fmt::Display for HistoricalPricesResponse {
654 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
655 use prettytable::format;
656 use prettytable::{Cell, Row, Table};
657
658 let mut table = Table::new();
659 table.set_format(*format::consts::FORMAT_BOX_CHARS);
660
661 table.add_row(Row::new(vec![
663 Cell::new("SNAPSHOT TIME"),
664 Cell::new("OPEN BID"),
665 Cell::new("OPEN ASK"),
666 Cell::new("HIGH BID"),
667 Cell::new("HIGH ASK"),
668 Cell::new("LOW BID"),
669 Cell::new("LOW ASK"),
670 Cell::new("CLOSE BID"),
671 Cell::new("CLOSE ASK"),
672 Cell::new("VOLUME"),
673 ]));
674
675 for price in &self.prices {
677 let open_bid = price
678 .open_price
679 .bid
680 .map(|v| format!("{:.4}", v))
681 .unwrap_or_else(|| "-".to_string());
682
683 let open_ask = price
684 .open_price
685 .ask
686 .map(|v| format!("{:.4}", v))
687 .unwrap_or_else(|| "-".to_string());
688
689 let high_bid = price
690 .high_price
691 .bid
692 .map(|v| format!("{:.4}", v))
693 .unwrap_or_else(|| "-".to_string());
694
695 let high_ask = price
696 .high_price
697 .ask
698 .map(|v| format!("{:.4}", v))
699 .unwrap_or_else(|| "-".to_string());
700
701 let low_bid = price
702 .low_price
703 .bid
704 .map(|v| format!("{:.4}", v))
705 .unwrap_or_else(|| "-".to_string());
706
707 let low_ask = price
708 .low_price
709 .ask
710 .map(|v| format!("{:.4}", v))
711 .unwrap_or_else(|| "-".to_string());
712
713 let close_bid = price
714 .close_price
715 .bid
716 .map(|v| format!("{:.4}", v))
717 .unwrap_or_else(|| "-".to_string());
718
719 let close_ask = price
720 .close_price
721 .ask
722 .map(|v| format!("{:.4}", v))
723 .unwrap_or_else(|| "-".to_string());
724
725 let volume = price
726 .last_traded_volume
727 .map(|v| v.to_string())
728 .unwrap_or_else(|| "-".to_string());
729
730 table.add_row(Row::new(vec![
731 Cell::new(&price.snapshot_time),
732 Cell::new(&open_bid),
733 Cell::new(&open_ask),
734 Cell::new(&high_bid),
735 Cell::new(&high_ask),
736 Cell::new(&low_bid),
737 Cell::new(&low_ask),
738 Cell::new(&close_bid),
739 Cell::new(&close_ask),
740 Cell::new(&volume),
741 ]));
742 }
743
744 writeln!(f, "{}", table)?;
746 writeln!(f, "\nSummary:")?;
747 writeln!(f, " Total price points: {}", self.prices.len())?;
748 writeln!(f, " Instrument type: {:?}", self.instrument_type)?;
749
750 if let Some(allowance) = &self.allowance {
751 writeln!(
752 f,
753 " Remaining allowance: {}",
754 allowance.remaining_allowance
755 )?;
756 writeln!(f, " Total allowance: {}", allowance.total_allowance)?;
757 }
758
759 Ok(())
760 }
761}
762
763impl std::fmt::Display for MarketSearchResponse {
764 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
765 use prettytable::format;
766 use prettytable::{Cell, Row, Table};
767
768 let mut table = Table::new();
769 table.set_format(*format::consts::FORMAT_BOX_CHARS);
770
771 table.add_row(Row::new(vec![
773 Cell::new("INSTRUMENT NAME"),
774 Cell::new("EPIC"),
775 Cell::new("BID"),
776 Cell::new("OFFER"),
777 Cell::new("MID"),
778 Cell::new("SPREAD"),
779 Cell::new("EXPIRY"),
780 Cell::new("TYPE"),
781 ]));
782
783 let mut sorted_markets = self.markets.clone();
785 sorted_markets.sort_by(|a, b| {
786 a.instrument_name
787 .to_lowercase()
788 .cmp(&b.instrument_name.to_lowercase())
789 });
790
791 for market in &sorted_markets {
793 let bid = market
794 .bid
795 .map(|b| format!("{:.4}", b))
796 .unwrap_or_else(|| "-".to_string());
797
798 let offer = market
799 .offer
800 .map(|o| format!("{:.4}", o))
801 .unwrap_or_else(|| "-".to_string());
802
803 let mid = match (market.bid, market.offer) {
804 (Some(b), Some(o)) => format!("{:.4}", (b + o) / 2.0),
805 _ => "-".to_string(),
806 };
807
808 let spread = match (market.bid, market.offer) {
809 (Some(b), Some(o)) => format!("{:.4}", o - b),
810 _ => "-".to_string(),
811 };
812
813 let name = if market.instrument_name.len() > 30 {
815 format!("{}...", &market.instrument_name[0..27])
816 } else {
817 market.instrument_name.clone()
818 };
819
820 let expiry = market
822 .expiry
823 .split('T')
824 .next()
825 .unwrap_or(&market.expiry)
826 .to_string();
827
828 let instrument_type = format!("{:?}", market.instrument_type);
829
830 table.add_row(Row::new(vec![
831 Cell::new(&name),
832 Cell::new(&market.epic),
833 Cell::new(&bid),
834 Cell::new(&offer),
835 Cell::new(&mid),
836 Cell::new(&spread),
837 Cell::new(&expiry),
838 Cell::new(&instrument_type),
839 ]));
840 }
841
842 writeln!(f, "{}", table)?;
843 writeln!(f, "\nTotal markets found: {}", self.markets.len())?;
844
845 Ok(())
846 }
847}
848
849#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
855pub struct WatchlistsResponse {
856 pub watchlists: Vec<Watchlist>,
858}
859
860#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
862pub struct Watchlist {
863 pub id: String,
865 pub name: String,
867 pub editable: bool,
869 pub deleteable: bool,
871 #[serde(rename = "defaultSystemWatchlist")]
873 pub default_system_watchlist: bool,
874}
875
876#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
878pub struct CreateWatchlistResponse {
879 #[serde(rename = "watchlistId")]
881 pub watchlist_id: String,
882 pub status: String,
884}
885
886#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
888pub struct WatchlistMarketsResponse {
889 pub markets: Vec<MarketData>,
891}
892
893#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
895pub struct StatusResponse {
896 pub status: String,
898}
899
900#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
906pub struct ClientSentimentResponse {
907 #[serde(rename = "clientSentiments")]
909 pub client_sentiments: Vec<MarketSentiment>,
910}
911
912#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
914pub struct MarketSentiment {
915 #[serde(rename = "marketId")]
917 pub market_id: String,
918 #[serde(rename = "longPositionPercentage")]
920 pub long_position_percentage: f64,
921 #[serde(rename = "shortPositionPercentage")]
923 pub short_position_percentage: f64,
924}
925
926#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
932pub struct IndicativeCostsResponse {
933 #[serde(rename = "indicativeQuoteReference")]
935 pub indicative_quote_reference: String,
936 #[serde(rename = "costsAndCharges")]
938 pub costs_and_charges: CostsAndCharges,
939}
940
941#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
943pub struct CostsAndCharges {
944 #[serde(rename = "totalCostPercentage")]
946 pub total_cost_percentage: Option<f64>,
947 #[serde(rename = "totalCostAmount")]
949 pub total_cost_amount: Option<f64>,
950 pub currency: Option<String>,
952 #[serde(rename = "oneOffCosts")]
954 pub one_off_costs: Option<CostBreakdown>,
955 #[serde(rename = "ongoingCosts")]
957 pub ongoing_costs: Option<CostBreakdown>,
958 #[serde(rename = "transactionCosts")]
960 pub transaction_costs: Option<CostBreakdown>,
961 #[serde(rename = "incidentalCosts")]
963 pub incidental_costs: Option<CostBreakdown>,
964}
965
966#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
968pub struct CostBreakdown {
969 pub percentage: Option<f64>,
971 pub amount: Option<f64>,
973}
974
975#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
977pub struct CostsHistoryResponse {
978 pub costs: Vec<HistoricalCost>,
980}
981
982#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
984pub struct HistoricalCost {
985 pub date: String,
987 #[serde(rename = "dealReference")]
989 pub deal_reference: Option<String>,
990 pub epic: Option<String>,
992 #[serde(rename = "totalCost")]
994 pub total_cost: Option<f64>,
995 pub currency: Option<String>,
997}
998
999#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
1001pub struct DurableMediumResponse {
1002 pub document: String,
1004}
1005
1006#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
1012pub struct AccountPreferencesResponse {
1013 #[serde(rename = "trailingStopsEnabled")]
1015 pub trailing_stops_enabled: bool,
1016}
1017
1018#[derive(DebugPretty, Clone, Serialize, Deserialize, Default)]
1024pub struct ApplicationDetailsResponse {
1025 #[serde(rename = "apiKey")]
1027 pub api_key: String,
1028 pub name: Option<String>,
1030 pub status: String,
1032 #[serde(rename = "allowanceAccountOverall")]
1034 pub allowance_account_overall: Option<i64>,
1035 #[serde(rename = "allowanceAccountTrading")]
1037 pub allowance_account_trading: Option<i64>,
1038 #[serde(rename = "concurrentSubscriptionsLimit")]
1040 pub concurrent_subscriptions_limit: Option<i64>,
1041 #[serde(rename = "createdDate")]
1043 pub created_date: Option<String>,
1044}
1045
1046#[derive(DebugPretty, Clone, Serialize, Deserialize)]
1052pub struct SinglePositionResponse {
1053 pub position: Position,
1055 pub market: MarketData,
1057}
1058
1059#[cfg(test)]
1060mod tests {
1061 use super::*;
1062 use crate::model::auth::{SessionResponse, V3Response};
1063 use crate::presentation::account::ActivityType;
1064
1065 fn roundtrip<T>(value: &T) -> T
1071 where
1072 T: serde::Serialize + serde::de::DeserializeOwned,
1073 {
1074 let json = serde_json::to_string(value).expect("serialize failed");
1075 serde_json::from_str(&json).expect("re-deserialize failed")
1076 }
1077
1078 #[test]
1079 fn test_accounts_response_deserialize_and_roundtrip() {
1080 let json = r#"{
1081 "accounts": [
1082 {
1083 "accountId": "ABC12",
1084 "accountName": "Demo CFD",
1085 "accountType": "CFD",
1086 "balance": {
1087 "balance": 10000.0,
1088 "deposit": 2000.0,
1089 "profitLoss": 150.5,
1090 "available": 8000.0
1091 },
1092 "currency": "EUR",
1093 "status": "ENABLED",
1094 "preferred": true
1095 }
1096 ]
1097 }"#;
1098
1099 let resp: AccountsResponse = serde_json::from_str(json).expect("deserialize failed");
1100 assert_eq!(resp.accounts.len(), 1);
1101 let acc = &resp.accounts[0];
1102 assert_eq!(acc.account_id, "ABC12");
1103 assert_eq!(acc.account_type, "CFD");
1104 assert!((acc.balance.available - 8000.0).abs() < 1e-9);
1105 assert!(acc.preferred);
1106
1107 let re = roundtrip(&resp);
1108 assert_eq!(re.accounts[0].account_id, "ABC12");
1109 assert_eq!(re.accounts[0].currency, "EUR");
1110 }
1111
1112 #[test]
1113 fn test_positions_response_deserialize_and_roundtrip() {
1114 let json = r#"{
1115 "positions": [
1116 {
1117 "position": {
1118 "contractSize": 1.0,
1119 "createdDate": "2025/07/01 10:00:00:000",
1120 "createdDateUTC": "2025-07-01T08:00:00",
1121 "dealId": "DIFAKE111",
1122 "dealReference": "REFFAKE111",
1123 "direction": "BUY",
1124 "limitLevel": null,
1125 "level": 100.5,
1126 "size": 2.0,
1127 "stopLevel": null,
1128 "trailingStep": null,
1129 "trailingStopDistance": null,
1130 "currency": "GBP",
1131 "controlledRisk": false,
1132 "limitedRiskPremium": null
1133 },
1134 "market": {
1135 "instrumentName": "FTSE 100",
1136 "expiry": "-",
1137 "epic": "IX.D.FTSE.DAILY.IP",
1138 "instrumentType": "INDICES",
1139 "lotSize": 1.0,
1140 "high": 7600.0,
1141 "low": 7500.0,
1142 "percentageChange": 0.5,
1143 "netChange": 30.0,
1144 "bid": 7550.0,
1145 "offer": 7551.0,
1146 "updateTime": "10:00:00",
1147 "updateTimeUTC": "08:00:00",
1148 "delayTime": 0,
1149 "streamingPricesAvailable": true,
1150 "marketStatus": "TRADEABLE",
1151 "scalingFactor": 1
1152 },
1153 "pnl": null
1154 }
1155 ]
1156 }"#;
1157
1158 let resp: PositionsResponse = serde_json::from_str(json).expect("deserialize failed");
1159 assert_eq!(resp.positions.len(), 1);
1160 let pos = &resp.positions[0];
1161 assert_eq!(pos.position.deal_id, "DIFAKE111");
1162 assert_eq!(pos.position.direction, Direction::Buy);
1163 assert!((pos.position.size - 2.0).abs() < 1e-9);
1164 assert_eq!(pos.market.epic, "IX.D.FTSE.DAILY.IP");
1165 assert_eq!(pos.market.bid, Some(7550.0));
1166 assert!(pos.pnl.is_none());
1167
1168 let re = roundtrip(&resp);
1169 assert_eq!(re.positions[0].position.deal_id, "DIFAKE111");
1170 assert_eq!(re.positions[0].market.epic, "IX.D.FTSE.DAILY.IP");
1171 }
1172
1173 #[test]
1174 fn test_working_orders_response_deserialize_and_roundtrip() {
1175 let json = r#"{
1178 "workingOrders": [
1179 {
1180 "workingOrderData": {
1181 "dealId": "DIFAKEWO1",
1182 "direction": "SELL",
1183 "epic": "CS.D.EURUSD.MINI.IP",
1184 "orderSize": 1.5,
1185 "orderLevel": 1.2345,
1186 "timeInForce": "GOOD_TILL_CANCELLED",
1187 "goodTillDate": null,
1188 "goodTillDateISO": null,
1189 "createdDate": "2025/07/01 09:30:00:000",
1190 "createdDateUTC": "2025-07-01T07:30:00",
1191 "guaranteedStop": false,
1192 "orderType": "LIMIT",
1193 "stopDistance": null,
1194 "limitDistance": null,
1195 "currencyCode": "USD",
1196 "dma": false,
1197 "limitedRiskPremium": null,
1198 "limitLevel": null,
1199 "stopLevel": null,
1200 "dealReference": "REFFAKEWO1"
1201 },
1202 "marketData": {
1203 "instrumentName": "EUR/USD Mini",
1204 "exchangeId": "FX",
1205 "expiry": "-",
1206 "marketStatus": "TRADEABLE",
1207 "epic": "CS.D.EURUSD.MINI.IP",
1208 "instrumentType": "CURRENCIES",
1209 "lotSize": 1.0,
1210 "high": 1.24,
1211 "low": 1.23,
1212 "percentageChange": 0.1,
1213 "netChange": 0.001,
1214 "bid": 1.2344,
1215 "offer": 1.2346,
1216 "updateTime": "09:30:00",
1217 "updateTimeUTC": "07:30:00",
1218 "delayTime": 0,
1219 "streamingPricesAvailable": true,
1220 "scalingFactor": 1
1221 }
1222 }
1223 ]
1224 }"#;
1225
1226 let resp: WorkingOrdersResponse = serde_json::from_str(json).expect("deserialize failed");
1227 assert_eq!(resp.working_orders.len(), 1);
1228 let order = &resp.working_orders[0];
1229 assert_eq!(order.working_order_data.epic, "CS.D.EURUSD.MINI.IP");
1230 assert_eq!(order.working_order_data.direction, Direction::Sell);
1231 assert!((order.working_order_data.order_size - 1.5).abs() < 1e-9);
1232 assert!((order.working_order_data.order_level - 1.2345).abs() < 1e-9);
1233 assert_eq!(
1234 order.market_data.instrument_type,
1235 InstrumentType::Currencies
1236 );
1237
1238 let re = roundtrip(&resp);
1239 assert_eq!(re.working_orders[0].working_order_data.deal_id, "DIFAKEWO1");
1240 assert_eq!(re.working_orders[0].market_data.epic, "CS.D.EURUSD.MINI.IP");
1241 }
1242
1243 #[test]
1244 fn test_account_activity_response_deserialize_and_roundtrip() {
1245 let json = r#"{
1246 "activities": [
1247 {
1248 "date": "2025-07-01T09:00:00",
1249 "dealId": "DIFAKEACT1",
1250 "epic": "IX.D.FTSE.DAILY.IP",
1251 "period": "DAY",
1252 "dealReference": "REFFAKEACT1",
1253 "type": "POSITION",
1254 "status": "ACCEPTED",
1255 "description": "Position opened",
1256 "channel": "WEB",
1257 "currency": "GBP",
1258 "level": "7550.0"
1259 }
1260 ],
1261 "metadata": { "paging": { "size": 50, "next": null } }
1262 }"#;
1263
1264 let resp: AccountActivityResponse = serde_json::from_str(json).expect("deserialize failed");
1265 assert_eq!(resp.activities.len(), 1);
1266 let act = &resp.activities[0];
1267 assert_eq!(act.deal_id.as_deref(), Some("DIFAKEACT1"));
1268 assert_eq!(act.activity_type, ActivityType::Position);
1269 assert_eq!(act.status, Some(Status::Accepted));
1270 assert!(resp.metadata.is_some());
1271
1272 let re = roundtrip(&resp);
1273 assert_eq!(re.activities[0].activity_type, ActivityType::Position);
1274 assert_eq!(
1275 re.activities[0].deal_reference.as_deref(),
1276 Some("REFFAKEACT1")
1277 );
1278 }
1279
1280 #[test]
1281 fn test_transaction_history_response_deserialize_and_roundtrip() {
1282 let json = r#"{
1283 "transactions": [
1284 {
1285 "date": "01/07/25",
1286 "dateUtc": "2025-07-01T08:00:00",
1287 "openDateUtc": "2025-06-30T08:00:00",
1288 "instrumentName": "FTSE 100",
1289 "period": "DAY",
1290 "profitAndLoss": "E150.50",
1291 "transactionType": "DEAL",
1292 "reference": "REFFAKETX1",
1293 "openLevel": "7500.0",
1294 "closeLevel": "7550.0",
1295 "size": "2",
1296 "currency": "GBP",
1297 "cashTransaction": false
1298 }
1299 ],
1300 "metadata": {
1301 "pageData": { "pageNumber": 1, "pageSize": 20, "totalPages": 1 },
1302 "size": 1
1303 }
1304 }"#;
1305
1306 let resp: TransactionHistoryResponse =
1307 serde_json::from_str(json).expect("deserialize failed");
1308 assert_eq!(resp.transactions.len(), 1);
1309 assert_eq!(resp.transactions[0].reference, "REFFAKETX1");
1310 assert_eq!(resp.transactions[0].profit_and_loss, "E150.50");
1311 assert_eq!(resp.metadata.size, 1);
1312 assert_eq!(resp.metadata.page_data.page_number, 1);
1313
1314 let re = roundtrip(&resp);
1315 assert_eq!(re.transactions[0].reference, "REFFAKETX1");
1316 assert_eq!(re.metadata.page_data.total_pages, 1);
1317 }
1318
1319 #[test]
1320 fn test_watchlists_response_deserialize_and_roundtrip() {
1321 let json = r#"{
1322 "watchlists": [
1323 {
1324 "id": "WL1",
1325 "name": "My Watchlist",
1326 "editable": true,
1327 "deleteable": true,
1328 "defaultSystemWatchlist": false
1329 }
1330 ]
1331 }"#;
1332
1333 let resp: WatchlistsResponse = serde_json::from_str(json).expect("deserialize failed");
1334 assert_eq!(resp.watchlists.len(), 1);
1335 let wl = &resp.watchlists[0];
1336 assert_eq!(wl.id, "WL1");
1337 assert_eq!(wl.name, "My Watchlist");
1338 assert!(wl.editable);
1339 assert!(!wl.default_system_watchlist);
1340
1341 let re = roundtrip(&resp);
1342 assert_eq!(re.watchlists[0].id, "WL1");
1343 assert!(re.watchlists[0].deleteable);
1344 }
1345
1346 #[test]
1347 fn test_client_sentiment_response_deserialize_and_roundtrip() {
1348 let json = r#"{
1349 "clientSentiments": [
1350 {
1351 "marketId": "EURUSD",
1352 "longPositionPercentage": 62.5,
1353 "shortPositionPercentage": 37.5
1354 }
1355 ]
1356 }"#;
1357
1358 let resp: ClientSentimentResponse = serde_json::from_str(json).expect("deserialize failed");
1359 assert_eq!(resp.client_sentiments.len(), 1);
1360 let s = &resp.client_sentiments[0];
1361 assert_eq!(s.market_id, "EURUSD");
1362 assert!((s.long_position_percentage - 62.5).abs() < 1e-9);
1363 assert!((s.short_position_percentage - 37.5).abs() < 1e-9);
1364
1365 let re = roundtrip(&resp);
1366 assert_eq!(re.client_sentiments[0].market_id, "EURUSD");
1367 }
1368
1369 #[test]
1370 fn test_indicative_costs_response_deserialize_and_roundtrip() {
1371 let json = r#"{
1372 "indicativeQuoteReference": "QREF-FAKE-1",
1373 "costsAndCharges": {
1374 "totalCostPercentage": 0.12,
1375 "totalCostAmount": 3.45,
1376 "currency": "GBP",
1377 "oneOffCosts": { "percentage": 0.05, "amount": 1.0 },
1378 "ongoingCosts": { "percentage": 0.02, "amount": 0.5 },
1379 "transactionCosts": { "percentage": 0.03, "amount": 1.2 },
1380 "incidentalCosts": { "percentage": 0.02, "amount": 0.75 }
1381 }
1382 }"#;
1383
1384 let resp: IndicativeCostsResponse = serde_json::from_str(json).expect("deserialize failed");
1385 assert_eq!(resp.indicative_quote_reference, "QREF-FAKE-1");
1386 assert_eq!(resp.costs_and_charges.total_cost_amount, Some(3.45));
1387 assert_eq!(resp.costs_and_charges.currency.as_deref(), Some("GBP"));
1388 let one_off = resp
1389 .costs_and_charges
1390 .one_off_costs
1391 .as_ref()
1392 .expect("oneOffCosts present");
1393 assert_eq!(one_off.amount, Some(1.0));
1394
1395 let re = roundtrip(&resp);
1396 assert_eq!(re.indicative_quote_reference, "QREF-FAKE-1");
1397 assert_eq!(re.costs_and_charges.total_cost_percentage, Some(0.12));
1398 }
1399
1400 #[test]
1401 fn test_costs_and_charges_deserialize_and_roundtrip() {
1402 let json = r#"{
1403 "totalCostPercentage": 0.20,
1404 "totalCostAmount": 5.0,
1405 "currency": "USD",
1406 "transactionCosts": { "percentage": 0.10, "amount": 2.5 }
1407 }"#;
1408
1409 let costs: CostsAndCharges = serde_json::from_str(json).expect("deserialize failed");
1410 assert_eq!(costs.total_cost_amount, Some(5.0));
1411 assert_eq!(costs.currency.as_deref(), Some("USD"));
1412 assert!(costs.one_off_costs.is_none());
1414 assert!(costs.ongoing_costs.is_none());
1415 let txn = costs
1416 .transaction_costs
1417 .as_ref()
1418 .expect("transactionCosts present");
1419 assert_eq!(txn.percentage, Some(0.10));
1420
1421 let re = roundtrip(&costs);
1422 assert_eq!(re.total_cost_amount, Some(5.0));
1423 }
1424
1425 #[test]
1426 fn test_costs_history_response_deserialize_and_roundtrip() {
1427 let json = r#"{
1428 "costs": [
1429 {
1430 "date": "2025-07-01",
1431 "dealReference": "REFFAKEC1",
1432 "epic": "IX.D.FTSE.DAILY.IP",
1433 "totalCost": 5.5,
1434 "currency": "GBP"
1435 }
1436 ]
1437 }"#;
1438
1439 let resp: CostsHistoryResponse = serde_json::from_str(json).expect("deserialize failed");
1440 assert_eq!(resp.costs.len(), 1);
1441 let cost = &resp.costs[0];
1442 assert_eq!(cost.date, "2025-07-01");
1443 assert_eq!(cost.deal_reference.as_deref(), Some("REFFAKEC1"));
1444 assert_eq!(cost.total_cost, Some(5.5));
1445
1446 let re = roundtrip(&resp);
1447 assert_eq!(re.costs[0].epic.as_deref(), Some("IX.D.FTSE.DAILY.IP"));
1448 }
1449
1450 #[test]
1451 fn test_durable_medium_response_deserialize_and_roundtrip() {
1452 let json = r#"{ "document": "<html>Terms and Conditions</html>" }"#;
1453
1454 let resp: DurableMediumResponse = serde_json::from_str(json).expect("deserialize failed");
1455 assert_eq!(resp.document, "<html>Terms and Conditions</html>");
1456
1457 let re = roundtrip(&resp);
1458 assert_eq!(re.document, "<html>Terms and Conditions</html>");
1459 }
1460
1461 #[test]
1462 fn test_account_preferences_response_deserialize_and_roundtrip() {
1463 let json = r#"{ "trailingStopsEnabled": true }"#;
1464
1465 let resp: AccountPreferencesResponse =
1466 serde_json::from_str(json).expect("deserialize failed");
1467 assert!(resp.trailing_stops_enabled);
1468
1469 let re = roundtrip(&resp);
1470 assert!(re.trailing_stops_enabled);
1471 }
1472
1473 #[test]
1474 fn test_application_details_response_deserialize_and_roundtrip() {
1475 let json = r#"{
1478 "apiKey": "FAKE-API-KEY",
1479 "name": "My App",
1480 "status": "ENABLED",
1481 "allowanceAccountOverall": 3000000000,
1482 "allowanceAccountTrading": 1000,
1483 "concurrentSubscriptionsLimit": 40,
1484 "createdDate": "2025-01-01"
1485 }"#;
1486
1487 let resp: ApplicationDetailsResponse =
1488 serde_json::from_str(json).expect("deserialize failed");
1489 assert_eq!(resp.api_key, "FAKE-API-KEY");
1490 assert_eq!(resp.name.as_deref(), Some("My App"));
1491 assert_eq!(resp.status, "ENABLED");
1492 assert!(resp.allowance_account_overall > Some(i64::from(i32::MAX)));
1493 assert_eq!(resp.allowance_account_overall, Some(3_000_000_000));
1494 assert_eq!(resp.concurrent_subscriptions_limit, Some(40));
1495
1496 let re = roundtrip(&resp);
1497 assert_eq!(re.api_key, "FAKE-API-KEY");
1498 assert_eq!(re.allowance_account_overall, Some(3_000_000_000));
1499 assert_eq!(re.allowance_account_trading, Some(1000));
1500 }
1501
1502 #[test]
1503 fn test_categories_response_deserialize_and_roundtrip() {
1504 let json = r#"{
1505 "categories": [
1506 { "code": "INDICES", "nonTradeable": false },
1507 { "code": "CRYPTOCURRENCY", "nonTradeable": true }
1508 ]
1509 }"#;
1510
1511 let resp: CategoriesResponse = serde_json::from_str(json).expect("deserialize failed");
1512 assert_eq!(resp.len(), 2);
1513 assert_eq!(resp.categories[0].code, "INDICES");
1514 assert!(!resp.categories[0].non_tradeable);
1515 assert!(resp.categories[1].non_tradeable);
1516
1517 let re = roundtrip(&resp);
1518 assert_eq!(re.categories[1].code, "CRYPTOCURRENCY");
1519 }
1520
1521 #[test]
1522 fn test_historical_prices_response_deserialize_and_roundtrip() {
1523 let json = r#"{
1524 "prices": [
1525 {
1526 "snapshotTime": "2025:07:01-09:00:00",
1527 "openPrice": { "bid": 1.2340, "ask": 1.2342, "lastTraded": null },
1528 "highPrice": { "bid": 1.2350, "ask": 1.2352, "lastTraded": null },
1529 "lowPrice": { "bid": 1.2330, "ask": 1.2332, "lastTraded": null },
1530 "closePrice": { "bid": 1.2345, "ask": 1.2347, "lastTraded": null },
1531 "lastTradedVolume": 1234
1532 }
1533 ],
1534 "instrumentType": "CURRENCIES",
1535 "allowance": {
1536 "remainingAllowance": 9950,
1537 "totalAllowance": 10000,
1538 "allowanceExpiry": 604800
1539 }
1540 }"#;
1541
1542 let resp: HistoricalPricesResponse =
1543 serde_json::from_str(json).expect("deserialize failed");
1544 assert_eq!(resp.len(), 1);
1545 assert_eq!(resp.prices[0].snapshot_time, "2025:07:01-09:00:00");
1546 assert_eq!(resp.prices[0].close_price.bid, Some(1.2345));
1547 assert_eq!(resp.prices[0].last_traded_volume, Some(1234));
1548 assert_eq!(resp.instrument_type, InstrumentType::Currencies);
1549 let allowance = resp.allowance.as_ref().expect("allowance present");
1550 assert_eq!(allowance.remaining_allowance, 9950);
1551 assert_eq!(allowance.total_allowance, 10000);
1552
1553 let re = roundtrip(&resp);
1554 assert_eq!(re.prices[0].open_price.ask, Some(1.2342));
1555 assert_eq!(
1556 re.allowance.as_ref().map(|a| a.allowance_expiry),
1557 Some(604800)
1558 );
1559 }
1560
1561 #[test]
1562 fn test_v3_login_response_deserialize_and_roundtrip() {
1563 let json = r#"{
1567 "clientId": "FAKE-CLIENT-101",
1568 "accountId": "ABC12",
1569 "timezoneOffset": 1,
1570 "lightstreamerEndpoint": "https://demo-apd.marketdatasystems.com",
1571 "oauthToken": {
1572 "access_token": "FAKE-ACCESS-TOKEN",
1573 "refresh_token": "FAKE-REFRESH-TOKEN",
1574 "scope": "profile",
1575 "token_type": "Bearer",
1576 "expires_in": "60"
1577 }
1578 }"#;
1579
1580 let resp: V3Response = serde_json::from_str(json).expect("deserialize failed");
1581 assert_eq!(resp.client_id, "FAKE-CLIENT-101");
1582 assert_eq!(resp.account_id, "ABC12");
1583 assert_eq!(resp.oauth_token.access_token, "FAKE-ACCESS-TOKEN");
1584 assert_eq!(resp.oauth_token.refresh_token, "FAKE-REFRESH-TOKEN");
1585 assert_eq!(resp.oauth_token.token_type, "Bearer");
1586 assert_eq!(resp.oauth_token.expires_in, "60");
1587
1588 let session_resp: SessionResponse =
1590 serde_json::from_str(json).expect("session deserialize failed");
1591 assert!(session_resp.is_v3());
1592 assert!(session_resp.get_session().is_oauth());
1593
1594 let re = roundtrip(&resp);
1595 assert_eq!(re.oauth_token.access_token, "FAKE-ACCESS-TOKEN");
1596 assert_eq!(re.account_id, "ABC12");
1597 }
1598}