tastytrade 0.4.2

Library for trading through tastytrade's 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
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
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
use crate::accounts::AccountNumber;
use crate::types::instrument::InstrumentType;
use crate::types::wire::wire_enum;
use chrono::{DateTime, FixedOffset, NaiveDate};
use derive_builder::Builder;
use pretty_simple_display::{DebugPretty, DisplaySimple};
use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;

/// Represents the effect of a price on an account.
///
/// This enum is used to indicate whether a price change results in a debit,
/// a credit, or has no effect on the account balance.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum PriceEffect {
    /// Represents a debit, meaning a reduction in the account balance.
    Debit,
    /// Represents a credit, meaning an increase in the account balance.
    Credit,
    /// Represents no effect on the account balance.
    None,
}

impl fmt::Display for PriceEffect {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PriceEffect::Debit => write!(f, "Debit"),
            PriceEffect::Credit => write!(f, "Credit"),
            PriceEffect::None => write!(f, "None"),
        }
    }
}

/// Represents an order action type.
///
/// This enum defines the different actions that can be performed when placing an order.
/// Each variant is serialized with a specific name for compatibility with the Tastyworks API.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    /// Represents a "Buy to Open" order action.
    #[serde(rename = "Buy to Open")]
    BuyToOpen,
    /// Represents a "Sell to Open" order action.
    #[serde(rename = "Sell to Open")]
    SellToOpen,
    /// Represents a "Buy to Close" order action.
    #[serde(rename = "Buy to Close")]
    BuyToClose,
    /// Represents a "Sell to Close" order action.
    #[serde(rename = "Sell to Close")]
    SellToClose,
    /// Represents a "Sell" order action.
    Sell,
    /// Represents a "Buy" order action.
    Buy,
}

/// Represents the type of order being placed.
///
/// This enum covers various order types, including limit orders, market orders,
/// marketable limit orders, stop orders, stop limit orders, and notional market orders.
/// The `#[serde(rename = "...")]` attribute is used to ensure proper serialization
/// and deserialization with external APIs that may use different naming conventions.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum OrderType {
    /// A limit order is an order to buy or sell a security at a specific price or better.
    Limit,
    /// A market order is an order to buy or sell a security at the best available price immediately.
    Market,
    /// A marketable limit order is a limit order that is priced to execute immediately.
    #[serde(rename = "Marketable Limit")]
    MarketableLimit,
    /// A stop order is an order to buy or sell a security once the price of the security reaches a specified stop price.
    Stop,
    /// A stop-limit order is an order to buy or sell a security once the price of the security reaches a specified stop price. Once the stop price is reached, the stop-limit order becomes a limit order to buy or sell at the limit price or better.
    #[serde(rename = "Stop Limit")]
    StopLimit,
    /// A notional market order specifies the total amount of money you are willing to spend rather than the number of shares you want to buy.
    #[serde(rename = "Notional Market")]
    NotionalMarket,
}

/// Represents the time-in-force instruction for an order.
///
/// This enum specifies how long an order remains active before it is canceled
/// or expires.  It uses serde's `rename` attribute to map the Rust enum
/// variants to specific string values expected by the Tastyworks API.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum TimeInForce {
    /// Day order: The order is valid only for the current trading day.
    #[serde(rename = "Day")]
    Day,
    /// Good-Til-Canceled order: The order remains active until it is filled or canceled.
    #[serde(rename = "GTC")]
    Gtc,
    /// Good-Til-Date order: The order remains active until the specified date.
    #[serde(rename = "GTD")]
    Gtd,
    /// Extended Hours order: The order can be executed during extended trading hours.
    #[serde(rename = "Ext")]
    Ext,
    /// Good-Til-Canceled Extended Hours order: Combines GTC and Extended Hours.
    #[serde(rename = "GTC Ext")]
    GTCExt,
    /// Immediate-or-Cancel order: The order must be filled immediately or partially filled.
    /// Any unfilled portion is canceled.
    #[serde(rename = "IOC")]
    Ioc,
}

wire_enum! {
    /// Represents the status of an order.
    ///
    /// The states an order moves through, from reception to a terminal one.
    /// The thirteen values are the ones the venue documents.
    ///
    /// It gained an `Unknown(String)` arm because this is a **response** enum
    /// and `Items<T>` skips what it cannot parse: a status the venue adds later
    /// would have made the order carrying it vanish from a live-orders listing
    /// without an error. An order disappearing quietly is the worst failure
    /// mode available on this endpoint.
    OrderStatus {
        Received => "Received",
        Routed => "Routed",
        InFlight => "In Flight",
        Live => "Live",
        CancelRequested => "Cancel Requested",
        ReplaceRequested => "Replace Requested",
        Contingent => "Contingent",
        Filled => "Filled",
        Cancelled => "Cancelled",
        Expired => "Expired",
        Rejected => "Rejected",
        Removed => "Removed",
        PartiallyRemoved => "Partially Removed",
    }
}

impl OrderStatus {
    /// Whether the order can still change.
    ///
    /// The terminal states are the ones the venue will not move an order out
    /// of. `Unknown` is **not** terminal: a status this crate has not seen says
    /// nothing about whether the order is done, and guessing "finished" would
    /// stop a caller watching an order that is still working.
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            OrderStatus::Filled
                | OrderStatus::Cancelled
                | OrderStatus::Expired
                | OrderStatus::Rejected
                | OrderStatus::Removed
        )
    }
}

/// Represents a trading symbol.
///
/// This struct wraps a `String` to represent a trading symbol.
/// The `#[serde(transparent)]` attribute ensures that during serialization and
/// deserialization, the `Symbol` is treated as if it were directly a `String`.
/// This simplifies the process and avoids unnecessary nesting in the resulting
/// JSON or other serialized formats.  It also ensures ordering, equality, and
/// hashing are based on the underlying string value.
#[derive(
    DebugPretty, DisplaySimple, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
#[serde(transparent)]
pub struct Symbol(pub String);

impl<T: AsRef<str>> From<T> for Symbol {
    fn from(value: T) -> Self {
        Self(value.as_ref().to_owned())
    }
}

