ig-client 0.11.3

This crate provides a client for the IG Markets API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
use crate::presentation::instrument::InstrumentType;
use crate::presentation::market::MarketState;
use crate::presentation::order::{Direction, OrderType, Status, TimeInForce};
use crate::presentation::serialization::string_as_float_opt;
use lightstreamer_rs::subscription::ItemUpdate;
use pretty_simple_display::{DebugPretty, DisplaySimple};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::ops::Add;

/// Account information
#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
pub struct AccountInfo {
    /// List of accounts owned by the user
    pub accounts: Vec<Account>,
}

/// Details of a specific account
#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
pub struct Account {
    /// Unique identifier for the account
    #[serde(rename = "accountId")]
    pub account_id: String,
    /// Name of the account
    #[serde(rename = "accountName")]
    pub account_name: String,
    /// Type of the account (e.g., CFD, Spread bet)
    #[serde(rename = "accountType")]
    pub account_type: String,
    /// Balance information for the account
    pub balance: AccountBalance,
    /// Base currency of the account
    pub currency: String,
    /// Current status of the account
    pub status: String,
    /// Whether this is the preferred account
    pub preferred: bool,
}

/// Account balance information
#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
pub struct AccountBalance {
    /// Total balance of the account
    pub balance: f64,
    /// Deposit amount
    pub deposit: f64,
    /// Current profit or loss
    #[serde(rename = "profitLoss")]
    pub profit_loss: f64,
    /// Available funds for trading
    pub available: f64,
}

/// Metadata for activity pagination
#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
pub struct ActivityMetadata {
    /// Paging information
    pub paging: Option<ActivityPaging>,
}

/// Paging information for activities
#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
pub struct ActivityPaging {
    /// Number of items per page
    pub size: Option<i32>,
    /// URL for the next page of results
    pub next: Option<String>,
}

/// Type of account activity
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, DisplaySimple, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ActivityType {
    /// Activity related to editing stop and limit orders
    EditStopAndLimit,
    /// Activity related to positions
    Position,
    /// System-generated activity
    System,
    /// Activity related to working orders
    WorkingOrder,
}

/// Individual activity record
#[derive(Debug, Clone, DisplaySimple, Deserialize, Serialize)]
pub struct Activity {
    /// Date and time of the activity
    pub date: String,
    /// Unique identifier for the deal
    #[serde(rename = "dealId", default)]
    pub deal_id: Option<String>,
    /// Instrument EPIC identifier
    #[serde(default)]
    pub epic: Option<String>,
    /// Time period of the activity
    #[serde(default)]
    pub period: Option<String>,
    /// Client-generated reference for the deal
    #[serde(rename = "dealReference", default)]
    pub deal_reference: Option<String>,
    /// Type of activity
    #[serde(rename = "type")]
    pub activity_type: ActivityType,
    /// Status of the activity
    #[serde(default)]
    pub status: Option<Status>,
    /// Description of the activity
    #[serde(default)]
    pub description: Option<String>,
    /// Additional details about the activity
    /// This is a string when detailed=false, and an object when detailed=true
    #[serde(default)]
    pub details: Option<ActivityDetails>,
    /// Channel the activity occurred on (e.g., "WEB" or "Mobile")
    #[serde(default)]
    pub channel: Option<String>,
    /// The currency, e.g., a pound symbol
    #[serde(default)]
    pub currency: Option<String>,
    /// Price level
    #[serde(default)]
    pub level: Option<String>,
}

/// Detailed information about an activity
/// Only available when using the detailed=true parameter
#[derive(Debug, Clone, DisplaySimple, Deserialize, Serialize)]
pub struct ActivityDetails {
    /// Client-generated reference for the deal
    #[serde(rename = "dealReference", default)]
    pub deal_reference: Option<String>,
    /// List of actions associated with this activity
    #[serde(default)]
    pub actions: Vec<ActivityAction>,
    /// Name of the market
    #[serde(rename = "marketName", default)]
    pub market_name: Option<String>,
    /// Date until which the order is valid
    #[serde(rename = "goodTillDate", default)]
    pub good_till_date: Option<String>,
    /// Currency of the transaction
    #[serde(default)]
    pub currency: Option<String>,
    /// Size/quantity of the transaction
    #[serde(default)]
    pub size: Option<f64>,
    /// Direction of the transaction (BUY or SELL)
    #[serde(default)]
    pub direction: Option<Direction>,
    /// Price level
    #[serde(default)]
    pub level: Option<f64>,
    /// Stop level price
    #[serde(rename = "stopLevel", default)]
    pub stop_level: Option<f64>,
    /// Distance for the stop
    #[serde(rename = "stopDistance", default)]
    pub stop_distance: Option<f64>,
    /// Whether the stop is guaranteed
    #[serde(rename = "guaranteedStop", default)]
    pub guaranteed_stop: Option<bool>,
    /// Distance for the trailing stop
    #[serde(rename = "trailingStopDistance", default)]
    pub trailing_stop_distance: Option<f64>,
    /// Step size for the trailing stop
    #[serde(rename = "trailingStep", default)]
    pub trailing_step: Option<f64>,
    /// Limit level price
    #[serde(rename = "limitLevel", default)]
    pub limit_level: Option<f64>,
    /// Distance for the limit
    #[serde(rename = "limitDistance", default)]
    pub limit_distance: Option<f64>,
}

