lnm-sdk 0.4.2

Rust SDK for interacting with LN Markets.
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
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
use std::fmt;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::shared::models::{
    leverage::Leverage,
    margin::Margin,
    price::Price,
    quantity::Quantity,
    serde_util,
    trade::{TradeExecution, TradeExecutionType, TradeSide, TradeSize},
};

use super::{
    client_id::ClientId, cross_leverage::CrossLeverage,
    error::FuturesIsolatedTradeRequestValidationError,
};

#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(in crate::api_v3) struct FuturesIsolatedTradeRequestBody {
    leverage: Leverage,
    side: TradeSide,
    #[serde(skip_serializing_if = "Option::is_none")]
    stoploss: Option<Price>,
    #[serde(skip_serializing_if = "Option::is_none")]
    takeprofit: Option<Price>,
    #[serde(skip_serializing_if = "Option::is_none")]
    client_id: Option<ClientId>,
    #[serde(flatten)]
    size: TradeSize,
    #[serde(rename = "type")]
    trade_type: TradeExecutionType,
    #[serde(skip_serializing_if = "Option::is_none")]
    price: Option<Price>,
}

impl FuturesIsolatedTradeRequestBody {
    pub fn new(
        leverage: Leverage,
        stoploss: Option<Price>,
        takeprofit: Option<Price>,
        side: TradeSide,
        client_id: Option<ClientId>,
        size: TradeSize,
        trade_execution: TradeExecution,
    ) -> Result<Self, FuturesIsolatedTradeRequestValidationError> {
        if let TradeExecution::Limit(price) = trade_execution {
            if let TradeSize::Margin(margin) = &size {
                // Implied `Quantity` must be valid
                let _ = Quantity::try_calculate(*margin, price, leverage)?;
            }

            if let Some(stoploss) = stoploss
                && stoploss >= price
            {
                return Err(FuturesIsolatedTradeRequestValidationError::StopLossHigherThanPrice);
            }

            if let Some(takeprofit) = takeprofit
                && takeprofit <= price
            {
                return Err(FuturesIsolatedTradeRequestValidationError::TakeProfitLowerThanPrice);
            }
        }

        let (trade_type, price) = match trade_execution {
            TradeExecution::Market => (TradeExecutionType::Market, None),
            TradeExecution::Limit(price) => (TradeExecutionType::Limit, Some(price)),
        };

        Ok(FuturesIsolatedTradeRequestBody {
            leverage,
            stoploss,
            takeprofit,
            side,
            client_id,
            size,
            trade_type,
            price,
        })
    }
}

/// An isolated futures trade returned from the LN Markets API.
///
/// Represents a complete isolated trade object with all associated data including execution
/// details, risk parameters, lifecycle status, and profit/loss information. Unlike cross-margin
/// positions, each isolated trade has its own dedicated margin and risk parameters.
///
/// # Examples
///
/// ```no_run
/// # async fn example(rest: lnm_sdk::api_v3::RestClient) -> Result<(), Box<dyn std::error::Error>> {
/// use lnm_sdk::api_v3::models::{
///     Leverage, Margin, Trade, TradeExecution, TradeSide, TradeSize,
/// };
///
/// let trade: Trade = rest
///     .futures_isolated
///     .new_trade(
///         TradeSide::Buy,
///         TradeSize::from(Margin::try_from(10_000)?),
///         Leverage::try_from(10.0)?,
///         TradeExecution::Market,
///         None,
///         None,
///         None,
///     )
///     .await?;
///
/// println!("Trade ID: {}", trade.id());
/// println!("Side: {:?}", trade.side());
/// println!("Quantity: {}", trade.quantity());
/// println!("Margin: {}", trade.margin());
/// println!("Leverage: {}", trade.leverage());
/// # Ok(())
/// # }
/// ```
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Trade {
    id: Uuid,
    #[serde(rename = "type")]
    trade_type: TradeExecutionType,
    side: TradeSide,
    opening_fee: u64,
    closing_fee: u64,
    maintenance_margin: i64,
    quantity: Quantity,
    margin: Margin,
    leverage: Leverage,
    price: Price,
    liquidation: Price,
    #[serde(with = "serde_util::price_option")]
    stoploss: Option<Price>,
    #[serde(with = "serde_util::price_option")]
    takeprofit: Option<Price>,
    #[serde(with = "serde_util::price_option")]
    exit_price: Option<Price>,
    pl: i64,
    created_at: DateTime<Utc>,
    filled_at: Option<DateTime<Utc>>,
    closed_at: Option<DateTime<Utc>>,
    #[serde(with = "serde_util::price_option")]
    entry_price: Option<Price>,
    entry_margin: Option<Margin>,
    open: bool,
    running: bool,
    canceled: bool,
    closed: bool,
    sum_funding_fees: i64,
    #[serde(with = "serde_util::client_id_option")]
    client_id: Option<ClientId>,
}