/// Trait for converting types to `Symbol`.
///
/// This trait provides a method to convert a type into a `Symbol`, which represents a trading symbol.  This is useful for abstracting the process of obtaining a `Symbol` from various data sources.
pub trait AsSymbol {
    /// Converts the implementing type to a `Symbol`.
    fn as_symbol(&self) -> Symbol;
}

impl<T: AsRef<str>> AsSymbol for T {
    fn as_symbol(&self) -> Symbol {
        Symbol(self.as_ref().to_owned())
    }
}

/// Implements the `AsSymbol` trait for the `Symbol` type.
///
/// This implementation allows a `Symbol` to be converted into itself, which is a trivial operation.  This is useful when dealing with collections or generics where the `AsSymbol` trait is required, even though the underlying type is already a `Symbol`.
impl AsSymbol for Symbol {
    fn as_symbol(&self) -> Symbol {
        self.clone()
    }
}

/// Implements the `AsSymbol` trait for references to `Symbol`.
///
/// This implementation allows a reference to a `Symbol` to be directly used
/// in any context where the `AsSymbol` trait is required.  It simply clones
/// the underlying `Symbol` to satisfy the trait's method signature.
impl AsSymbol for &Symbol {
    fn as_symbol(&self) -> Symbol {
        (*self).clone()
    }
}

/// Represents an Order ID.
///
/// This struct provides a transparent wrapper around a `u64` to represent an order ID.
/// The `#[serde(transparent)]` attribute ensures that during serialization and deserialization,
/// the `OrderId` is treated as if it were just a `u64`.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct OrderId(pub u64);

/// Represents a live order record.
///
/// This struct holds the details of a live order, including its ID, account number,
/// time in force, order type, size, underlying symbol, price, price effect, status,
/// and flags indicating whether it's cancellable or editable.  The `#[serde(...)]`
/// attributes are used to control how the struct is serialized and deserialized
/// to and from JSON, ensuring compatibility with the Tastyworks API.  For example,
/// `rename_all = "kebab-case"` converts field names to kebab-case during serialization.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct LiveOrderRecord {
    /// The unique identifier for the order.
    pub id: OrderId,
    /// The account number associated with the order.
    pub account_number: AccountNumber,
    /// The time-in-force instruction for the order.
    pub time_in_force: TimeInForce,
    /// The type of order (e.g., Limit, Market, Stop).
    pub order_type: OrderType,
    /// The size of the order.
    ///
    /// `Decimal` rather than an integer: cryptocurrencies trade in fractions,
    /// and a corporate action can leave an equity position with one too.
    #[serde(with = "crate::types::wire::decimal")]
    pub size: Decimal,
    /// The symbol of the underlying asset being traded.
    pub underlying_symbol: Symbol,
    /// The price of the order, for order types that have one.
    ///
    /// `Option`, and it has to be: a market order has no price, and the
    /// account streamer's own documented example is a filled market order with
    /// no `price` field at all. A required `Decimal` here meant that
    /// notification could not be decoded — the most common order type there
    /// is, arriving on the socket that exists to report it.
    ///
    /// `Decimal` rather than `f64`, as everywhere money appears outside
    /// `types::dxfeed`.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub price: Option<Decimal>,
    /// Whether the price is a debit or a credit. Absent with `price`.
    #[serde(default)]
    pub price_effect: Option<PriceEffect>,
    /// The current status of the order (e.g., Live, Filled, Cancelled).
    pub status: OrderStatus,
    /// Indicates whether the order can be cancelled.
    pub cancellable: bool,
    /// Indicates whether the order can be edited.
    pub editable: bool,
    /// Indicates whether the order has been edited.
    pub edited: bool,

    // The account streamer publishes a *full* order object on every status
    // change, and the fills inside `legs` are the only place this crate ever
    // sees an execution: there is no other endpoint or event that carries
    // them. Everything below is what was being decoded and thrown away.
    //
    // All `Option`: the published schema marks nothing required, and an order
    // that has not been routed yet has no `live-at`, one that was never
    // rejected has no `reject-reason`. A required field the venue skips would
    // fail the decode of an order notification entirely.
    /// The legs of the order, each with the executions that filled it.
    #[serde(default)]
    pub legs: Vec<LiveOrderLeg>,

    /// The instrument type of the underlying.
    #[serde(default)]
    pub underlying_instrument_type: Option<InstrumentType>,

    /// The notional value of the order.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub value: Option<Decimal>,

    /// Whether `value` is a debit or a credit.
    #[serde(default)]
    pub value_effect: Option<PriceEffect>,

    /// How many legs the venue counts, as it reports it.
    #[serde(default, with = "crate::types::wire::loose_string_option")]
    pub leg_count: Option<String>,

    /// Where the order came from, as the venue labels it.
    #[serde(default)]
    pub source: Option<String>,

    /// Why the venue rejected the order, when it did.
    ///
    /// Venue prose. It can name the account, the instrument or the buying
    /// power involved, so it belongs in front of a person and never in a log
    /// line — the same rule dry-run warnings follow.
    #[serde(default)]
    pub reject_reason: Option<String>,

    /// The state of a contingency attached to the order.
    #[serde(default)]
    pub contingent_status: Option<String>,

    /// The stop trigger, for order types that have one.
    #[serde(default)]
    pub stop_trigger: Option<String>,

    /// The good-till-cancelled expiry date, for GTD orders.
    #[serde(default, with = "crate::types::wire::date_option")]
    pub gtc_date: Option<NaiveDate>,

    /// The complex order this one belongs to, when it belongs to one.
    #[serde(default)]
    pub complex_order_id: Option<String>,

    /// The tag of the complex order this one belongs to.
    #[serde(default)]
    pub complex_order_tag: Option<String>,

    /// The order this one replaces.
    #[serde(default)]
    pub replaces_order_id: Option<String>,

    /// The order that is replacing this one.
    #[serde(default)]
    pub replacing_order_id: Option<String>,

    /// The venue's own identifier for the order.
    #[serde(default)]
    pub external_identifier: Option<String>,

    /// The request that created the order, for correlating with a submission.
    #[serde(default)]
    pub global_request_id: Option<String>,

    /// The pre-flight identifier, when the venue assigns one.
    #[serde(default)]
    pub preflight_id: Option<String>,

    /// The user the order belongs to.
    ///
    /// Tolerant of both wire shapes: the swagger types it as a string and the
    /// account-streaming guide's example shows `"user-id": 99`.
    #[serde(default, with = "crate::types::wire::loose_string_option")]
    pub user_id: Option<String>,

    /// The username the order was placed under.
    #[serde(default)]
    pub username: Option<String>,

    /// Who cancelled the order.
    #[serde(default, with = "crate::types::wire::loose_string_option")]
    pub cancel_user_id: Option<String>,

    /// The username the cancellation was made under.
    #[serde(default)]
    pub cancel_username: Option<String>,

    /// When the venue received the order.
    #[serde(default, with = "crate::types::wire::datetime_option")]
    pub received_at: Option<DateTime<FixedOffset>>,

    /// When the order was in flight to the exchange.
    #[serde(default, with = "crate::types::wire::datetime_option")]
    pub in_flight_at: Option<DateTime<FixedOffset>>,

    /// When the order went live on the exchange.
    #[serde(default, with = "crate::types::wire::datetime_option")]
    pub live_at: Option<DateTime<FixedOffset>>,

    /// When the order reached a terminal state.
    #[serde(default, with = "crate::types::wire::datetime_option")]
    pub terminal_at: Option<DateTime<FixedOffset>>,

    /// When the order was cancelled.
    #[serde(default, with = "crate::types::wire::datetime_option")]
    pub cancelled_at: Option<DateTime<FixedOffset>>,

    /// When the order last changed, as the venue reports it.
    ///
    /// `String` on purpose. The published schema says this is a string with
    /// no format, and the account-streaming guide's own worked example shows
    /// `"updated-at": 1688584052750` — an integer. Two sources, two shapes,
    /// and no captured frame to settle it, so this keeps whatever arrived
    /// rather than inventing a timezone for it. The neighbouring timestamps
    /// are all `date-time` and are typed.
    #[serde(default, with = "crate::types::wire::loose_string_option")]
    pub updated_at: Option<String>,
}