/// Types of actions that can be performed on an activity
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, DisplaySimple, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ActionType {
    /// A limit order was deleted
    LimitOrderDeleted,
    /// A limit order was filled
    LimitOrderFilled,
    /// A limit order was opened
    LimitOrderOpened,
    /// A limit order was rolled
    LimitOrderRolled,
    /// A position was closed
    PositionClosed,
    /// A position was deleted
    PositionDeleted,
    /// A position was opened
    PositionOpened,
    /// A position was partially closed
    PositionPartiallyClosed,
    /// A position was rolled
    PositionRolled,
    /// A stop/limit was amended
    StopLimitAmended,
    /// A stop order was amended
    StopOrderAmended,
    /// A stop order was deleted
    StopOrderDeleted,
    /// A stop order was filled
    StopOrderFilled,
    /// A stop order was opened
    StopOrderOpened,
    /// A stop order was rolled
    StopOrderRolled,
    /// Unknown action type
    Unknown,
    /// A working order was deleted
    WorkingOrderDeleted,
}

/// Action associated with an activity
#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActivityAction {
    /// Type of action
    pub action_type: ActionType,
    /// Deal ID affected by this action
    pub affected_deal_id: Option<String>,
}

/// Individual position
#[derive(DebugPretty, Clone, DisplaySimple, Serialize, Deserialize)]
pub struct Position {
    /// Details of the position
    pub position: PositionDetails,
    /// Market information for the position
    pub market: PositionMarket,
    /// Profit and loss for the position
    pub pnl: Option<f64>,
}

impl Position {
    /// Calculates the profit and loss (PnL) for the current position
    /// of a trader.
    ///
    /// The method determines PnL based on whether it is already cached
    /// (`self.pnl`) or needs to be calculated from the position and
    /// market details.
    ///
    /// # Returns
    ///
    /// A floating-point value that represents the PnL for the position.
    /// Positive values indicate a profit, and negative values indicate a loss.
    ///
    /// # Logic
    ///
    /// - If `self.pnl` is available, it directly returns the cached value.
    /// - If not, the PnL is calculated based on the direction of the position:
    ///   - For a Buy position:
    ///     - The PnL is calculated as the difference between the `current_value`
    ///       (based on the `market.bid` price or fallback value) and the original
    ///       `value` (based on the position's size and level).
    ///   - For a Sell position:
    ///     - The PnL is calculated as the difference between the original
    ///       `value` and the `current_value` (based on the `market.offer`
    ///       price or fallback value).
    ///
    /// # Assumptions
    /// - The `market.bid` and `market.offer` values are optional, so fallback
    ///   to the original position value is used if they are unavailable.
    /// - `self.position.direction` must be either `Direction::Buy` or
    ///   `Direction::Sell`.
    ///
    #[must_use]
    pub fn pnl(&self) -> f64 {
        if let Some(pnl) = self.pnl {
            pnl
        } else {
            match self.position.direction {
                Direction::Buy => {
                    let value = self.position.size * self.position.level;
                    let current_value = self.position.size * self.market.bid.unwrap_or(value);
                    current_value - value
                }
                Direction::Sell => {
                    let value = self.position.size * self.position.level;
                    let current_value = self.position.size * self.market.offer.unwrap_or(value);
                    value - current_value
                }
            }
        }
    }