impl Trade {
    /// Returns the unique identifier for this trade.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let trade_id = trade.id();
    ///
    /// println!("Trade ID: {}", trade_id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn id(&self) -> Uuid {
        self.id
    }

    /// Returns the execution type (Market or Limit).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let exec_type = trade.trade_type();
    ///
    /// println!("Trade execution type: {:?}", exec_type);
    /// # Ok(())
    /// # }
    /// ```
    pub fn trade_type(&self) -> TradeExecutionType {
        self.trade_type
    }

    /// Returns the side of the trade (Buy or Sell).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let side = trade.side();
    ///
    /// println!("Trade side: {:?}", side);
    /// # Ok(())
    /// # }
    /// ```
    pub fn side(&self) -> TradeSide {
        self.side
    }

    /// Returns the opening fee charged when the trade was filled (in satoshis), or zero if the
    /// trade was not filled.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let fee = trade.opening_fee();
    ///
    /// println!("Opening fee: {} sats", fee);
    /// # Ok(())
    /// # }
    /// ```
    pub fn opening_fee(&self) -> u64 {
        self.opening_fee
    }

    /// Returns the closing fee that was charged when the trade was closed (in satoshis), or zero
    /// if the trade was not closed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let fee = trade.closing_fee();
    ///
    /// println!("Closing fee: {} sats", fee);
    /// # Ok(())
    /// # }
    /// ```
    pub fn closing_fee(&self) -> u64 {
        self.closing_fee
    }

    /// Returns the maintenance margin requirement (in satoshis).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let margin = trade.maintenance_margin();
    ///
    /// println!("Maintenance margin: {} sats", margin);
    /// # Ok(())
    /// # }
    /// ```
    pub fn maintenance_margin(&self) -> i64 {
        self.maintenance_margin
    }

    /// Returns the quantity (notional value in USD) of the trade.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let quantity = trade.quantity();
    ///
    /// println!("Trade quantity: {}", quantity);
    /// # Ok(())
    /// # }
    /// ```
    pub fn quantity(&self) -> Quantity {
        self.quantity
    }

    /// Returns the margin (collateral in satoshis) allocated to the trade.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let margin = trade.margin();
    ///
    /// println!("Trade margin: {}", margin);
    /// # Ok(())
    /// # }
    /// ```
    pub fn margin(&self) -> Margin {
        self.margin
    }

    /// Returns the leverage multiplier applied to the trade.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let leverage = trade.leverage();
    ///
    /// println!("Trade leverage: {}", leverage);
    /// # Ok(())
    /// # }
    /// ```
    pub fn leverage(&self) -> Leverage {
        self.leverage
    }

    /// Returns the trade price.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let price = trade.price();
    ///
    /// println!("Trade price: {}", price);
    /// # Ok(())
    /// # }
    /// ```
    pub fn price(&self) -> Price {
        self.price
    }

    /// Returns the liquidation price at which the position will be automatically closed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let liq_price = trade.liquidation();
    ///
    /// println!("Liquidation price: {}", liq_price);
    /// # Ok(())
    /// # }
    /// ```
    pub fn liquidation(&self) -> Price {
        self.liquidation
    }

    /// Returns the stop loss price, if set.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(sl) = trade.stoploss() {
    ///     println!("Stop loss: {}", sl);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn stoploss(&self) -> Option<Price> {
        self.stoploss
    }

    /// Returns the take profit price, if set.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(tp) = trade.takeprofit() {
    ///     println!("Take profit: {}", tp);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn takeprofit(&self) -> Option<Price> {
        self.takeprofit
    }

    /// Returns the price at which the trade was closed, if applicable.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(exit) = trade.exit_price() {
    ///     println!("Exit price: {}", exit);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn exit_price(&self) -> Option<Price> {
        self.exit_price
    }

    /// Returns the realized profit/loss in satoshis.
    ///
    /// For running trades, this represents the current unrealized P/L. For closed trades, this is
    /// the final realized P/L.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let pl = trade.pl();
    ///
    /// if pl > 0 {
    ///     println!("Profit: {} sats", pl);
    /// } else {
    ///     println!("Loss: {} sats", pl.abs());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn pl(&self) -> i64 {
        self.pl
    }

    /// Returns the timestamp when the trade was created.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let created_at = trade.created_at();
    ///
    /// println!("Trade created at: {}", created_at);
    /// # Ok(())
    /// # }
    /// ```
    pub fn created_at(&self) -> DateTime<Utc> {
        self.created_at
    }

    /// Returns the timestamp when the trade was filled, if applicable.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(filled_at) = trade.filled_at() {
    ///     println!("Trade filled at: {}", filled_at);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn filled_at(&self) -> Option<DateTime<Utc>> {
        self.filled_at
    }

    /// Returns the timestamp when the trade was closed, if applicable.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(closed_at) = trade.closed_at() {
    ///     println!("Trade closed at: {}", closed_at);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn closed_at(&self) -> Option<DateTime<Utc>> {
        self.closed_at
    }

    /// Returns the actual entry price when the trade was filled.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(entry) = trade.entry_price() {
    ///     println!("Entry price: {}", entry);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn entry_price(&self) -> Option<Price> {
        self.entry_price
    }

    /// Returns the actual margin at entry, which may differ from the requested margin.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(entry_margin) = trade.entry_margin() {
    ///     println!("Entry margin: {}", entry_margin);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn entry_margin(&self) -> Option<Margin> {
        self.entry_margin
    }

    /// Returns `true` if the trade is open (limit order not yet filled).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if trade.open() {
    ///     println!("Trade is open (limit order not filled)");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn open(&self) -> bool {
        self.open
    }

    /// Returns `true` if the trade is currently running (filled and active).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if trade.running() {
    ///     println!("Trade is actively running");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn running(&self) -> bool {
        self.running
    }

    /// Returns `true` if the trade was canceled before being filled.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if trade.canceled() {
    ///     println!("Trade was canceled");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn canceled(&self) -> bool {
        self.canceled
    }

    /// Returns `true` if the trade has been closed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if trade.closed() {
    ///     println!("Trade has been closed");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn closed(&self) -> bool {
        self.closed
    }

    /// Returns the sum of all funding fees paid on this trade in satoshis.
    ///
    /// Funding fees are periodic payments charged on open orders.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// let total_fees = trade.sum_funding_fees();
    ///
    /// println!("Total funding fees paid: {} sats", total_fees);
    /// # Ok(())
    /// # }
    /// ```
    pub fn sum_funding_fees(&self) -> i64 {
        self.sum_funding_fees
    }

    /// Returns the client-provided identifier for this trade.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::api_v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(client_id) = trade.client_id() {
    ///     println!("Client ID: {}", client_id);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn client_id(&self) -> Option<&ClientId> {
        self.client_id.as_ref()
    }

    pub fn as_data_str(&self) -> String {
        let mut data_str = format!(
            "id: {}\nside: {}\nopen: {}\nrunning: {}\ncanceled: {}\nclosed: {}\nquantity: {}\nmargin: {}\nleverage: {}\nprice: {}\nliquidation: {}\npl: {}\ncreated_at: {}",
            self.id,
            self.side,
            self.open,
            self.running,
            self.canceled,
            self.closed,
            self.quantity,
            self.margin,
            self.leverage,
            self.price,
            self.liquidation,
            self.pl,
            self.created_at.to_rfc3339()
        );

        if let Some(entry_price) = self.entry_price {
            data_str.push_str(&format!("\nentry_price: {entry_price}"));
        }
        if let Some(exit_price) = self.exit_price {
            data_str.push_str(&format!("\nexit_price: {exit_price}"));
        }
        if let Some(stoploss) = self.stoploss {
            data_str.push_str(&format!("\nstoploss: {stoploss}"));
        }
        if let Some(takeprofit) = self.takeprofit {
            data_str.push_str(&format!("\ntakeprofit: {takeprofit}"));
        }
        if let Some(client_id) = &self.client_id {
            data_str.push_str(&format!("\nclient_id: {client_id}"));
        }

        data_str
    }
}