/// Represents a leg of a live order.
///
/// This struct stores information about a specific leg within a live order.
/// It includes details such as the instrument type, symbol, quantity, remaining
/// quantity, action, and a vector of fills.  The `#[serde(rename_all =
/// "kebab-case")]` attribute ensures that the fields are serialized and
/// deserialized with kebab-case naming conventions.
#[allow(dead_code)]
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct LiveOrderLeg {
    /// The type of instrument for this leg.
    pub instrument_type: InstrumentType,
    /// The trading symbol for this leg.
    pub symbol: Symbol,
    /// The total quantity of the order for this leg.
    #[serde(with = "crate::types::wire::decimal")]
    pub quantity: Decimal,
    /// The remaining quantity to be filled for this leg.
    #[serde(with = "crate::types::wire::decimal")]
    pub remaining_quantity: Decimal,
    /// The action associated with this leg (e.g., Buy, Sell).
    pub action: Action,
    /// The executions that filled this leg.
    ///
    /// Was `Vec<String>`, which no real frame ever matched: a fill is an
    /// object. The venue publishes one message per fill as each is processed,
    /// so a leg routinely fills many times — a hundred one-share fills for a
    /// hundred-share order is the documented example — and this is where the
    /// prices are.
    #[serde(default)]
    pub fills: Vec<OrderFill>,
}

/// One execution against an order leg.
///
/// The only place an executed price reaches a caller of this crate. Everything
/// is `Option` except the numbers that define the execution, because the
/// published schema marks nothing required and a venue that omits an
/// identifier must not cost the caller the price.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct OrderFill {
    /// How much of the leg this execution filled.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub quantity: Option<Decimal>,
    /// The price it filled at.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub fill_price: Option<Decimal>,
    /// When it filled.
    #[serde(default, with = "crate::types::wire::datetime_option")]
    pub filled_at: Option<DateTime<FixedOffset>>,
    /// Where it filled.
    #[serde(default)]
    pub destination_venue: Option<String>,
    /// The venue's identifier for this fill.
    #[serde(default)]
    pub fill_id: Option<String>,
    /// The execution identifier the exchange assigned.
    #[serde(default)]
    pub ext_exec_id: Option<String>,
    /// The group identifier the exchange assigned, for grouped fills.
    #[serde(default)]
    pub ext_group_fill_id: Option<String>,
}

/// Represents an order to be placed.
///
/// This struct encapsulates the details of an order, including its time-in-force,
/// order type, price, price effect, and a vector of order legs.  It uses the
/// `derive_builder` crate to provide a convenient builder pattern for constructing
/// order instances.  The `serde` attributes control how the struct is serialized
/// and deserialized, ensuring compatibility with external APIs or data formats.
#[derive(Builder, Serialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
#[builder(setter(into), build_fn(validate = "OrderBuilder::validate_order"))]
pub struct Order {
    /// Specifies how long the order remains active before being canceled or expiring.
    time_in_force: TimeInForce,
    /// The type of order (e.g., Limit, Market, Stop).
    order_type: OrderType,
    /// The price of the order.  Serialized with arbitrary precision.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    price: Decimal,
    /// The effect of the price on the account (Debit, Credit, None).
    price_effect: PriceEffect,
    /// A vector of order legs, each specifying details about a specific instrument
    /// involved in the order.
    legs: Vec<OrderLeg>,
}

/// Represents a leg of an order.
///
/// An `OrderLeg` defines the specifics of a particular instrument within a potentially
/// more complex order.  It includes details such as the instrument type, symbol,
/// quantity, and desired action (buy, sell, etc.).  The struct utilizes the derive
/// builder pattern to simplify construction and uses the `serde` crate for
/// serialization and deserialization with kebab-case renaming.
///
#[derive(Builder, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
#[builder(setter(into), build_fn(validate = "OrderLegBuilder::validate_leg"))]
pub struct OrderLeg {
    /// The type of instrument (e.g., Equity, Option).
    instrument_type: InstrumentType,
    /// The trading symbol for the instrument.
    symbol: Symbol,
    /// The quantity of the instrument to be traded.
    ///
    /// Read from either wire shape and never through `f64`, so a fractional
    /// crypto quantity survives the round trip.
    #[serde(with = "crate::types::wire::decimal")]
    quantity: Decimal,
    /// The action to be taken (e.g., Buy, Sell).
    action: Action,
}