    /// Updates the profit and loss (PnL) for the current position in the market.
    ///
    /// The method calculates the PnL based on the position's direction (Buy or Sell),
    /// size, level (entry price), and the current bid or offer price from the market data.
    /// The result is stored in the `pnl` field.
    ///
    /// # Calculation:
    /// - If the position is a Buy:
    ///     - Calculate the initial value of the position as `size * level`.
    ///     - Calculate the current value of the position using the current `bid` price from the market,
    ///       or use the initial value if the `bid` price is not available.
    ///     - PnL is the difference between the current value and the initial value.
    /// - If the position is a Sell:
    ///     - Calculate the initial value of the position as `size * level`.
    ///     - Calculate the current value of the position using the current `offer` price from the market,
    ///       or use the initial value if the `offer` price is not available.
    ///     - PnL is the difference between the initial value and the current value.
    ///
    /// # Fields Updated:
    /// - `self.pnl`: The calculated profit or loss is updated in this field. If no valid market price
    ///   (bid/offer) is available, `pnl` will be calculated based on the initial value.
    ///
    /// # Panics:
    /// This function does not explicitly panic but relies on the `unwrap_or` method to handle cases
    /// where the `bid` or `offer` is unavailable. It assumes that the market or position data are initialized correctly.
    ///
    pub fn update_pnl(&mut self) {
        let pnl = match self.position.direction {
            Direction::Buy => {
                let value = self.position.size * self.position.level;
                let current_value = self.position.size * self.market.bid.unwrap_or(value);
                current_value - value
            }
            Direction::Sell => {
                let value = self.position.size * self.position.level;
                let current_value = self.position.size * self.market.offer.unwrap_or(value);
                value - current_value
            }
        };
        self.pnl = Some(pnl);
    }
}

impl Position {
    /// Checks if the current financial instrument is a call option.
    ///
    /// A call option is a financial derivative that gives the holder the right (but not the obligation)
    /// to buy an underlying asset at a specified price within a specified time period. This method checks
    /// whether the instrument represented by this instance is a call option by inspecting the `instrument_name`
    /// field.
    ///
    /// # Returns
    ///
    /// * `true` if the instrument's name contains the substring `"CALL"`, indicating it is a call option.
    /// * `false` otherwise.
    ///
    #[must_use]
    #[inline]
    pub fn is_call(&self) -> bool {
        self.market.instrument_name.contains("CALL")
    }

    /// Checks if the financial instrument is a "PUT" option.
    ///
    /// This method examines the `instrument_name` field of the struct to determine
    /// if it contains the substring "PUT". If the substring is found, the method
    /// returns `true`, indicating that the instrument is categorized as a "PUT" option.
    /// Otherwise, it returns `false`.
    ///
    /// # Returns
    /// * `true` - If `instrument_name` contains the substring "PUT".
    /// * `false` - If `instrument_name` does not contain the substring "PUT".
    ///
    #[must_use]
    #[inline]
    pub fn is_put(&self) -> bool {
        self.market.instrument_name.contains("PUT")
    }
}

impl Add for Position {
    type Output = Position;

    /// Adds two positions together.
    ///
    /// # Invariants
    /// Both positions must belong to the same market (same EPIC).
    /// In debug builds, adding positions from different markets will panic.
    /// In release builds, the left-hand side market is used.
    fn add(self, other: Position) -> Position {
        debug_assert_eq!(
            self.market.epic, other.market.epic,
            "cannot add positions from different markets"
        );
        Position {
            position: self.position + other.position,
            market: self.market,
            pnl: match (self.pnl, other.pnl) {
                (Some(a), Some(b)) => Some(a + b),
                (Some(a), None) => Some(a),
                (None, Some(b)) => Some(b),
                (None, None) => None,
            },
        }
    }
}

/// Details of a position
#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
pub struct PositionDetails {
    /// Size of one contract
    #[serde(rename = "contractSize")]
    pub contract_size: f64,
    /// Date and time when the position was created
    #[serde(rename = "createdDate")]
    pub created_date: String,
    /// UTC date and time when the position was created
    #[serde(rename = "createdDateUTC")]
    pub created_date_utc: String,
    /// Unique identifier for the deal
    #[serde(rename = "dealId")]
    pub deal_id: String,
    /// Client-generated reference for the deal
    #[serde(rename = "dealReference")]
    pub deal_reference: String,
    /// Direction of the position (buy or sell)
    pub direction: Direction,
    /// Price level for take profit
    #[serde(rename = "limitLevel")]
    pub limit_level: Option<f64>,
    /// Opening price level of the position
    pub level: f64,
    /// Size/quantity of the position
    pub size: f64,
    /// Price level for stop loss
    #[serde(rename = "stopLevel")]
    pub stop_level: Option<f64>,
    /// Step size for trailing stop
    #[serde(rename = "trailingStep")]
    pub trailing_step: Option<f64>,
    /// Distance for trailing stop
    #[serde(rename = "trailingStopDistance")]
    pub trailing_stop_distance: Option<f64>,
    /// Currency of the position
    pub currency: String,
    /// Whether the position has controlled risk
    #[serde(rename = "controlledRisk")]
    pub controlled_risk: bool,
    /// Premium paid for limited risk
    #[serde(rename = "limitedRiskPremium")]
    pub limited_risk_premium: Option<f64>,
}