impl fmt::Display for Trade {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Trade:")?;
        for line in self.as_data_str().lines() {
            write!(f, "\n  {line}")?;
        }
        Ok(())
    }
}

#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(in crate::api_v3) struct FuturesCrossOrderBody {
    side: TradeSide,
    quantity: Quantity,
    #[serde(rename = "type")]
    trade_type: TradeExecutionType,
    #[serde(skip_serializing_if = "Option::is_none")]
    price: Option<Price>,
    #[serde(skip_serializing_if = "Option::is_none")]
    client_id: Option<ClientId>,
}

impl FuturesCrossOrderBody {
    pub fn new(
        side: TradeSide,
        quantity: Quantity,
        execution: TradeExecution,
        client_id: Option<ClientId>,
    ) -> Self {
        let (trade_type, price) = match execution {
            TradeExecution::Market => (TradeExecutionType::Market, None),
            TradeExecution::Limit(price) => (TradeExecutionType::Limit, Some(price)),
        };

        Self {
            side,
            quantity,
            trade_type,
            price,
            client_id,
        }
    }
}

/// An order to modify a cross-margin futures position returned from the LN Markets API.
///
/// Represents an order that, when filled, will update the user's [`CrossPosition`]. Cross orders
/// allow traders to increase or decrease their position size within a unified cross-margin account,
/// where margin is shared across all positions.
///
/// # Examples
///
/// ```no_run
/// # async fn example(rest: lnm_sdk::api_v3::RestClient) -> Result<(), Box<dyn std::error::Error>> {
/// use lnm_sdk::api_v3::models::{
///     CrossOrder, Quantity, TradeExecution, TradeSide,
/// };
///
/// let order: CrossOrder = rest
///     .futures_cross
///     .place_order(
///         TradeSide::Buy,
///         Quantity::try_from(1000)?,
///         TradeExecution::Market,
///         None,
///     )
///     .await?;
///
/// println!("Order ID: {}", order.id());
/// println!("Side: {:?}", order.side());
/// println!("Quantity: {}", order.quantity());
/// println!("Status - Open: {}, Filled: {}", order.open(), order.filled());
/// # Ok(())
/// # }
/// ```
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CrossOrder {
    id: Uuid,
    #[serde(rename = "type")]
    trade_type: TradeExecutionType,
    side: TradeSide,
    quantity: Quantity,
    price: Price,
    trading_fee: u64,
    created_at: DateTime<Utc>,
    filled_at: Option<DateTime<Utc>>,
    canceled_at: Option<DateTime<Utc>>,
    open: bool,
    filled: bool,
    canceled: bool,
    #[serde(with = "serde_util::client_id_option")]
    client_id: Option<ClientId>,
}