/// Represents the result of placing an order.
///
/// This structure encapsulates the details of a placed order, including the order record itself,
/// any warnings generated during order placement, the effect of the order on buying power, and
/// the fee calculation associated with the order.  The `#[serde(...)]` attributes control how
/// the struct is serialized and deserialized, ensuring compatibility with the Tastyworks API.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct OrderPlacedResult {
    /// The details of the placed order.
    pub order: LiveOrderRecord,
    /// A list of warnings generated during order placement.  This can include warnings such
    /// as insufficient buying power or exceeding order limits.
    pub warnings: Vec<Warning>,
    /// The effect of the placed order on the account's buying power. This includes details
    /// about changes in margin requirements and available buying power.
    pub buying_power_effect: BuyingPowerEffect,
    /// The calculation of fees associated with the placed order.
    pub fee_calculation: FeeCalculation,
}

/// Represents the result of a dry-run order execution.  This structure provides
/// details about the simulated order execution, including potential warnings,
/// buying power effects, and fee calculations.  It's designed for deserialization
/// from a JSON response using `serde`, with kebab-case field renaming.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct DryRunResult {
    /// Details of the simulated order.
    pub order: DryRunRecord,
    /// Any warnings generated during the dry-run.
    pub warnings: Vec<Warning>,
    /// The effect of the order on buying power.
    pub buying_power_effect: BuyingPowerEffect,
    /// Calculation of fees associated with the order.
    pub fee_calculation: FeeCalculation,
}

/// Represents a dry-run order record.  A dry-run order allows a user to simulate
/// placing an order to see the potential impact on their account without actually
/// executing the trade. This struct provides details about the simulated order,
/// such as its status, price, and whether it can be cancelled or edited.  The struct
/// utilizes the `serde` crate for serialization and deserialization, with kebab-case
/// renaming for compatibility with external APIs.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct DryRunRecord {
    /// The account number associated with the dry-run order.
    pub account_number: AccountNumber,
    /// The time-in-force instruction for the dry-run order (e.g., Day, GTC).
    pub time_in_force: TimeInForce,
    /// The type of the dry-run order (e.g., Limit, Market).
    pub order_type: OrderType,
    /// The size of the dry-run order.
    #[serde(with = "crate::types::wire::decimal")]
    pub size: Decimal,
    /// The underlying symbol for the dry-run order.
    pub underlying_symbol: Symbol,
    /// The price of the dry-run order.  Uses arbitrary precision deserialization.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub price: Decimal,
    /// The effect of the dry-run order's price on the account (Debit, Credit, None).
    pub price_effect: PriceEffect,
    /// The status of the dry-run order (e.g., Received, Filled, Cancelled).
    pub status: OrderStatus,
    /// Indicates whether the dry-run order can be cancelled.
    pub cancellable: bool,
    /// Indicates whether the dry-run order can be edited.
    pub editable: bool,
    /// Indicates whether the dry-run order has been edited.
    pub edited: bool,
    /// The legs of the dry-run order, providing details about each instrument involved.
    pub legs: Vec<OrderLeg>,
}

/// Represents the effect of a price change on buying power.
///
/// This struct details the changes in margin requirements and buying power
/// resulting from a price movement. It provides both the absolute changes and
/// the direction of the impact (debit or credit).  It uses `rust_decimal`
/// for arbitrary-precision decimal arithmetic to avoid floating-point
/// precision issues.  The `#[serde(rename_all = "kebab-case")]` attribute
/// ensures that the fields in the JSON response are matched to the struct
/// fields correctly, even if the casing is different.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct BuyingPowerEffect {
    /// The change in margin requirement.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub change_in_margin_requirement: Decimal,
    /// The effect of the change in margin requirement (Debit, Credit, None).
    pub change_in_margin_requirement_effect: PriceEffect,
    /// The change in buying power.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub change_in_buying_power: Decimal,
    /// The effect of the change in buying power (Debit, Credit, None).
    pub change_in_buying_power_effect: PriceEffect,
    /// The current buying power.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub current_buying_power: Decimal,
    /// The effect of the current buying power (Debit, Credit, None).  This field indicates whether
    /// the current buying power represents a debit or credit balance relative to a neutral point.
    pub current_buying_power_effect: PriceEffect,
    /// The overall impact of the price change.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub impact: Decimal,
    /// The overall effect of the price change (Debit, Credit, None).
    pub effect: PriceEffect,
}

/// Represents the calculation of fees.
///
/// This struct holds the total fees and the effect of those fees on the account balance.
/// It uses `#[serde(rename_all = "kebab-case")]` to handle kebab-case formatted data during deserialization.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct FeeCalculation {
    /// The total fees calculated. Uses `rust_decimal::serde::arbitrary_precision` for deserialization
    /// to avoid precision loss with floating-point numbers.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub total_fees: Decimal,
    /// The effect of the total fees on the price.  For example, fees are typically a debit.
    pub total_fees_effect: PriceEffect,
}

/// A warning the venue attached to a dry run or a placement.
///
/// Warnings are the reason to dry-run at all: they are how the broker says
/// "this will work, but not the way you probably meant". A caller is expected
/// to read them before placing.
///
/// The prose in `message` is venue-supplied and can name the account, the
/// order or a buying-power figure, so it belongs in front of a person who
/// asked for it, not in a log.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Warning {
    /// Broker code identifying the warning, when it sends one.
    ///
    /// Codes are stable enough to branch on; the message is not.
    pub code: Option<String>,
    /// Human-readable description of what the broker is warning about.
    ///
    /// Defaulted rather than required: `warnings` is a plain `Vec`, so one
    /// warning the venue shapes differently would otherwise fail the whole
    /// dry-run response and take the buying-power effect down with it. A
    /// warning that cannot be read is still better than no result at all, and
    /// whatever the venue did send lands in `details`.
    #[serde(default)]
    pub message: String,
    /// Any extra detail the broker attaches, kept as-is.
    ///
    /// The shape here is not documented and varies by warning, so it is
    /// preserved rather than modelled. Forward compatibility matters more
    /// than a typed view of something the venue can change at will.
    #[serde(flatten)]
    pub details: std::collections::BTreeMap<String, serde_json::Value>,
}