impl Add for PositionDetails {
    type Output = PositionDetails;

    fn add(self, other: PositionDetails) -> PositionDetails {
        let (contract_size, size) = if self.direction != other.direction {
            (
                (self.contract_size - other.contract_size).abs(),
                (self.size - other.size).abs(),
            )
        } else {
            (
                self.contract_size + other.contract_size,
                self.size + other.size,
            )
        };

        PositionDetails {
            contract_size,
            created_date: self.created_date,
            created_date_utc: self.created_date_utc,
            deal_id: self.deal_id,
            deal_reference: self.deal_reference,
            direction: self.direction,
            limit_level: other.limit_level.or(self.limit_level),
            level: (self.level + other.level) / 2.0, // Average level
            size,
            stop_level: other.stop_level.or(self.stop_level),
            trailing_step: other.trailing_step.or(self.trailing_step),
            trailing_stop_distance: other.trailing_stop_distance.or(self.trailing_stop_distance),
            currency: self.currency.clone(),
            controlled_risk: self.controlled_risk || other.controlled_risk,
            limited_risk_premium: other.limited_risk_premium.or(self.limited_risk_premium),
        }
    }
}

/// Market information for a position
#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
pub struct PositionMarket {
    /// Human-readable name of the instrument
    #[serde(rename = "instrumentName")]
    pub instrument_name: String,
    /// Expiry date of the instrument
    pub expiry: String,
    /// Unique identifier for the market
    pub epic: String,
    /// Type of the instrument
    #[serde(rename = "instrumentType")]
    pub instrument_type: String,
    /// Size of one lot
    #[serde(rename = "lotSize")]
    pub lot_size: f64,
    /// Highest price of the current trading session
    pub high: Option<f64>,
    /// Lowest price of the current trading session
    pub low: Option<f64>,
    /// Percentage change in price since previous close
    #[serde(rename = "percentageChange")]
    pub percentage_change: f64,
    /// Net change in price since previous close
    #[serde(rename = "netChange")]
    pub net_change: f64,
    /// Current bid price
    pub bid: Option<f64>,
    /// Current offer/ask price
    pub offer: Option<f64>,
    /// Time of the last price update
    #[serde(rename = "updateTime")]
    pub update_time: String,
    /// UTC time of the last price update
    #[serde(rename = "updateTimeUTC")]
    pub update_time_utc: String,
    /// Delay time in milliseconds for market data
    #[serde(rename = "delayTime")]
    pub delay_time: i64,
    /// Whether streaming prices are available for this market
    #[serde(rename = "streamingPricesAvailable")]
    pub streaming_prices_available: bool,
    /// Current status of the market (e.g., "OPEN", "CLOSED")
    #[serde(rename = "marketStatus")]
    pub market_status: String,
    /// Factor for scaling prices
    #[serde(rename = "scalingFactor")]
    pub scaling_factor: i64,
}

impl PositionMarket {
    /// Checks if the current financial instrument is a call option.
    ///
    /// A call option is a financial derivative that gives the holder the right (but not the obligation)
    /// to buy an underlying asset at a specified price within a specified time period. This method checks
    /// whether the instrument represented by this instance is a call option by inspecting the `instrument_name`
    /// field.
    ///
    /// # Returns
    ///
    /// * `true` if the instrument's name contains the substring `"CALL"`, indicating it is a call option.
    /// * `false` otherwise.
    ///
    pub fn is_call(&self) -> bool {
        self.instrument_name.contains("CALL")
    }

    /// Checks if the financial instrument is a "PUT" option.
    ///
    /// This method examines the `instrument_name` field of the struct to determine
    /// if it contains the substring "PUT". If the substring is found, the method
    /// returns `true`, indicating that the instrument is categorized as a "PUT" option.
    /// Otherwise, it returns `false`.
    ///
    /// # Returns
    /// * `true` - If `instrument_name` contains the substring "PUT".
    /// * `false` - If `instrument_name` does not contain the substring "PUT".
    ///
    pub fn is_put(&self) -> bool {
        self.instrument_name.contains("PUT")
    }
}