impl CrossOrder {
    /// Returns the unique identifier for this cross order.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// let order_id = order.id();
    ///
    /// println!("Order ID: {}", order_id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn id(&self) -> Uuid {
        self.id
    }

    /// Returns the execution type (Market or Limit).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// let exec_type = order.trade_type();
    ///
    /// println!("Order execution type: {:?}", exec_type);
    /// # Ok(())
    /// # }
    /// ```
    pub fn trade_type(&self) -> TradeExecutionType {
        self.trade_type
    }

    /// Returns the side of the order (Buy or Sell).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// let side = order.side();
    ///
    /// println!("Order side: {:?}", side);
    /// # Ok(())
    /// # }
    /// ```
    pub fn side(&self) -> TradeSide {
        self.side
    }

    /// Returns the quantity (notional value in USD) of the order.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// let quantity = order.quantity();
    ///
    /// println!("Order quantity: {}", quantity);
    /// # Ok(())
    /// # }
    /// ```
    pub fn quantity(&self) -> Quantity {
        self.quantity
    }

    /// Returns the order price.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// let price = order.price();
    ///
    /// println!("Order price: {}", price);
    /// # Ok(())
    /// # }
    /// ```
    pub fn price(&self) -> Price {
        self.price
    }

    /// Returns the trading fee charged (in satoshis).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// let fee = order.trading_fee();
    ///
    /// println!("Trading fee: {} sats", fee);
    /// # Ok(())
    /// # }
    /// ```
    pub fn trading_fee(&self) -> u64 {
        self.trading_fee
    }

    /// Returns the timestamp when the order was created.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// let created_at = order.created_at();
    ///
    /// println!("Order created at: {}", created_at);
    /// # Ok(())
    /// # }
    /// ```
    pub fn created_at(&self) -> DateTime<Utc> {
        self.created_at
    }

    /// Returns the timestamp when the order was filled, if applicable.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(filled_at) = order.filled_at() {
    ///     println!("Order filled at: {}", filled_at);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn filled_at(&self) -> Option<DateTime<Utc>> {
        self.filled_at
    }

    /// Returns the timestamp when the order was canceled, if applicable.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(canceled_at) = order.canceled_at() {
    ///     println!("Order canceled at: {}", canceled_at);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn canceled_at(&self) -> Option<DateTime<Utc>> {
        self.canceled_at
    }

    /// Returns `true` if the order is open (limit order not yet filled).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// if order.open() {
    ///     println!("Order is open (limit order not filled)");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn open(&self) -> bool {
        self.open
    }

    /// Returns `true` if the order has been filled.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// if order.filled() {
    ///     println!("Order has been filled");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn filled(&self) -> bool {
        self.filled
    }

    /// Returns `true` if the order was canceled before being filled.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// if order.canceled() {
    ///     println!("Order was canceled");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn canceled(&self) -> bool {
        self.canceled
    }

    /// Returns the client-provided identifier for this order.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(order: lnm_sdk::api_v3::models::CrossOrder) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(client_id) = order.client_id() {
    ///     println!("Client ID: {}", client_id);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn client_id(&self) -> Option<&ClientId> {
        self.client_id.as_ref()
    }

    pub fn as_data_str(&self) -> String {
        let mut result = format!(
            "id: {}\nside: {}\nopen: {}\nfilled: {}\ncanceled: {}\nquantity: {}\nprice: {}\ntrading_fee: {}\ncreated_at: {}",
            self.id,
            self.side,
            self.open,
            self.filled,
            self.canceled,
            self.quantity,
            self.price,
            self.trading_fee,
            self.created_at.to_rfc3339()
        );

        if let Some(filled_at) = self.filled_at {
            result.push_str(&format!("\nfilled_at: {}", filled_at.to_rfc3339()));
        }
        if let Some(canceled_at) = self.canceled_at {
            result.push_str(&format!("\ncanceled_at: {}", canceled_at.to_rfc3339()));
        }
        if let Some(client_id) = &self.client_id {
            result.push_str(&format!("\nclient_id: {}", client_id));
        }

        result
    }
}