impl Warning {
    /// Whether the broker attached anything beyond a code and a message.
    pub fn has_details(&self) -> bool {
        !self.details.is_empty()
    }
}

#[cfg(test)]
mod warning_tests {
    use super::*;

    /// Shaped like a real dry-run warning: a code, a message, and extra keys
    /// the API documentation does not describe.
    const WARNING: &str = r#"{
        "code": "tif_next_valid_sesssion",
        "message": "Your order will be placed at the next valid session.",
        "preflight-id": "9f3c",
        "buying-power-required": "1250.00"
    }"#;

    #[test]
    fn a_warning_keeps_its_code_and_message() {
        let warning: Warning = serde_json::from_str(WARNING).expect("warnings must parse");

        assert_eq!(warning.code.as_deref(), Some("tif_next_valid_sesssion"));
        assert_eq!(
            warning.message,
            "Your order will be placed at the next valid session."
        );
    }

    /// The venue adds keys without notice and their shape is undocumented, so
    /// they are preserved rather than modelled or dropped.
    #[test]
    fn undocumented_keys_are_preserved_rather_than_discarded() {
        let warning: Warning = serde_json::from_str(WARNING).expect("warnings must parse");

        assert!(warning.has_details());
        assert_eq!(
            warning.details.get("preflight-id").and_then(|v| v.as_str()),
            Some("9f3c")
        );
        assert_eq!(
            warning
                .details
                .get("buying-power-required")
                .and_then(|v| v.as_str()),
            Some("1250.00")
        );
    }

    /// `warnings` is a plain Vec, so a warning shaped differently must not take
    /// the buying-power effect down with it.
    #[test]
    fn a_warning_without_a_message_is_not_fatal() {
        let warning: Warning =
            serde_json::from_str(r#"{"code":"odd","note":"venue changed shape"}"#)
                .expect("a missing message must not fail the dry run");

        assert_eq!(warning.code.as_deref(), Some("odd"));
        assert!(warning.message.is_empty());
        assert_eq!(
            warning.details.get("note").and_then(|v| v.as_str()),
            Some("venue changed shape")
        );
    }

    /// The old empty struct swallowed everything, which is what this fixes.
    #[test]
    fn a_dry_run_response_surfaces_its_warnings() {
        let body = format!(r#"{{"warnings":[{WARNING}]}}"#);

        #[derive(serde::Deserialize)]
        struct JustWarnings {
            warnings: Vec<Warning>,
        }

        let parsed: JustWarnings = serde_json::from_str(&body).expect("the list must parse");
        assert_eq!(parsed.warnings.len(), 1);
        assert!(
            !parsed.warnings[0].message.is_empty(),
            "a caller must be able to read the warning before risking money"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal::Decimal;
    use std::str::FromStr;

    #[test]
    fn test_price_effect_display() {
        assert_eq!(format!("{}", PriceEffect::Debit), "Debit");
        assert_eq!(format!("{}", PriceEffect::Credit), "Credit");
        assert_eq!(format!("{}", PriceEffect::None), "None");
    }

    #[test]
    fn test_order_status_display() {
        assert_eq!(format!("{}", OrderStatus::Received), "Received");
        assert_eq!(format!("{}", OrderStatus::Live), "Live");
        assert_eq!(format!("{}", OrderStatus::Filled), "Filled");
        assert_eq!(format!("{}", OrderStatus::Cancelled), "Cancelled");
        assert_eq!(format!("{}", OrderStatus::InFlight), "In Flight");
        assert_eq!(
            format!("{}", OrderStatus::CancelRequested),
            "Cancel Requested"
        );
        assert_eq!(
            format!("{}", OrderStatus::ReplaceRequested),
            "Replace Requested"
        );
        assert_eq!(
            format!("{}", OrderStatus::PartiallyRemoved),
            "Partially Removed"
        );
    }

    #[test]
    fn test_symbol_from_string() {
        let symbol = Symbol::from("AAPL");
        assert_eq!(symbol.0, "AAPL");

        let symbol = Symbol::from(String::from("MSFT"));
        assert_eq!(symbol.0, "MSFT");
    }

    #[test]
    fn test_symbol_as_symbol_trait() {
        let symbol_str = "TSLA";
        let symbol = symbol_str.as_symbol();
        assert_eq!(symbol.0, "TSLA");

        let symbol_string = String::from("GOOGL");
        let symbol = symbol_string.as_symbol();
        assert_eq!(symbol.0, "GOOGL");

        let symbol_obj = Symbol::from("NVDA");
        let symbol = symbol_obj.as_symbol();
        assert_eq!(symbol.0, "NVDA");

        let symbol_ref = &Symbol::from("AMD");
        let symbol = symbol_ref.as_symbol();
        assert_eq!(symbol.0, "AMD");
    }

    #[test]
    fn test_order_id() {
        let order_id = OrderId(12345);
        assert_eq!(order_id.0, 12345);
    }

    #[test]
    fn test_order_builder() {
        // A leg is required now: an order with none does nothing, and the
        // builder rejects it rather than letting the venue say so.
        let leg = OrderLegBuilder::default()
            .instrument_type(InstrumentType::Equity)
            .symbol("AAPL")
            .quantity(Decimal::from(1))
            .action(Action::BuyToOpen)
            .build()
            .unwrap();

        let order = OrderBuilder::default()
            .time_in_force(TimeInForce::Day)
            .order_type(OrderType::Limit)
            .price(Decimal::from_str("150.50").unwrap())
            .price_effect(PriceEffect::Debit)
            .legs(vec![leg])
            .build()
            .unwrap();

        // Test that the order was built successfully
        // We can't directly access private fields, but we can serialize to test
        let serialized = serde_json::to_string(&order).unwrap();
        assert!(serialized.contains("Day"));
        assert!(serialized.contains("Limit"));
        assert!(serialized.contains("150.50"));
        assert!(serialized.contains("Debit"));
    }

    #[test]
    fn test_order_leg_builder() {
        let order_leg = OrderLegBuilder::default()
            .instrument_type(InstrumentType::Equity)
            .symbol(Symbol::from("AAPL"))
            .quantity(Decimal::from(100))
            .action(Action::Buy)
            .build()
            .unwrap();

        let serialized = serde_json::to_string(&order_leg).unwrap();
        assert!(serialized.contains("Equity"));
        assert!(serialized.contains("AAPL"));
        assert!(serialized.contains("100"));
        assert!(serialized.contains("Buy"));
    }

    #[test]
    fn test_enum_serialization() {
        // Test Action enum serialization
        let action = Action::BuyToOpen;
        let serialized = serde_json::to_string(&action).unwrap();
        assert_eq!(serialized, "\"Buy to Open\"");

        let action = Action::SellToClose;
        let serialized = serde_json::to_string(&action).unwrap();
        assert_eq!(serialized, "\"Sell to Close\"");

        // Test OrderType enum serialization
        let order_type = OrderType::MarketableLimit;
        let serialized = serde_json::to_string(&order_type).unwrap();
        assert_eq!(serialized, "\"Marketable Limit\"");

        let order_type = OrderType::StopLimit;
        let serialized = serde_json::to_string(&order_type).unwrap();
        assert_eq!(serialized, "\"Stop Limit\"");

        // Test TimeInForce enum serialization
        let tif = TimeInForce::Gtc;
        let serialized = serde_json::to_string(&tif).unwrap();
        assert_eq!(serialized, "\"GTC\"");

        let tif = TimeInForce::GTCExt;
        let serialized = serde_json::to_string(&tif).unwrap();
        assert_eq!(serialized, "\"GTC Ext\"");
    }

    #[test]
    fn test_enum_deserialization() {
        // Test Action enum deserialization
        let action: Action = serde_json::from_str("\"Buy to Open\"").unwrap();
        matches!(action, Action::BuyToOpen);

        let action: Action = serde_json::from_str("\"Sell to Close\"").unwrap();
        matches!(action, Action::SellToClose);

        // Test OrderStatus enum deserialization
        let status: OrderStatus = serde_json::from_str("\"In Flight\"").unwrap();
        matches!(status, OrderStatus::InFlight);

        let status: OrderStatus = serde_json::from_str("\"Cancel Requested\"").unwrap();
        matches!(status, OrderStatus::CancelRequested);
    }

    #[test]
    fn test_symbol_clone_and_eq() {
        let symbol1 = Symbol::from("AAPL");
        let symbol2 = symbol1.clone();
        assert_eq!(symbol1, symbol2);

        let symbol3 = Symbol::from("MSFT");
        assert_ne!(symbol1, symbol3);
    }

    #[test]
    fn test_symbol_ordering() {
        let symbol1 = Symbol::from("AAPL");
        let symbol2 = Symbol::from("MSFT");
        let symbol3 = Symbol::from("AAPL");

        assert!(symbol1 < symbol2);
        assert!(symbol1 <= symbol3);
        assert!(symbol2 > symbol1);
        assert_eq!(symbol1, symbol3);
    }

    /// `PriceEffect` is `Copy` now, so a copy is a copy. It gained `Copy`,
    /// `PartialEq` and `Eq` because the transaction ledger compares them: a
    /// debit of 100 and a credit of 100 are opposite facts about one number.
    #[test]
    fn test_price_effect_copies_and_compares() {
        let effect1 = PriceEffect::Debit;
        let effect2 = effect1;

        assert_eq!(effect1, effect2);
        assert_ne!(effect1, PriceEffect::Credit);
    }

    #[test]
    fn test_all_enum_variants_exist() {
        // Test that all Action variants can be created
        let _actions = [
            Action::BuyToOpen,
            Action::SellToOpen,
            Action::BuyToClose,
            Action::SellToClose,
            Action::Sell,
            Action::Buy,
        ];

        // Test that all OrderType variants can be created
        let _order_types = [
            OrderType::Limit,
            OrderType::Market,
            OrderType::MarketableLimit,
            OrderType::Stop,
            OrderType::StopLimit,
            OrderType::NotionalMarket,
        ];

        // Test that all TimeInForce variants can be created
        let _time_in_forces = [
            TimeInForce::Day,
            TimeInForce::Gtc,
            TimeInForce::Gtd,
            TimeInForce::Ext,
            TimeInForce::GTCExt,
            TimeInForce::Ioc,
        ];

        // Test that all OrderStatus variants can be created
        let _statuses = [
            OrderStatus::Received,
            OrderStatus::Routed,
            OrderStatus::InFlight,
            OrderStatus::Live,
            OrderStatus::CancelRequested,
            OrderStatus::ReplaceRequested,
            OrderStatus::Contingent,
            OrderStatus::Filled,
            OrderStatus::Cancelled,
            OrderStatus::Expired,
            OrderStatus::Rejected,
            OrderStatus::Removed,
            OrderStatus::PartiallyRemoved,
        ];
    }
}

impl Order {
    /// The legs this order is made of.
    ///
    /// Read-only: an order is validated when it is built, and handing out a
    /// mutable reference would let a caller edit past the builder's checks.
    pub fn legs(&self) -> &[OrderLeg] {
        &self.legs
    }
}

impl OrderLeg {
    /// What kind of instrument this leg trades.
    pub fn instrument_type(&self) -> &InstrumentType {
        &self.instrument_type
    }

    /// The instrument.
    pub fn symbol(&self) -> &Symbol {
        &self.symbol
    }

    /// How many units.
    pub fn quantity(&self) -> Decimal {
        self.quantity
    }

    /// What the leg does to a position.
    pub fn action(&self) -> Action {
        self.action
    }
}

impl OrderLegBuilder {
    /// Rejects a leg the venue would reject, before it can reach the venue.
    ///
    /// A quantity is a count of things being traded, so zero means "do
    /// nothing" and a negative means the direction belongs in `action`, not in
    /// the number. Both are round trips to the broker to be told something
    /// this crate already knew.
    fn validate_leg(&self) -> Result<(), String> {
        if let Some(quantity) = self.quantity
            && quantity <= Decimal::ZERO
        {
            return Err(format!(
                "order leg quantity must be greater than zero, got {quantity}; \
                 use the action field to express direction"
            ));
        }

        if let Some(symbol) = &self.symbol
            && symbol.0.trim().is_empty()
        {
            return Err("order leg symbol must not be empty".to_string());
        }

        Ok(())
    }
}

impl OrderBuilder {
    /// Rejects an order the venue would reject.
    ///
    /// The rules encoded here hold regardless of instrument or account: an
    /// order with no legs does nothing, a limit or stop-limit order needs a
    /// price the venue can work, and a market order takes no price at all.
    /// Anything account-specific — buying power, permissions, suitability — is
    /// the venue's to judge, and `dry_run` is how you ask.
    fn validate_order(&self) -> Result<(), String> {
        if let Some(legs) = &self.legs
            && legs.is_empty()
        {
            return Err("an order must have at least one leg".to_string());
        }

        let Some(order_type) = &self.order_type else {
            return Ok(());
        };

        // Exhaustive on purpose, with no wildcard arm: OrderType is a closed
        // set the broker owns, and a variant added later must break this build
        // rather than inherit "any price is fine".
        let needs_positive_price = match order_type {
            // A working price is the whole point of these.
            OrderType::Limit | OrderType::StopLimit | OrderType::MarketableLimit => true,
            // The price field carries the trigger. A stop at zero or below is
            // a trigger that either never fires or fires immediately.
            OrderType::Stop => true,
            // The price is the amount of money to spend, so it is the order.
            OrderType::NotionalMarket => true,
            // The venue fills these at whatever the book offers, so a price is
            // at best ignored and at worst a misunderstanding worth flagging.
            OrderType::Market => false,
        };

        if let Some(price) = self.price {
            if needs_positive_price && price <= Decimal::ZERO {
                return Err(format!(
                    "a {order_type:?} order needs a price greater than zero, got {price}"
                ));
            }
            if !needs_positive_price && price != Decimal::ZERO {
                return Err(format!(
                    "a {order_type:?} order carries no price, so price must be zero, got \
                     {price}; use Limit to bound the fill"
                ));
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod builder_validation_tests {
    use super::*;
    use std::str::FromStr;

    fn leg() -> OrderLeg {
        OrderLegBuilder::default()
            .instrument_type(InstrumentType::Equity)
            .symbol("AAPL")
            .quantity(Decimal::from(1))
            .action(Action::BuyToOpen)
            .build()
            .expect("a one-share buy is valid")
    }

    /// Zero means "do nothing" and a negative means the direction was put in
    /// the wrong field. Both are round trips to the broker to be told
    /// something this crate already knew.
    #[test]
    fn a_leg_needs_a_positive_quantity() {
        for quantity in ["0", "-1", "-0.5"] {
            let error = OrderLegBuilder::default()
                .instrument_type(InstrumentType::Equity)
                .symbol("AAPL")
                .quantity(Decimal::from_str(quantity).unwrap())
                .action(Action::BuyToOpen)
                .build()
                .expect_err("a non-positive quantity must not build");

            assert!(
                error.to_string().contains("greater than zero"),
                "the error should say what is wrong: {error}"
            );
        }
    }

    /// Fractional quantities are legitimate — crypto trades in them — so the
    /// rule is "positive", not "whole".
    #[test]
    fn a_fractional_quantity_is_allowed() {
        OrderLegBuilder::default()
            .instrument_type(InstrumentType::Cryptocurrency)
            .symbol("BTC/USD")
            .quantity(Decimal::from_str("0.0001").unwrap())
            .action(Action::BuyToOpen)
            .build()
            .expect("a fractional crypto quantity is valid");
    }

    #[test]
    fn a_leg_needs_a_symbol() {
        let error = OrderLegBuilder::default()
            .instrument_type(InstrumentType::Equity)
            .symbol("   ")
            .quantity(Decimal::from(1))
            .action(Action::BuyToOpen)
            .build()
            .expect_err("a blank symbol must not build");

        assert!(error.to_string().contains("symbol"), "{error}");
    }

    #[test]
    fn an_order_needs_at_least_one_leg() {
        let error = OrderBuilder::default()
            .time_in_force(TimeInForce::Day)
            .order_type(OrderType::Market)
            .price(Decimal::ZERO)
            .price_effect(PriceEffect::None)
            .legs(Vec::<OrderLeg>::new())
            .build()
            .expect_err("an order with no legs does nothing");

        assert!(error.to_string().contains("at least one leg"), "{error}");
    }

    #[test]
    fn a_limit_order_needs_a_working_price() {
        let error = OrderBuilder::default()
            .time_in_force(TimeInForce::Day)
            .order_type(OrderType::Limit)
            .price(Decimal::ZERO)
            .price_effect(PriceEffect::Debit)
            .legs(vec![leg()])
            .build()
            .expect_err("a limit order at zero is not a price");

        assert!(error.to_string().contains("greater than zero"), "{error}");
    }

    /// A price on a market order is either ignored or a misunderstanding about
    /// what the order does, and the second is worth catching.
    #[test]
    fn a_market_order_takes_no_price() {
        let error = OrderBuilder::default()
            .time_in_force(TimeInForce::Day)
            .order_type(OrderType::Market)
            .price(Decimal::from(100))
            .price_effect(PriceEffect::Debit)
            .legs(vec![leg()])
            .build()
            .expect_err("a market order with a price must not build");

        assert!(error.to_string().contains("price must be zero"), "{error}");
    }

    #[test]
    fn a_well_formed_order_still_builds() {
        OrderBuilder::default()
            .time_in_force(TimeInForce::Day)
            .order_type(OrderType::Limit)
            .price(Decimal::from_str("1.25").unwrap())
            .price_effect(PriceEffect::Debit)
            .legs(vec![leg()])
            .build()
            .expect("a limit order with a price and a leg is valid");
    }
}

#[cfg(test)]
mod order_type_price_tests {
    use super::*;
    use std::str::FromStr;

    fn leg() -> OrderLeg {
        OrderLegBuilder::default()
            .instrument_type(InstrumentType::Equity)
            .symbol("AAPL")
            .quantity(Decimal::from(1))
            .action(Action::BuyToOpen)
            .build()
            .expect("a one-share buy is valid")
    }

    fn build_with(order_type: OrderType, price: &str) -> Result<Order, OrderBuilderError> {
        OrderBuilder::default()
            .time_in_force(TimeInForce::Day)
            .order_type(order_type)
            .price(Decimal::from_str(price).unwrap())
            .price_effect(PriceEffect::Debit)
            .legs(vec![leg()])
            .build()
    }

    /// Every order type that carries a price needs a working one. The match in
    /// the validator is exhaustive so a variant added later cannot quietly
    /// inherit "any price is fine" — this table is the other half of that.
    #[test]
    fn every_priced_order_type_rejects_a_non_positive_price() {
        for order_type in [
            OrderType::Limit,
            OrderType::StopLimit,
            OrderType::MarketableLimit,
            OrderType::Stop,
            OrderType::NotionalMarket,
        ] {
            for price in ["0", "-1"] {
                let error =
                    build_with(order_type, price).expect_err("a non-positive price must not build");
                assert!(
                    error.to_string().contains("greater than zero"),
                    "{order_type:?} at {price} should be rejected: {error}"
                );
            }

            build_with(order_type, "1.25")
                .unwrap_or_else(|e| panic!("{order_type:?} at 1.25 should build: {e}"));
        }
    }

    /// Market is the one type where a price means the caller misunderstood.
    #[test]
    fn a_market_order_is_the_only_one_that_takes_no_price() {
        build_with(OrderType::Market, "0").expect("a market order with no price builds");

        let error =
            build_with(OrderType::Market, "100").expect_err("a market order with a price must not");
        assert!(error.to_string().contains("price must be zero"), "{error}");
    }
}

/// An amendment to a working order: price and execution properties.
///
/// The body of both `PUT /orders/{id}` (replace) and `PATCH /orders/{id}`
/// (edit). The venue's schema gives the two **identical** property sets and
/// neither carries legs, so one type serves both — what differs is the verb,
/// and which one was intended is recorded on the receipt rather than left to
/// the call site.
///
/// The five fields the venue marks required are not `Option`. A required field
/// that could be omitted would compile and then 400.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct OrderAmendment {
    /// What kind of order it becomes.
    pub order_type: OrderType,
    /// How long it rests.
    pub time_in_force: TimeInForce,
    /// The price trigger for a stop or stop-limit order.
    #[serde(with = "crate::types::wire::decimal")]
    pub stop_trigger: Decimal,
    /// Whether the price is a debit or a credit.
    pub price_effect: PriceEffect,
    /// Whether the value is a debit or a credit.
    pub value_effect: PriceEffect,
    /// The price, for order types that take one.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::wire::decimal_option"
    )]
    pub price: Option<Decimal>,
    /// The notional value, for order types that take one.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::wire::decimal_option"
    )]
    pub value: Option<Decimal>,
    /// When a good-til-date order expires.
    ///
    /// The venue accepts this **only** when the time in force is `GTD`, which
    /// is checked before anything is sent.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::wire::date_option"
    )]
    pub gtc_date: Option<NaiveDate>,
}