/// Working order
#[derive(DebugPretty, Clone, DisplaySimple, Deserialize, Serialize)]
pub struct WorkingOrder {
    /// Details of the working order
    #[serde(rename = "workingOrderData")]
    pub working_order_data: WorkingOrderData,
    /// Market information for the working order
    #[serde(rename = "marketData")]
    pub market_data: AccountMarketData,
}

/// Details of a working order
#[derive(DebugPretty, Clone, DisplaySimple, Deserialize, Serialize)]
pub struct WorkingOrderData {
    /// Unique identifier for the deal
    #[serde(rename = "dealId")]
    pub deal_id: String,
    /// Direction of the order (buy or sell)
    pub direction: Direction,
    /// Instrument EPIC identifier
    pub epic: String,
    /// Size/quantity of the order
    #[serde(rename = "orderSize")]
    pub order_size: f64,
    /// Price level for the order
    #[serde(rename = "orderLevel")]
    pub order_level: f64,
    /// Time in force for the order
    #[serde(rename = "timeInForce")]
    pub time_in_force: TimeInForce,
    /// Expiry date for GTD orders
    #[serde(rename = "goodTillDate")]
    pub good_till_date: Option<String>,
    /// ISO formatted expiry date for GTD orders
    #[serde(rename = "goodTillDateISO")]
    pub good_till_date_iso: Option<String>,
    /// Date and time when the order was created
    #[serde(rename = "createdDate")]
    pub created_date: String,
    /// UTC date and time when the order was created
    #[serde(rename = "createdDateUTC")]
    pub created_date_utc: String,
    /// Whether the order has a guaranteed stop
    #[serde(rename = "guaranteedStop")]
    pub guaranteed_stop: bool,
    /// Type of the order
    #[serde(rename = "orderType")]
    pub order_type: OrderType,
    /// Distance for stop loss
    #[serde(rename = "stopDistance")]
    pub stop_distance: Option<f64>,
    /// Distance for take profit
    #[serde(rename = "limitDistance")]
    pub limit_distance: Option<f64>,
    /// Currency code for the order
    #[serde(rename = "currencyCode")]
    pub currency_code: String,
    /// Whether direct market access is enabled
    pub dma: bool,
    /// Premium for limited risk
    #[serde(rename = "limitedRiskPremium")]
    pub limited_risk_premium: Option<f64>,
    /// Price level for take profit
    #[serde(rename = "limitLevel", default)]
    pub limit_level: Option<f64>,
    /// Price level for stop loss
    #[serde(rename = "stopLevel", default)]
    pub stop_level: Option<f64>,
    /// Client-generated reference for the deal
    #[serde(rename = "dealReference", default)]
    pub deal_reference: Option<String>,
}

/// Market data for a working order
#[derive(DebugPretty, Clone, DisplaySimple, Deserialize, Serialize)]
pub struct AccountMarketData {
    /// Human-readable name of the instrument
    #[serde(rename = "instrumentName")]
    pub instrument_name: String,
    /// Exchange identifier
    #[serde(rename = "exchangeId")]
    pub exchange_id: String,
    /// Expiry date of the instrument
    pub expiry: String,
    /// Current status of the market
    #[serde(rename = "marketStatus")]
    pub market_status: MarketState,
    /// Unique identifier for the market
    pub epic: String,
    /// Type of the instrument
    #[serde(rename = "instrumentType")]
    pub instrument_type: InstrumentType,
    /// Size of one lot
    #[serde(rename = "lotSize")]
    pub lot_size: f64,
    /// Highest price of the current trading session
    pub high: Option<f64>,
    /// Lowest price of the current trading session
    pub low: Option<f64>,
    /// Percentage change in price since previous close
    #[serde(rename = "percentageChange")]
    pub percentage_change: f64,
    /// Net change in price since previous close
    #[serde(rename = "netChange")]
    pub net_change: f64,
    /// Current bid price
    pub bid: Option<f64>,
    /// Current offer/ask price
    pub offer: Option<f64>,
    /// Time of the last price update
    #[serde(rename = "updateTime")]
    pub update_time: String,
    /// UTC time of the last price update
    #[serde(rename = "updateTimeUTC")]
    pub update_time_utc: String,
    /// Delay time in milliseconds for market data
    #[serde(rename = "delayTime")]
    pub delay_time: i64,
    /// Whether streaming prices are available for this market
    #[serde(rename = "streamingPricesAvailable")]
    pub streaming_prices_available: bool,
    /// Factor for scaling prices
    #[serde(rename = "scalingFactor")]
    pub scaling_factor: i64,
}