impl fmt::Display for CrossOrder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Cross Order:")?;
        for line in self.as_data_str().lines() {
            write!(f, "\n  {line}")?;
        }
        Ok(())
    }
}

/// A cross-margin futures position returned from the LN Markets API.
///
/// Represents a user's aggregated cross-margin position where margin is shared across the entire
/// account rather than allocated per trade.
///
/// Cross positions are modified through [`CrossOrder`]s.
///
/// # Examples
///
/// ```no_run
/// # async fn example(rest: lnm_sdk::api_v3::RestClient) -> Result<(), Box<dyn std::error::Error>> {
/// use lnm_sdk::api_v3::models::CrossPosition;
///
/// let position: CrossPosition = rest
///     .futures_cross
///     .get_position()
///     .await?;
///
/// println!("Position ID: {}", position.id());
/// println!("Quantity: {}", position.quantity());
/// println!("Margin: {}", position.margin());
/// println!("Leverage: {}", position.leverage());
/// if let Some(entry_price) = position.entry_price() {
///     println!("Entry price: {}", entry_price);
/// }
/// println!("Total P/L: {} sats", position.total_pl());
/// # Ok(())
/// # }
/// ```
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CrossPosition {
    id: Uuid,
    margin: u64,
    quantity: i64,
    leverage: CrossLeverage,
    entry_price: Option<Price>,
    running_margin: u64,
    initial_margin: u64,
    maintenance_margin: u64,
    liquidation: Option<Price>,
    trading_fees: u64,
    funding_fees: u64,
    total_pl: i64,
    delta_pl: i64,
}