impl OrderAmendment {
    /// An amendment that changes an order to `order_type` resting for
    /// `time_in_force`.
    pub fn new(
        order_type: OrderType,
        time_in_force: TimeInForce,
        stop_trigger: Decimal,
        price_effect: PriceEffect,
        value_effect: PriceEffect,
    ) -> Self {
        Self {
            order_type,
            time_in_force,
            stop_trigger,
            price_effect,
            value_effect,
            price: None,
            value: None,
            gtc_date: None,
        }
    }

    /// Sets the price.
    #[must_use]
    pub fn with_price(mut self, price: Decimal) -> Self {
        self.price = Some(price);
        self
    }

    /// Sets the notional value.
    #[must_use]
    pub fn with_value(mut self, value: Decimal) -> Self {
        self.value = Some(value);
        self
    }

    /// Sets the expiry of a good-til-date order.
    #[must_use]
    pub fn with_gtc_date(mut self, gtc_date: NaiveDate) -> Self {
        self.gtc_date = Some(gtc_date);
        self
    }

    /// Fails when the amendment cannot be what the venue accepts.
    ///
    /// Local checks, so [`crate::TastyTradeError::Precondition`] and not
    /// retryable: nothing was sent and sending it again would fail the same
    /// way.
    pub(crate) fn validate(&self) -> crate::TastyResult<()> {
        // "Can only be provided if time-in-force is GTD", says the venue. A
        // date attached to a Day order is a caller who meant something else.
        let is_gtd = matches!(self.time_in_force, TimeInForce::Gtd);
        if self.gtc_date.is_some() && !is_gtd {
            return Err(crate::TastyTradeError::Precondition(format!(
                "a good-til-date expiry only applies to a GTD order, and this one \
                 is {:?}",
                self.time_in_force
            )));
        }
        if is_gtd && self.gtc_date.is_none() {
            return Err(crate::TastyTradeError::Precondition(
                "a GTD order needs the date it expires on".to_string(),
            ));
        }

        // The venue documents `price` as required for limit and stop-limit.
        // Sending one without it is a rejection that costs a round trip and, on
        // a replacement, leaves the original order alone in an unclear state.
        if matches!(self.order_type, OrderType::Limit | OrderType::StopLimit)
            && self.price.is_none()
        {
            return Err(crate::TastyTradeError::Precondition(format!(
                "a {:?} order needs a price",
                self.order_type
            )));
        }

        Ok(())
    }
}