impl AccountMarketData {
    /// Checks if the current financial instrument is a call option.
    ///
    /// A call option is a financial derivative that gives the holder the right (but not the obligation)
    /// to buy an underlying asset at a specified price within a specified time period. This method checks
    /// whether the instrument represented by this instance is a call option by inspecting the `instrument_name`
    /// field.
    ///
    /// # Returns
    ///
    /// * `true` if the instrument's name contains the substring `"CALL"`, indicating it is a call option.
    /// * `false` otherwise.
    ///
    pub fn is_call(&self) -> bool {
        self.instrument_name.contains("CALL")
    }

    /// Checks if the financial instrument is a "PUT" option.
    ///
    /// This method examines the `instrument_name` field of the struct to determine
    /// if it contains the substring "PUT". If the substring is found, the method
    /// returns `true`, indicating that the instrument is categorized as a "PUT" option.
    /// Otherwise, it returns `false`.
    ///
    /// # Returns
    /// * `true` - If `instrument_name` contains the substring "PUT".
    /// * `false` - If `instrument_name` does not contain the substring "PUT".
    ///
    pub fn is_put(&self) -> bool {
        self.instrument_name.contains("PUT")
    }
}

/// Transaction metadata
#[derive(DebugPretty, Clone, DisplaySimple, Deserialize, Serialize)]
pub struct TransactionMetadata {
    /// Pagination information
    #[serde(rename = "pageData")]
    pub page_data: PageData,
    /// Total number of transactions
    pub size: i32,
}

/// Pagination information
#[derive(DebugPretty, Clone, DisplaySimple, Deserialize, Serialize)]
pub struct PageData {
    /// Current page number
    #[serde(rename = "pageNumber")]
    pub page_number: i32,
    /// Number of items per page
    #[serde(rename = "pageSize")]
    pub page_size: i32,
    /// Total number of pages
    #[serde(rename = "totalPages")]
    pub total_pages: i32,
}

/// Individual transaction
#[derive(DebugPretty, DisplaySimple, Clone, Deserialize, Serialize)]
pub struct AccountTransaction {
    /// Date and time of the transaction
    pub date: String,
    /// UTC date and time of the transaction
    #[serde(rename = "dateUtc")]
    pub date_utc: String,
    /// Represents the date and time in UTC when an event or entity was opened or initiated.
    #[serde(rename = "openDateUtc")]
    pub open_date_utc: String,
    /// Name of the instrument
    #[serde(rename = "instrumentName")]
    pub instrument_name: String,
    /// Time period of the transaction
    pub period: String,
    /// Profit or loss amount
    #[serde(rename = "profitAndLoss")]
    pub profit_and_loss: String,
    /// Type of transaction
    #[serde(rename = "transactionType")]
    pub transaction_type: String,
    /// Reference identifier for the transaction
    pub reference: String,
    /// Opening price level
    #[serde(rename = "openLevel")]
    pub open_level: String,
    /// Closing price level
    #[serde(rename = "closeLevel")]
    pub close_level: String,
    /// Size/quantity of the transaction
    pub size: String,
    /// Currency of the transaction
    pub currency: String,
    /// Whether this is a cash transaction
    #[serde(rename = "cashTransaction")]
    pub cash_transaction: bool,
}

impl AccountTransaction {
    /// Checks if the current financial instrument is a call option.
    ///
    /// A call option is a financial derivative that gives the holder the right (but not the obligation)
    /// to buy an underlying asset at a specified price within a specified time period. This method checks
    /// whether the instrument represented by this instance is a call option by inspecting the `instrument_name`
    /// field.
    ///
    /// # Returns
    ///
    /// * `true` if the instrument's name contains the substring `"CALL"`, indicating it is a call option.
    /// * `false` otherwise.
    ///
    pub fn is_call(&self) -> bool {
        self.instrument_name.contains("CALL")
    }

    /// Checks if the financial instrument is a "PUT" option.
    ///
    /// This method examines the `instrument_name` field of the struct to determine
    /// if it contains the substring "PUT". If the substring is found, the method
    /// returns `true`, indicating that the instrument is categorized as a "PUT" option.
    /// Otherwise, it returns `false`.
    ///
    /// # Returns
    /// * `true` - If `instrument_name` contains the substring "PUT".
    /// * `false` - If `instrument_name` does not contain the substring "PUT".
    ///
    pub fn is_put(&self) -> bool {
        self.instrument_name.contains("PUT")
    }
}