impl CrossPosition {
    /// Returns the unique identifier for this cross position.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let position_id = position.id();
    ///
    /// println!("Position ID: {}", position_id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn id(&self) -> Uuid {
        self.id
    }

    /// Returns the margin (collateral in satoshis) allocated to the position.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let margin = position.margin();
    ///
    /// println!("Position margin: {}", margin);
    /// # Ok(())
    /// # }
    /// ```
    pub fn margin(&self) -> u64 {
        self.margin
    }

    /// Returns the signed quantity (notional value in USD) of the position.
    ///
    /// A positive value indicates a long position, a negative value indicates a short position,
    /// and `0` indicates no open position.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let quantity = position.quantity();
    ///
    /// println!("Position quantity: {}", quantity);
    /// # Ok(())
    /// # }
    /// ```
    pub fn quantity(&self) -> i64 {
        self.quantity
    }

    /// Returns the leverage multiplier applied to the position.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let leverage = position.leverage();
    ///
    /// println!("Position leverage: {}", leverage);
    /// # Ok(())
    /// # }
    /// ```
    pub fn leverage(&self) -> CrossLeverage {
        self.leverage
    }

    /// Returns the entry price of the position, if any.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(entry_price) = position.entry_price() {
    ///     println!("Entry price: {}", entry_price);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn entry_price(&self) -> Option<Price> {
        self.entry_price
    }

    /// Returns the running margin (current margin including P/L) in satoshis.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let running_margin = position.running_margin();
    ///
    /// println!("Running margin: {}", running_margin);
    /// # Ok(())
    /// # }
    /// ```
    pub fn running_margin(&self) -> u64 {
        self.running_margin
    }

    /// Returns the initial margin of the position (in satoshis).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let initial_margin = position.initial_margin();
    ///
    /// println!("Initial margin: {}", initial_margin);
    /// # Ok(())
    /// # }
    /// ```
    pub fn initial_margin(&self) -> u64 {
        self.initial_margin
    }

    /// Returns the maintenance margin requirement (in satoshis).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let maintenance_margin = position.maintenance_margin();
    ///
    /// println!("Maintenance margin: {}", maintenance_margin);
    /// # Ok(())
    /// # }
    /// ```
    pub fn maintenance_margin(&self) -> u64 {
        self.maintenance_margin
    }

    /// Returns the liquidation price at which the position will be automatically closed, if any.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(liq_price) = position.liquidation() {
    ///     println!("Liquidation price: {}", liq_price);
    /// }
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn liquidation(&self) -> Option<Price> {
        self.liquidation
    }

    /// Returns the total trading fees paid on this position in satoshis.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let fees = position.trading_fees();
    ///
    /// println!("Trading fees: {} sats", fees);
    /// # Ok(())
    /// # }
    /// ```
    pub fn trading_fees(&self) -> u64 {
        self.trading_fees
    }

    /// Returns the net funding fees for this position in satoshis.
    ///
    /// Funding fees are periodic payments that can be either paid by the user (positive value)
    /// or received by the user (negative value), depending on the funding rate. The funding rate
    /// varies according to the current balance between long and short positions on the exchange.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let fees = position.funding_fees();
    ///
    /// println!("Funding fees: {} sats", fees);
    /// # Ok(())
    /// # }
    /// ```
    pub fn funding_fees(&self) -> u64 {
        self.funding_fees
    }

    /// Returns the total profit/loss in satoshis.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let total_pl = position.total_pl();
    ///
    /// if total_pl > 0 {
    ///     println!("Total profit: {} sats", total_pl);
    /// } else {
    ///     println!("Total loss: {} sats", total_pl.abs());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn total_pl(&self) -> i64 {
        self.total_pl
    }

    /// Returns the delta profit/loss in satoshis since last update.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(position: lnm_sdk::api_v3::models::CrossPosition) -> Result<(), Box<dyn std::error::Error>> {
    /// let delta_pl = position.delta_pl();
    ///
    /// if delta_pl > 0 {
    ///     println!("P/L change: +{} sats", delta_pl);
    /// } else {
    ///     println!("P/L change: {} sats", delta_pl);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn delta_pl(&self) -> i64 {
        self.delta_pl
    }

    pub fn as_data_str(&self) -> String {
        let mut data_str = format!(
            "id: {}\nmargin: {}\nquantity: {}\nleverage: {}\nrunning_margin: {}\ninitial_margin: {}\nmaintenance_margin: {}\ntrading_fees: {}\nfunding_fees: {}\ntotal_pl: {}\ndelta_pl: {}",
            self.id,
            self.margin,
            self.quantity,
            self.leverage,
            self.running_margin,
            self.initial_margin,
            self.maintenance_margin,
            self.trading_fees,
            self.funding_fees,
            self.total_pl,
            self.delta_pl
        );

        if let Some(entry_price) = self.entry_price {
            data_str.push_str(&format!("\nentry_price: {entry_price}"));
        }
        if let Some(liquidation) = self.liquidation {
            data_str.push_str(&format!("\nliquidation: {liquidation}"));
        }

        data_str
    }
}

impl fmt::Display for CrossPosition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Cross Position:")?;
        for line in self.as_data_str().lines() {
            write!(f, "\n  {line}")?;
        }
        Ok(())
    }
}