/// Representation of account data received from the IG Markets streaming API
#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize, Default)]
pub struct AccountData {
    /// Name of the item this data belongs to
    pub item_name: String,
    /// Position of the item in the subscription
    pub item_pos: i32,
    /// All account fields
    pub fields: AccountFields,
    /// Fields that have changed in this update
    pub changed_fields: AccountFields,
    /// Whether this is a snapshot or an update
    pub is_snapshot: bool,
}

/// Fields containing account financial information
#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize, Default)]
pub struct AccountFields {
    #[serde(rename = "PNL")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pnl: Option<f64>,

    #[serde(rename = "DEPOSIT")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    deposit: Option<f64>,

    #[serde(rename = "AVAILABLE_CASH")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    available_cash: Option<f64>,

    #[serde(rename = "PNL_LR")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pnl_lr: Option<f64>,

    #[serde(rename = "PNL_NLR")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pnl_nlr: Option<f64>,

    #[serde(rename = "FUNDS")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    funds: Option<f64>,

    #[serde(rename = "MARGIN")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    margin: Option<f64>,

    #[serde(rename = "MARGIN_LR")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    margin_lr: Option<f64>,

    #[serde(rename = "MARGIN_NLR")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    margin_nlr: Option<f64>,

    #[serde(rename = "AVAILABLE_TO_DEAL")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    available_to_deal: Option<f64>,

    #[serde(rename = "EQUITY")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    equity: Option<f64>,

    #[serde(rename = "EQUITY_USED")]
    #[serde(with = "string_as_float_opt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    equity_used: Option<f64>,
}

impl AccountData {
    /// Converts an ItemUpdate from the Lightstreamer API to an AccountData object
    ///
    /// # Arguments
    /// * `item_update` - The ItemUpdate received from the Lightstreamer API
    ///
    /// # Returns
    /// * `Result<Self, String>` - The converted AccountData or an error message
    pub fn from_item_update(item_update: &ItemUpdate) -> Result<Self, String> {
        // Extract the item_name, defaulting to an empty string if None
        let item_name = item_update.item_name.clone().unwrap_or_default();

        // Convert item_pos from usize to i32
        let item_pos = item_update.item_pos as i32;

        // Extract is_snapshot
        let is_snapshot = item_update.is_snapshot;

        // Convert fields
        let fields = Self::create_account_fields(&item_update.fields)?;

        // Convert changed_fields by first creating a HashMap<String, Option<String>>
        let mut changed_fields_map: HashMap<String, Option<String>> = HashMap::new();
        for (key, value) in &item_update.changed_fields {
            changed_fields_map.insert(key.clone(), Some(value.clone()));
        }
        let changed_fields = Self::create_account_fields(&changed_fields_map)?;

        Ok(AccountData {
            item_name,
            item_pos,
            fields,
            changed_fields,
            is_snapshot,
        })
    }

    /// Helper method to create AccountFields from a HashMap of field values
    ///
    /// # Arguments
    /// * `fields_map` - HashMap containing field names and their string values
    ///
    /// # Returns
    /// * `Result<AccountFields, String>` - The parsed AccountFields or an error message
    fn create_account_fields(
        fields_map: &HashMap<String, Option<String>>,
    ) -> Result<AccountFields, String> {
        // Helper function to safely get a field value
        let get_field = |key: &str| -> Option<String> { fields_map.get(key).cloned().flatten() };

        // Helper function to parse float values
        let parse_float = |key: &str| -> Result<Option<f64>, String> {
            match get_field(key) {
                Some(val) if !val.is_empty() => val
                    .parse::<f64>()
                    .map(Some)
                    .map_err(|_| format!("Failed to parse {key} as float: {val}")),
                _ => Ok(None),
            }
        };

        Ok(AccountFields {
            pnl: parse_float("PNL")?,
            deposit: parse_float("DEPOSIT")?,
            available_cash: parse_float("AVAILABLE_CASH")?,
            pnl_lr: parse_float("PNL_LR")?,
            pnl_nlr: parse_float("PNL_NLR")?,
            funds: parse_float("FUNDS")?,
            margin: parse_float("MARGIN")?,
            margin_lr: parse_float("MARGIN_LR")?,
            margin_nlr: parse_float("MARGIN_NLR")?,
            available_to_deal: parse_float("AVAILABLE_TO_DEAL")?,
            equity: parse_float("EQUITY")?,
            equity_used: parse_float("EQUITY_USED")?,
        })
    }
}

impl From<&ItemUpdate> for AccountData {
    fn from(item_update: &ItemUpdate) -> Self {
        Self::from_item_update(item_update).unwrap_or_else(|_| AccountData::default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::presentation::order::Direction;

    fn sample_position_details(direction: Direction, level: f64, size: f64) -> PositionDetails {
        PositionDetails {
            contract_size: 1.0,
            created_date: "2025/10/30 18:13:53:000".to_string(),
            created_date_utc: "2025-10-30T17:13:53".to_string(),
            deal_id: "DIAAAAVJNQPWZAG".to_string(),
            deal_reference: "RZ0RQ1K8V1S1JN2".to_string(),
            direction,
            limit_level: None,
            level,
            size,
            stop_level: None,
            trailing_step: None,
            trailing_stop_distance: None,
            currency: "USD".to_string(),
            controlled_risk: false,
            limited_risk_premium: None,
        }
    }

    fn sample_market(bid: Option<f64>, offer: Option<f64>) -> PositionMarket {
        PositionMarket {
            instrument_name: "US 500 6910 PUT ($1)".to_string(),
            expiry: "DEC-25".to_string(),
            epic: "OP.D.OTCSPX3.6910P.IP".to_string(),
            instrument_type: "UNKNOWN".to_string(),
            lot_size: 1.0,
            high: Some(153.43),
            low: Some(147.42),
            percentage_change: 0.61,
            net_change: 6895.38,
            bid,
            offer,
            update_time: "05:55:59".to_string(),
            update_time_utc: "05:55:59".to_string(),
            delay_time: 0,
            streaming_prices_available: true,
            market_status: "TRADEABLE".to_string(),
            scaling_factor: 1,
        }
    }

    #[test]
    fn pnl_sell_uses_offer_and_matches_sample_data() {
        // Given the provided sample data (SELL):
        // size = 1.0, level = 155.14, offer = 152.82
        // value = 155.14, current_value = 152.82 => pnl = 155.14 - 152.82 = 2.32
        let details = sample_position_details(Direction::Sell, 155.14, 1.0);
        let market = sample_market(Some(151.32), Some(152.82));
        let position = Position {
            position: details,
            market,
            pnl: None,
        };

        let pnl = position.pnl();
        assert!((pnl - 2.32).abs() < 1e-9, "expected 2.32, got {}", pnl);
    }

    #[test]
    fn pnl_buy_uses_bid_and_computes_difference() {
        // For BUY: pnl = current_value - value
        // Using size = 1.0, level = 155.14, bid = 151.32 => pnl = 151.32 - 155.14 = -3.82
        let details = sample_position_details(Direction::Buy, 155.14, 1.0);
        let market = sample_market(Some(151.32), Some(152.82));
        let position = Position {
            position: details,
            market,
            pnl: None,
        };

        let pnl = position.pnl();
        assert!((pnl + 3.82).abs() < 1e-9, "expected -3.82, got {}", pnl);
    }

    #[test]
    fn pnl_field_overrides_calculation_when_present() {
        let details = sample_position_details(Direction::Sell, 155.14, 1.0);
        let market = sample_market(Some(151.32), Some(152.82));
        // Set explicit pnl different from calculated (which would be 2.32)
        let position = Position {
            position: details,
            market,
            pnl: Some(10.0),
        };
        assert_eq!(position.pnl(), 10.0);
    }

    #[test]
    fn pnl_sell_is_zero_when_offer_missing() {
        // When offer is missing for SELL, unwrap_or(value) makes current_value == value => pnl = 0
        let details = sample_position_details(Direction::Sell, 155.14, 1.0);
        let market = sample_market(Some(151.32), None);
        let position = Position {
            position: details,
            market,
            pnl: None,
        };
        assert!((position.pnl() - 0.0).abs() < 1e-12);
    }

    #[test]
    fn pnl_buy_is_zero_when_bid_missing() {
        // When bid is missing for BUY, unwrap_or(value) makes current_value == value => pnl = 0
        let details = sample_position_details(Direction::Buy, 155.14, 1.0);
        let market = sample_market(None, Some(152.82));
        let position = Position {
            position: details,
            market,
            pnl: None,
        };
        assert!((position.pnl() - 0.0).abs() < 1e-12);
    }
}