tastytrade 0.4.0

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
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
use super::base::{Items, Paginated};
use crate::api::base::TastyResult;
use crate::api::query::{PageRequest, QueryBuilder};
use crate::api::url::encode_path_segment;
use crate::types::account_filter::{BalanceSnapshotFilter, PositionFilter, SnapshotRange};
use crate::types::balance::{Balance, BalanceSnapshot, SnapshotTimeOfDay};
use crate::types::capability::{ensure_legs_are_tradable, ensure_orders_are_tradable};
use crate::types::complex_order::{
    ComplexOrder, ComplexOrderId, ComplexOrderRequest, PairsThresholdEdit,
};
use crate::types::margin::{
    EffectiveMarginRequirement, MarginEstimate, MarginOrderRequest, MarginRequirementsReport,
    PositionLimit,
};
use crate::types::net_liq::{NetLiqHistoryFilter, NetLiqOhlc};
use crate::types::order::{
    DryRunResult, Order, OrderAmendment, OrderId, OrderPlacedResult, Warning,
};
use crate::types::order_filter::{LiveOrderFilter, OrderFilter};
use crate::types::trading_status::TradingStatus;
use crate::types::transaction::{TotalFees, Transaction, TransactionFilter};
use crate::{FullPosition, LiveOrderRecord, TastyTrade};
use chrono::{DateTime, FixedOffset, NaiveDate};
use pretty_simple_display::{DebugPretty, DisplaySimple};
use serde::{Deserialize, Serialize};

#[derive(
    DebugPretty, DisplaySimple, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone,
)]
#[serde(transparent)]
/// A broker-assigned account identifier.
///
/// Account PII: keep it out of logs and errors. [`AccountNumber::redacted`]
/// gives a form that is safe to write down.
pub struct AccountNumber(pub String);

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

impl AccountNumber {
    /// A form of this account number that is safe to log.
    ///
    /// Enough of it survives to tell two accounts apart in a log or a support
    /// thread; not enough to identify the account to someone who did not
    /// already have it. Anything short enough that a prefix and a suffix would
    /// reveal most of it is masked entirely.
    ///
    /// This exists because the rule — account identifiers stay out of logs —
    /// is easy to state and easy to forget at the call site. Somewhere to
    /// reach for makes it easier to follow than to break.
    pub fn redacted(&self) -> String {
        const KEEP_PREFIX: usize = 2;
        const KEEP_SUFFIX: usize = 3;

        let chars: Vec<char> = self.0.chars().collect();
        if chars.len() <= KEEP_PREFIX + KEEP_SUFFIX {
            return "*".repeat(chars.len().max(1));
        }

        let prefix: String = chars[..KEEP_PREFIX].iter().collect();
        let suffix: String = chars[chars.len() - KEEP_SUFFIX..].iter().collect();
        format!("{prefix}…{suffix}")
    }
}

/// Details of a single trading account.
///
/// The certification environment and production do not return the same set of
/// keys, and either side gains fields over time. A strict field is not a safe
/// default here: `Items<T>` skips items it cannot parse, so one missing key
/// turns a live account into an empty list rather than an error.
///
/// Tolerance does not mean inventing an answer. A flag the venue did not send
/// is `None`, never `false` — "the broker did not say whether this account is
/// in a firm error state" and "this account is not in a firm error state" are
/// different facts, and only one of them is safe to act on.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct AccountDetails {
    /// Broker-assigned account identifier.
    pub account_number: AccountNumber,
    /// External identifier, when the account carries one.
    pub external_id: Option<String>,
    /// Timestamp the account was opened, RFC 3339.
    #[serde(with = "crate::types::wire::datetime")]
    pub opened_at: DateTime<FixedOffset>,
    /// User-facing name of the account.
    pub nickname: String,
    /// Account type as named by the broker, e.g. `Individual`.
    pub account_type_name: String,
    /// Whether the account is flagged as a pattern day trader. `None` when the
    /// venue omits the flag, which is not the same as `false`.
    pub day_trader_status: Option<bool>,
    /// Whether the account is in a firm error state. `None` when the venue
    /// omits the flag, which is not the same as `false`.
    pub is_firm_error: Option<bool>,
    /// Whether the account is firm proprietary. `None` when the venue omits
    /// the flag, which is not the same as `false`.
    pub is_firm_proprietary: Option<bool>,
    /// Whether the account is a test-drive account.
    ///
    /// The only flag that defaults rather than reporting `None`: certification
    /// never sends it, and every account it serves is a real one from the
    /// caller's point of view, which is what `false` says.
    #[serde(default)]
    pub is_test_drive: bool,
    /// Whether the account is margin or cash.
    ///
    /// Still `String`, now for a measured reason rather than an assumed one.
    /// The census on 2026-08-04 (certification) could read exactly **one**
    /// account, and one record is not a value set. See
    /// [#125](https://github.com/joaquinbejar/tastytrade/issues/125).
    pub margin_or_cash: String,
    /// Whether the account is foreign. `None` when the venue omits the flag,
    /// which is not the same as `false`.
    pub is_foreign: Option<bool>,
    /// Date the account was funded, when it has been.
    #[serde(default, with = "crate::types::wire::date_option")]
    pub funding_date: Option<NaiveDate>,
    /// Whether the account has been closed. `None` when the venue omits it.
    pub is_closed: Option<bool>,
    /// Timestamp the account record was created.
    #[serde(default, with = "crate::types::wire::datetime_option")]
    pub created_at: Option<DateTime<FixedOffset>>,
    /// Stated investment objective, e.g. `SPECULATION`.
    pub investment_objective: Option<String>,
    /// Whether the account is approved to trade futures.
    pub is_futures_approved: Option<bool>,
    /// Options level the account is suitable for, e.g. `Defined Risk Spreads`.
    pub suitable_options_level: Option<String>,
}

#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
/// An account as the listing endpoint returns it.
pub struct AccountInner {
    /// The account itself.
    pub account: AccountDetails,
    /// What this session may do with it, e.g. `owner`.
    ///
    /// `None` when the account came from `GET /customers/me/accounts/{number}`,
    /// which answers with the account itself rather than the listing's
    /// authority decorator. A field the venue did not send is unknown, never
    /// empty — the same rule `is-test-drive` taught in #5, where a flag the
    /// broker omitted must not read as `false`.
    #[serde(default)]
    pub authority_level: Option<String>,
}

/// Evidence that a specific order was dry-run against a specific account.
///
/// Produced only by [`Account::review_order`], so it cannot be forged by
/// constructing a value: the fields are private and there is no constructor.
/// Turning it into a [`ReviewedOrder`] is a deliberate step, and when the
/// venue attached warnings the only way through is the method that says so in
/// its name.
#[derive(Debug)]
pub struct DryRunReceipt {
    account_number: AccountNumber,
    /// The base URL the dry run was answered by.
    ///
    /// An account number is just text, and certification reuses production
    /// numbering, so binding to the number alone would let a sandbox dry run
    /// authorise a real order. The origin is what actually distinguishes the
    /// venue that gave the answer.
    origin: String,
    order: Order,
    result: DryRunResult,
}

impl DryRunReceipt {
    /// Everything the venue said about the order: buying-power effect, fees
    /// and warnings.
    pub fn result(&self) -> &DryRunResult {
        &self.result
    }

    /// The warnings the venue attached, which is the part worth reading before
    /// risking money.
    pub fn warnings(&self) -> &[Warning] {
        &self.result.warnings
    }

    /// The order this receipt is about.
    pub fn order(&self) -> &Order {
        &self.order
    }

    /// Whether the venue attached anything that needs reading.
    pub fn is_clean(&self) -> bool {
        self.result.warnings.is_empty()
    }

    /// Accepts a clean dry run.
    ///
    /// # Errors
    ///
    /// Returns [`crate::TastyTradeError::Precondition`] when the venue attached
    /// warnings. That is not a refusal to proceed — it is a refusal to proceed
    /// *silently*. Read [`DryRunReceipt::warnings`] first, then use
    /// [`DryRunReceipt::accept_with_warnings`] to say you did.
    pub fn accept(self) -> TastyResult<ReviewedOrder> {
        if !self.is_clean() {
            return Err(crate::TastyTradeError::Precondition(format!(
                "the venue attached {} warning(s) to this order; read them and use \
                 accept_with_warnings to proceed deliberately",
                self.result.warnings.len()
            )));
        }

        Ok(ReviewedOrder {
            account_number: self.account_number,
            origin: self.origin,
            order: self.order,
        })
    }

    /// Accepts a dry run whose warnings the caller has read.
    ///
    /// Named so that the decision is visible at the call site rather than
    /// buried in a boolean argument.
    pub fn accept_with_warnings(self) -> ReviewedOrder {
        ReviewedOrder {
            account_number: self.account_number,
            origin: self.origin,
            order: self.order,
        }
    }
}

/// An order that has been dry-run and accepted, ready for
/// [`Account::place_reviewed_order`].
///
/// Like [`DryRunReceipt`], this has no public constructor: holding one means
/// the review happened.
#[derive(Debug)]
pub struct ReviewedOrder {
    account_number: AccountNumber,
    origin: String,
    order: Order,
}

impl ReviewedOrder {
    /// The account this order was reviewed against.
    pub fn account_number(&self) -> &AccountNumber {
        &self.account_number
    }

    /// The order that was reviewed.
    pub fn order(&self) -> &Order {
        &self.order
    }
}

/// Which verb a reviewed amendment will be applied with.
///
/// Recorded on the receipt at review time, so an amendment reviewed as one
/// cannot be applied as the other. The venue treats them differently, and a
/// caller should not be able to swap them after reading the answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AmendmentIntent {
    /// `PUT`: replace the working order.
    Replace,
    /// `PATCH`: edit its price and execution properties.
    Edit,
}

/// Evidence that a specific amendment to a specific order was dry-run.
///
/// Produced only by [`Account::review_amendment`], so it cannot be forged by
/// constructing a value. Not `Clone`: duplicable proof is not proof.
#[derive(Debug)]
pub struct AmendmentReceipt {
    account_number: AccountNumber,
    origin: String,
    order_id: OrderId,
    intent: AmendmentIntent,
    amendment: OrderAmendment,
    result: DryRunResult,
}

impl AmendmentReceipt {
    /// Everything the venue said about the amendment.
    pub fn result(&self) -> &DryRunResult {
        &self.result
    }

    /// The warnings the venue attached, which is the part worth reading before
    /// changing a live order.
    pub fn warnings(&self) -> &[Warning] {
        &self.result.warnings
    }

    /// The amendment this receipt is about.
    pub fn amendment(&self) -> &OrderAmendment {
        &self.amendment
    }

    /// Which order it amends.
    pub fn order_id(&self) -> OrderId {
        self.order_id
    }

    /// Whether it will be applied as a replacement or an edit.
    pub fn intent(&self) -> AmendmentIntent {
        self.intent
    }

    /// Whether the venue attached anything that needs reading.
    pub fn is_clean(&self) -> bool {
        self.result.warnings.is_empty()
    }

    /// Accepts a clean dry run.
    ///
    /// # Errors
    ///
    /// [`crate::TastyTradeError::Precondition`] when the venue attached
    /// warnings. Not a refusal to proceed — a refusal to proceed *silently*.
    pub fn accept(self) -> TastyResult<ReviewedAmendment> {
        if !self.is_clean() {
            return Err(crate::TastyTradeError::Precondition(format!(
                "the venue attached {} warning(s) to this amendment; read them and use \
                 accept_with_warnings to proceed deliberately",
                self.result.warnings.len()
            )));
        }

        Ok(self.into_reviewed())
    }

    /// Accepts a dry run that carried warnings, having read them.
    ///
    /// The name is the point: a caller reaching for this is saying so.
    pub fn accept_with_warnings(self) -> ReviewedAmendment {
        self.into_reviewed()
    }

    fn into_reviewed(self) -> ReviewedAmendment {
        ReviewedAmendment {
            account_number: self.account_number,
            origin: self.origin,
            order_id: self.order_id,
            intent: self.intent,
            amendment: self.amendment,
        }
    }
}

/// An amendment that has been dry-run and accepted.
///
/// Not `Clone`, for the same reason [`ReviewedOrder`] is not.
#[derive(Debug)]
pub struct ReviewedAmendment {
    account_number: AccountNumber,
    origin: String,
    order_id: OrderId,
    intent: AmendmentIntent,
    amendment: OrderAmendment,
}

impl ReviewedAmendment {
    /// The account this was reviewed against.
    pub fn account_number(&self) -> &AccountNumber {
        &self.account_number
    }

    /// Which order it amends.
    pub fn order_id(&self) -> OrderId {
        self.order_id
    }

    /// Whether it will be applied as a replacement or an edit.
    pub fn intent(&self) -> AmendmentIntent {
        self.intent
    }
}

/// Evidence that a specific complex order was dry-run against this account.
///
/// Produced only by [`Account::review_complex_order`]. Not `Clone`.
#[derive(Debug)]
pub struct ComplexOrderReceipt {
    account_number: AccountNumber,
    origin: String,
    request: ComplexOrderRequest,
    result: DryRunResult,
}

impl ComplexOrderReceipt {
    /// Everything the venue said about it.
    pub fn result(&self) -> &DryRunResult {
        &self.result
    }

    /// The warnings the venue attached.
    pub fn warnings(&self) -> &[Warning] {
        &self.result.warnings
    }

    /// The container this receipt is about.
    pub fn request(&self) -> &ComplexOrderRequest {
        &self.request
    }

    /// Whether the venue attached anything that needs reading.
    pub fn is_clean(&self) -> bool {
        self.result.warnings.is_empty()
    }

    /// Accepts a clean dry run.
    ///
    /// # Errors
    ///
    /// [`crate::TastyTradeError::Precondition`] when the venue attached
    /// warnings. A refusal to proceed *silently*, not a refusal to proceed.
    pub fn accept(self) -> TastyResult<ReviewedComplexOrder> {
        if !self.is_clean() {
            return Err(crate::TastyTradeError::Precondition(format!(
                "the venue attached {} warning(s) to this complex order; read them and \
                 use accept_with_warnings to proceed deliberately",
                self.result.warnings.len()
            )));
        }
        Ok(self.into_reviewed())
    }

    /// Accepts a dry run that carried warnings, having read them.
    pub fn accept_with_warnings(self) -> ReviewedComplexOrder {
        self.into_reviewed()
    }

    fn into_reviewed(self) -> ReviewedComplexOrder {
        ReviewedComplexOrder {
            account_number: self.account_number,
            origin: self.origin,
            request: self.request,
        }
    }
}

/// A complex order that has been dry-run and accepted. Not `Clone`.
#[derive(Debug)]
pub struct ReviewedComplexOrder {
    account_number: AccountNumber,
    origin: String,
    request: ComplexOrderRequest,
}

impl ReviewedComplexOrder {
    /// The account this was reviewed against.
    pub fn account_number(&self) -> &AccountNumber {
        &self.account_number
    }
}

/// Evidence that a threshold change was dry-run. Not `Clone`.
#[derive(Debug)]
pub struct PairsThresholdReceipt {
    account_number: AccountNumber,
    origin: String,
    complex_order_id: ComplexOrderId,
    edit: PairsThresholdEdit,
    result: DryRunResult,
}

impl PairsThresholdReceipt {
    /// Everything the venue said about it.
    pub fn result(&self) -> &DryRunResult {
        &self.result
    }

    /// The warnings the venue attached.
    pub fn warnings(&self) -> &[Warning] {
        &self.result.warnings
    }

    /// Whether the venue attached anything that needs reading.
    pub fn is_clean(&self) -> bool {
        self.result.warnings.is_empty()
    }

    /// Accepts a clean dry run.
    ///
    /// # Errors
    ///
    /// As [`ComplexOrderReceipt::accept`].
    pub fn accept(self) -> TastyResult<ReviewedPairsThreshold> {
        if !self.is_clean() {
            return Err(crate::TastyTradeError::Precondition(format!(
                "the venue attached {} warning(s) to this threshold change; read them \
                 and use accept_with_warnings to proceed deliberately",
                self.result.warnings.len()
            )));
        }
        Ok(self.into_reviewed())
    }

    /// Accepts a dry run that carried warnings, having read them.
    pub fn accept_with_warnings(self) -> ReviewedPairsThreshold {
        self.into_reviewed()
    }

    fn into_reviewed(self) -> ReviewedPairsThreshold {
        ReviewedPairsThreshold {
            account_number: self.account_number,
            origin: self.origin,
            complex_order_id: self.complex_order_id,
            edit: self.edit,
        }
    }
}

/// A threshold change that has been dry-run and accepted. Not `Clone`.
#[derive(Debug)]
pub struct ReviewedPairsThreshold {
    account_number: AccountNumber,
    origin: String,
    complex_order_id: ComplexOrderId,
    edit: PairsThresholdEdit,
}

impl ReviewedPairsThreshold {
    /// The account this was reviewed against.
    pub fn account_number(&self) -> &AccountNumber {
        &self.account_number
    }

    /// Which complex order it changes.
    pub fn complex_order_id(&self) -> &ComplexOrderId {
        &self.complex_order_id
    }
}

/// An account bound to the session that found it.
///
/// The lifetime ties it to its client, so an account cannot outlive the
/// session that can act on it.
pub struct Account<'t> {
    pub(crate) inner: AccountInner,
    pub(crate) tasty: &'t TastyTrade,
}

impl Account<'_> {
    /// This account's number.
    ///
    /// Account PII. Use [`AccountNumber::redacted`] before logging it.
    pub fn number(&self) -> AccountNumber {
        self.inner.account.account_number.clone()
    }

    /// Everything the venue said about this account.
    ///
    /// Nickname, type, margin-or-cash, the approval flags and the dates. A
    /// flag the broker did not send is `None`, never `false`.
    ///
    /// Account PII: [`AccountDetails::account_number`] is in here, so the same
    /// care applies as to [`Account::number`].
    pub fn details(&self) -> &AccountDetails {
        &self.inner.account
    }

    /// What this session may do with the account, e.g. `owner`.
    ///
    /// `None` when the account came from the single-account endpoint, which
    /// answers with the account itself rather than the listing's authority
    /// decorator, so there is no level to report. Not reported is not the same
    /// as none, and the caller should not have to know which call produced the
    /// account in order to read the value correctly.
    ///
    /// This reports what was decoded. It no longer maps an empty string to
    /// `None`, because nothing synthesises one any more: a level the venue sent
    /// as `""` would be a level the venue sent, and reading it as absent would
    /// be this crate deciding otherwise.
    pub fn authority_level(&self) -> Option<&str> {
        self.inner.authority_level.as_deref()
    }

    /// `/accounts/{this account}{suffix}`, with the number percent-encoded.
    ///
    /// Every account-scoped request builds its path here, so no endpoint can
    /// be added that forgets the encoding — the seven that existed before this
    /// each interpolated the number raw. `suffix` starts with `/` and carries
    /// any further dynamic segment already encoded, because only its caller
    /// knows where the boundaries between segments are.
    fn path(&self, suffix: &str) -> String {
        format!(
            "/accounts/{}{suffix}",
            encode_path_segment(&self.inner.account.account_number.0)
        )
    }

    /// Every current balance row, one per currency the account holds.
    ///
    /// Every monetary field is `Decimal`.
    ///
    /// # Errors
    ///
    /// Fails when balances arrive but none can be decoded, which is a defect
    /// in this crate rather than an account with no money. Propagates the
    /// venue's error otherwise; the response body never reaches it.
    pub async fn balances(&self) -> TastyResult<Vec<Balance>> {
        let resp: Items<Balance> = self.tasty.get(&self.path("/balances")).await?;
        resp.into_items()
    }

    /// The account's single balance row.
    ///
    /// The endpoint answers with an `items` envelope — it has since the venue
    /// changed it on 2024-05-01 — so "the balance" only means something when
    /// exactly one row came back. This decodes the envelope properly and says
    /// so when it does not, rather than picking a currency for the caller.
    ///
    /// # Errors
    ///
    /// [`crate::TastyTradeError::Precondition`] when the venue returned any
    /// number of rows other than one: the request succeeded and the answer
    /// does not fit the question, so retrying changes nothing. Use
    /// [`Account::balances`] or [`Account::balance_in`] instead. Otherwise as
    /// [`Account::balances`].
    pub async fn balance(&self) -> TastyResult<Balance> {
        let mut rows = self.balances().await?;

        if rows.len() == 1 {
            // `swap_remove` rather than indexing: the length is known and this
            // moves the row out without a clone or an unwrap.
            return Ok(rows.swap_remove(0));
        }

        // Currency codes are schema; the amounts beside them are not, and an
        // error travels wherever the caller sends it.
        let currencies: Vec<&str> = rows
            .iter()
            .map(|row| row.currency.as_deref().unwrap_or("unnamed"))
            .collect();

        Err(crate::TastyTradeError::Precondition(format!(
            "the account returned {} balance row(s) ({}), so there is no single \
             balance to return; use balances() for all of them or \
             balance_in(currency) for one",
            rows.len(),
            currencies.join(", ")
        )))
    }

    /// The balance row for one currency.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error, including a `404` for a currency the
    /// account does not hold.
    pub async fn balance_in(&self, currency: &str) -> TastyResult<Balance> {
        self.tasty
            .get(&self.path(&format!("/balances/{}", encode_path_segment(currency))))
            .await
    }

    /// Historical balance snapshots.
    ///
    /// `filter` carries the whole documented query: the time of day (which the
    /// venue requires), a single day **or** a date range, a currency and a
    /// page.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error, and fails if the endpoint answers
    /// without a pagination block.
    pub async fn balance_snapshots(
        &self,
        filter: &BalanceSnapshotFilter,
    ) -> TastyResult<Paginated<BalanceSnapshot>> {
        let query = filter.to_query();
        self.tasty
            .get_with_query::<Items<BalanceSnapshot>, _, _>(
                &self.path("/balance-snapshots"),
                &query.pairs(),
            )
            .await
    }

    /// Historical balance snapshots, by positional argument.
    ///
    /// The 0.3 signature, forwarding to [`Account::balance_snapshots`]. It
    /// could reach only one of the two date shapes the venue documents and had
    /// no way to send a currency, which is why the filter replaced it — but
    /// removing it outright would break every existing caller for no reason
    /// the caller can act on at the call site.
    ///
    /// # Errors
    ///
    /// As [`Account::balance_snapshots`].
    #[deprecated(
        since = "0.4.0",
        note = "use `balance_snapshots(&BalanceSnapshotFilter)`, which reaches the whole \
                documented query rather than four of its parameters"
    )]
    pub async fn balance_snapshot(
        &self,
        start_date: chrono::NaiveDate,
        end_date: chrono::NaiveDate,
        tod: SnapshotTimeOfDay,
        page_offset: usize,
    ) -> TastyResult<Paginated<BalanceSnapshot>> {
        let page_offset = u32::try_from(page_offset).map_err(|_| {
            crate::TastyTradeError::Precondition(format!(
                "page offset {page_offset} does not fit the u32 the venue accepts"
            ))
        })?;

        self.balance_snapshots(
            &BalanceSnapshotFilter::at(tod)
                .with_range(SnapshotRange::Range {
                    start: Some(start_date),
                    end: Some(end_date),
                })
                .with_page(PageRequest::new().with_page_offset(page_offset)),
        )
        .await
    }

    /// Open positions.
    ///
    /// # Errors
    ///
    /// Fails when positions arrive but none can be decoded, which is a defect
    /// in this crate rather than a flat account. A genuinely empty list is
    /// `Ok`.
    pub async fn positions(&self) -> TastyResult<Vec<FullPosition>> {
        self.positions_matching(&PositionFilter::new()).await
    }

    /// Positions the venue selects, rather than every open one.
    ///
    /// The filters are applied at the venue: asking for one underlying
    /// downloads one underlying. An empty [`PositionFilter`] sends no query
    /// parameters at all, so it is byte for byte the request
    /// [`Account::positions`] makes.
    ///
    /// # Errors
    ///
    /// As [`Account::positions`].
    pub async fn positions_matching(
        &self,
        filter: &PositionFilter,
    ) -> TastyResult<Vec<FullPosition>> {
        let query = filter.to_query();
        let resp: Items<FullPosition> = self
            .tasty
            .get_with_query(&self.path("/positions"), &query.pairs())
            .await?;
        resp.into_items()
    }

    /// One page of the account's ledger.
    ///
    /// Everything that changed a balance or a position: fills, fees,
    /// dividends, assignments, cash movements. `filter` carries the whole
    /// documented query.
    ///
    /// # Errors
    ///
    /// Fails when the endpoint answers without a pagination block, and when
    /// transactions arrive but none can be decoded. A genuinely empty page is
    /// `Ok`.
    pub async fn transactions(
        &self,
        filter: &TransactionFilter,
    ) -> TastyResult<Paginated<Transaction>> {
        let query = filter.to_query();
        self.tasty
            .get_with_query::<Items<Transaction>, _, _>(&self.path("/transactions"), &query.pairs())
            .await
    }

    /// One transaction by its identifier.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error, including a `404` for an identifier this
    /// account does not have.
    pub async fn transaction(&self, id: i64) -> TastyResult<Transaction> {
        // `id` is an `i64`, so its rendering is already path-safe. The type is
        // what guarantees that, not this call site.
        self.tasty
            .get(&self.path(&format!("/transactions/{id}")))
            .await
    }

    /// What the account paid in fees on one day.
    ///
    /// `None` omits the `date` parameter, which leaves the venue's documented
    /// default of today in place — sending today's date from this process
    /// would substitute *this machine's* idea of the date for the venue's.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error.
    pub async fn total_fees(&self, date: Option<NaiveDate>) -> TastyResult<TotalFees> {
        let mut query = QueryBuilder::new();
        query.push_opt("date", date);

        self.tasty
            .get_with_query::<TotalFees, TotalFees, _>(
                &self.path("/transactions/total-fees"),
                &query.pairs(),
            )
            .await
    }

    /// Whether the account may trade, and what it may trade.
    ///
    /// The cheap check before an order: a closed or frozen account cannot trade
    /// at all, a closing-only account can only reduce, and the feature flags
    /// decide whether futures, cryptocurrency or uncovered short calls are
    /// available. It also carries the live day-trade count.
    ///
    /// Every flag is `Option<bool>`: one the venue omitted is unknown, never
    /// `false`.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error.
    pub async fn trading_status(&self) -> TastyResult<TradingStatus> {
        self.tasty.get(&self.path("/trading-status")).await
    }

    /// The account's current margin and capital requirements, by underlying.
    ///
    /// The standing requirement, as opposed to the effect of one order. Nested
    /// three levels — total, per underlying, per margin strategy — because the
    /// per-strategy figures are what explain the total.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error.
    pub async fn margin_requirements(&self) -> TastyResult<MarginRequirementsReport> {
        self.tasty
            .get(&format!(
                "/margin/accounts/{}/requirements",
                encode_path_segment(&self.inner.account.account_number.0)
            ))
            .await
    }

    /// Estimates the margin one order would consume.
    ///
    /// **Routes nothing.** Named to keep it apart from
    /// [`Account::dry_run`], which is the order preflight against
    /// `/accounts/{n}/orders/dry-run`: this one answers "how much buying power
    /// would that take", that one answers "would the venue accept it". There is
    /// no path from here to a placement.
    ///
    /// # Errors
    ///
    /// Fails **before sending anything** with
    /// [`crate::TastyTradeError::Precondition`] when the request names a
    /// different account, has a blank underlying or symbol, carries no legs or
    /// more than [`crate::prelude::MAX_MARGIN_LEGS`], or repeats a leg.
    /// Propagates the venue's error otherwise.
    pub async fn estimate_margin(
        &self,
        request: &MarginOrderRequest,
    ) -> TastyResult<MarginEstimate> {
        request.validate(&self.inner.account.account_number.0)?;

        self.tasty
            .post(
                &format!(
                    "/margin/accounts/{}/dry-run",
                    encode_path_segment(&self.inner.account.account_number.0)
                ),
                request,
            )
            .await
    }

    /// The standing margin requirement for one underlying.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error.
    pub async fn effective_margin_requirement(
        &self,
        underlying_symbol: &str,
    ) -> TastyResult<EffectiveMarginRequirement> {
        self.tasty
            .get(&self.path(&format!(
                "/margin-requirements/{}/effective",
                encode_path_segment(underlying_symbol)
            )))
            .await
    }

    /// How much of each instrument type this account may order and hold.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error.
    pub async fn position_limit(&self) -> TastyResult<PositionLimit> {
        self.tasty.get(&self.path("/position-limit")).await
    }

    /// The account's equity curve.
    ///
    /// Open, high, low and close of net liquidating value over time — what a
    /// performance or drawdown chart is drawn from.
    ///
    /// **Live only.** The venue's sandbox page lists Net Liq History as
    /// unavailable in certification, so this returns nothing useful there.
    ///
    /// # Errors
    ///
    /// Fails when the listing arrives but nothing in it can be decoded, which
    /// is a defect in this crate's model rather than an account with no
    /// history. Propagates the venue's error otherwise.
    pub async fn net_liq_history(
        &self,
        filter: &NetLiqHistoryFilter,
    ) -> TastyResult<Vec<NetLiqOhlc>> {
        let query = filter.to_query();
        let resp: Items<NetLiqOhlc> = self
            .tasty
            .get_with_query(&self.path("/net-liq/history"), &query.pairs())
            .await?;
        resp.into_items()
    }

    /// Orders that are still working.
    ///
    /// # Errors
    ///
    /// As [`Account::positions`].
    pub async fn live_orders(&self) -> TastyResult<Vec<LiveOrderRecord>> {
        let resp: Items<LiveOrderRecord> = self.tasty.get(&self.path("/orders/live")).await?;
        resp.into_items()
    }

    /// Dry-runs `order` and returns evidence bound to this account and this
    /// exact order.
    ///
    /// This is the entry point to the reviewed-placement flow. The receipt
    /// cannot be constructed any other way, so a `ReviewedOrder` is proof that
    /// the venue was asked about *this* order against *this* account, and that
    /// whoever holds it had the chance to read the answer.
    pub async fn review_order(&self, order: &Order) -> TastyResult<DryRunReceipt> {
        let result = self.dry_run(order).await?;

        Ok(DryRunReceipt {
            account_number: self.number(),
            origin: self.tasty.config.base_url.clone(),
            order: order.clone(),
            result,
        })
    }

    /// Places an order that came through [`Account::review_order`].
    ///
    /// # Errors
    ///
    /// Returns [`crate::TastyTradeError::Precondition`] when the receipt belongs to a
    /// different account. A receipt is bound to the account it was reviewed
    /// against, and buying power, permissions and positions are all per
    /// account, so a review against one says nothing about another.
    pub async fn place_reviewed_order(
        &self,
        reviewed: ReviewedOrder,
    ) -> TastyResult<OrderPlacedResult> {
        if reviewed.account_number != self.number() {
            return Err(crate::TastyTradeError::Precondition(
                "this order was reviewed against a different account; \
                 review it again against the account you mean to trade"
                    .to_string(),
            ));
        }

        // An account number is text and certification reuses production
        // numbering, so without this a sandbox dry run would authorise a real
        // order against the same number.
        if reviewed.origin != self.tasty.config.base_url {
            return Err(crate::TastyTradeError::Precondition(
                "this order was reviewed against a different venue; \
                 a dry run on one environment says nothing about another"
                    .to_string(),
            ));
        }

        // `place_order` checks too. Repeated on purpose: a receipt is a value a
        // caller can hold across a process's lifetime, and this is the last
        // point before the request goes out.
        ensure_legs_are_tradable(reviewed.order.legs())?;

        self.place_order(&reviewed.order).await
    }

    /// Dry-runs an order without producing a receipt.
    ///
    /// Useful for pricing and what-if questions. For actually placing
    /// something, [`Account::review_order`] carries the answer forward.
    pub async fn dry_run(&self, order: &Order) -> TastyResult<DryRunResult> {
        // The same guard as placement, deliberately. A dry run that succeeds
        // and a placement that refuses would be a worse answer than one
        // consistent refusal: the caller would learn the venue accepts the
        // order and then find out it does not accept the route.
        ensure_legs_are_tradable(order.legs())?;

        let resp: DryRunResult = self
            .tasty
            .post(&self.path("/orders/dry-run"), order)
            .await?;
        Ok(resp)
    }

    /// Places an order directly, with no evidence it was ever dry-run.
    ///
    /// Prefer [`Account::review_order`] followed by
    /// [`Account::place_reviewed_order`]: that path makes the venue's warnings
    /// impossible to skip past without saying so. This one remains for callers
    /// that manage the review themselves.
    pub async fn place_order(&self, order: &Order) -> TastyResult<OrderPlacedResult> {
        ensure_legs_are_tradable(order.legs())?;

        let resp: OrderPlacedResult = self.tasty.post(&self.path("/orders"), order).await?;
        Ok(resp)
    }

    /// One order by its identifier.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error, including a `404` for an identifier this
    /// account does not have.
    pub async fn order(&self, id: OrderId) -> TastyResult<LiveOrderRecord> {
        // `OrderId` is a `u64`, so its rendering is already path-safe.
        self.tasty
            .get(&self.path(&format!("/orders/{}", id.0)))
            .await
    }

    /// One page of the account's order history.
    ///
    /// # Errors
    ///
    /// Fails when the endpoint answers without a pagination block, and when
    /// orders arrive but none can be decoded. A genuinely empty page is `Ok`.
    pub async fn search_orders(
        &self,
        filter: &OrderFilter,
    ) -> TastyResult<Paginated<LiveOrderRecord>> {
        let query = filter.to_query();
        self.tasty
            .get_with_query::<Items<LiveOrderRecord>, _, _>(&self.path("/orders"), &query.pairs())
            .await
    }

    /// One page of working orders, filtered.
    ///
    /// The live endpoint takes a **single** status and an underlying symbol,
    /// which is why [`LiveOrderFilter`] is not [`OrderFilter`]: sending the
    /// history filters here would be ignored, and the caller would believe a
    /// full listing had been narrowed.
    ///
    /// # Errors
    ///
    /// As [`Account::search_orders`].
    pub async fn live_orders_matching(
        &self,
        filter: &LiveOrderFilter,
    ) -> TastyResult<Paginated<LiveOrderRecord>> {
        let query = filter.to_query();
        self.tasty
            .get_with_query::<Items<LiveOrderRecord>, _, _>(
                &self.path("/orders/live"),
                &query.pairs(),
            )
            .await
    }

    /// Dry-runs an amendment to a working order and returns evidence.
    ///
    /// The entry point to the reviewed path for replacing and editing, and the
    /// only way to obtain an [`AmendmentReceipt`]. `intent` is recorded on the
    /// receipt, so an amendment reviewed as a replacement cannot be applied as
    /// an edit — the venue treats them differently and a caller should not be
    /// able to swap one for the other after reading the answer.
    ///
    /// # Errors
    ///
    /// Fails **before sending anything** with
    /// [`crate::TastyTradeError::Precondition`] when the amendment cannot be
    /// what the venue accepts — a good-til-date expiry on a non-GTD order, a
    /// GTD order with no expiry, or a limit order with no price. Propagates the
    /// venue's error otherwise.
    pub async fn review_amendment(
        &self,
        id: OrderId,
        intent: AmendmentIntent,
        amendment: &OrderAmendment,
    ) -> TastyResult<AmendmentReceipt> {
        amendment.validate()?;

        let result: DryRunResult = self
            .tasty
            .post(&self.path(&format!("/orders/{}/dry-run", id.0)), amendment)
            .await?;

        Ok(AmendmentReceipt {
            account_number: self.number(),
            origin: self.tasty.config.base_url.clone(),
            order_id: id,
            intent,
            amendment: amendment.clone(),
            result,
        })
    }

    /// Applies a reviewed amendment.
    ///
    /// **Mutates account state.** `PUT` for [`AmendmentIntent::Replace`],
    /// `PATCH` for [`AmendmentIntent::Edit`], chosen by what the receipt
    /// records rather than by which method was called.
    ///
    /// A replacement is not atomic at the venue: a fill on the original order
    /// aborts it. That is the venue's behaviour and this crate does not paper
    /// over it — the error comes back as the venue sent it.
    ///
    /// # Errors
    ///
    /// [`crate::TastyTradeError::Precondition`] when the receipt was produced
    /// against a different account or a different deployment. Propagates the
    /// venue's error otherwise.
    pub async fn place_reviewed_amendment(
        &self,
        reviewed: ReviewedAmendment,
    ) -> TastyResult<LiveOrderRecord> {
        if reviewed.account_number != self.number() {
            return Err(crate::TastyTradeError::Precondition(
                "this amendment was reviewed against a different account;                  review it again against the account you mean to trade"
                    .to_string(),
            ));
        }

        // Certification reuses production account numbering, so without this a
        // sandbox dry run would authorise a real amendment on the same number.
        if reviewed.origin != self.tasty.config.base_url {
            return Err(crate::TastyTradeError::Precondition(
                "this amendment was reviewed against a different venue; \
                 a dry run on one environment says nothing about another"
                    .to_string(),
            ));
        }

        let path = self.path(&format!("/orders/{}", reviewed.order_id.0));
        match reviewed.intent {
            AmendmentIntent::Replace => self.tasty.put(&path, &reviewed.amendment).await,
            AmendmentIntent::Edit => self.tasty.patch(&path, &reviewed.amendment).await,
        }
    }

    /// One page of the account's complex orders.
    ///
    /// # Errors
    ///
    /// Fails when the endpoint answers without a pagination block, and when
    /// containers arrive but none can be decoded.
    pub async fn complex_orders(&self, page: &PageRequest) -> TastyResult<Paginated<ComplexOrder>> {
        let mut query = QueryBuilder::new();
        page.write_into(&mut query);
        self.tasty
            .get_with_query::<Items<ComplexOrder>, _, _>(
                &self.path("/complex-orders"),
                &query.pairs(),
            )
            .await
    }

    /// Complex orders with components placed today.
    ///
    /// # Errors
    ///
    /// As [`Account::positions`].
    pub async fn live_complex_orders(&self) -> TastyResult<Vec<ComplexOrder>> {
        let resp: Items<ComplexOrder> = self.tasty.get(&self.path("/complex-orders/live")).await?;
        resp.into_items()
    }

    /// One complex order in full.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error, including a `404`.
    pub async fn complex_order(&self, id: &ComplexOrderId) -> TastyResult<ComplexOrder> {
        self.tasty
            .get(&self.path(&format!("/complex-orders/{}", encode_path_segment(&id.0))))
            .await
    }

    /// Dry-runs a complex order and returns evidence bound to this account.
    ///
    /// The entry point to the reviewed path, and the only way to obtain a
    /// [`ComplexOrderReceipt`]. A complex order routes real money, so it gets
    /// the same discipline as a plain one.
    ///
    /// # Errors
    ///
    /// Fails **before sending anything** with
    /// [`crate::TastyTradeError::Precondition`] when the container cannot be
    /// what the venue accepts — too few components for the strategy, or a
    /// PAIRS trade with no threshold. Propagates the venue's error otherwise.
    pub async fn review_complex_order(
        &self,
        request: &ComplexOrderRequest,
    ) -> TastyResult<ComplexOrderReceipt> {
        request.validate()?;
        ensure_orders_are_tradable(&request.orders)?;

        let result: DryRunResult = self
            .tasty
            .post(&self.path("/complex-orders/dry-run"), request)
            .await?;

        Ok(ComplexOrderReceipt {
            account_number: self.number(),
            origin: self.tasty.config.base_url.clone(),
            request: request.clone(),
            result,
        })
    }

    /// Places a reviewed complex order.
    ///
    /// **Mutates account state and routes real money.**
    ///
    /// # Errors
    ///
    /// [`crate::TastyTradeError::Precondition`] when the receipt was produced
    /// against a different account or a different deployment.
    pub async fn place_reviewed_complex_order(
        &self,
        reviewed: ReviewedComplexOrder,
    ) -> TastyResult<ComplexOrder> {
        self.check_origin(&reviewed.account_number, &reviewed.origin, "complex order")?;
        // Checked at review time too. Repeated on purpose: a receipt is a value
        // a caller can hold across a process's lifetime, and this is the last
        // point before the request goes out.
        ensure_orders_are_tradable(&reviewed.request.orders)?;

        self.tasty
            .post(&self.path("/complex-orders"), &reviewed.request)
            .await
    }

    /// Cancels a complex order.
    ///
    /// **Mutates account state.** The venue requests cancellation of every
    /// component that is not already terminal; a component that has filled
    /// stays filled.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error, including a refusal to cancel.
    pub async fn cancel_complex_order(&self, id: &ComplexOrderId) -> TastyResult<ComplexOrder> {
        self.tasty
            .delete(&self.path(&format!("/complex-orders/{}", encode_path_segment(&id.0))))
            .await
    }

    /// Dry-runs a change to a PAIRS trade's threshold price.
    ///
    /// The only thing `PATCH /complex-orders/{id}` changes, and it goes behind
    /// a receipt like every other change to a working order.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error.
    pub async fn review_pairs_threshold(
        &self,
        id: &ComplexOrderId,
        edit: &PairsThresholdEdit,
    ) -> TastyResult<PairsThresholdReceipt> {
        let result: DryRunResult = self
            .tasty
            .post(
                &self.path(&format!(
                    "/complex-orders/{}/dry-run",
                    encode_path_segment(&id.0)
                )),
                edit,
            )
            .await?;

        Ok(PairsThresholdReceipt {
            account_number: self.number(),
            origin: self.tasty.config.base_url.clone(),
            complex_order_id: id.clone(),
            edit: edit.clone(),
            result,
        })
    }

    /// Applies a reviewed threshold change.
    ///
    /// **Mutates account state.**
    ///
    /// # Errors
    ///
    /// As [`Account::place_reviewed_complex_order`].
    pub async fn place_reviewed_pairs_threshold(
        &self,
        reviewed: ReviewedPairsThreshold,
    ) -> TastyResult<ComplexOrder> {
        self.check_origin(
            &reviewed.account_number,
            &reviewed.origin,
            "threshold change",
        )?;

        self.tasty
            .patch(
                &self.path(&format!(
                    "/complex-orders/{}",
                    encode_path_segment(&reviewed.complex_order_id.0)
                )),
                &reviewed.edit,
            )
            .await
    }

    /// The account-and-deployment check every reviewed placement makes.
    ///
    /// Shared so the receipts cannot drift apart on the part that matters:
    /// certification reuses production account numbering, so the number alone
    /// does not identify what a dry run was answered by.
    fn check_origin(
        &self,
        account_number: &AccountNumber,
        origin: &str,
        what: &str,
    ) -> TastyResult<()> {
        if account_number != &self.number() {
            return Err(crate::TastyTradeError::Precondition(format!(
                "this {what} was reviewed against a different account; \
                 review it again against the account you mean to trade"
            )));
        }
        if origin != self.tasty.config.base_url {
            return Err(crate::TastyTradeError::Precondition(format!(
                "this {what} was reviewed against a different venue; \
                 a dry run on one environment says nothing about another"
            )));
        }
        Ok(())
    }

    /// Cancels a working order.
    ///
    /// **Mutates account state.** Cancelling an order that has already filled
    /// is the venue's decision to refuse, not this crate's.
    ///
    /// # Errors
    ///
    /// Propagates the venue's error, including a refusal to cancel.
    pub async fn cancel_order(&self, id: OrderId) -> TastyResult<LiveOrderRecord> {
        self.tasty
            // `OrderId` is a `u64`, so its decimal rendering is already inside
            // the unreserved set and encoding it would be a no-op. The type is
            // what guarantees that, not this call site.
            .delete(&self.path(&format!("/orders/{}", id.0)))
            .await
    }
}

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

    /// `GET /customers/me/accounts` exactly as certification answered it.
    ///
    /// A **capture**, not a transcription. Written by
    /// `examples/instruments/src/bin/capture_fixtures.rs` on 2026-08-04 with
    /// the account number and nickname replaced before the file reached the
    /// disk; every other key is what the venue sent. The hand-written literal
    /// this replaces happened to name the right keys, which is worth knowing
    /// and is exactly what could not be known while it was hand-written.
    ///
    /// What it pins down is the absence: no `is-test-drive`, no `external-id`,
    /// no `funding-date`. That absence is issue #5 — a required
    /// `is-test-drive` made `Items<T>` skip the account and
    /// `TastyTrade::account` report it as not on the session.
    const ACCOUNTS_CAPTURE: &str = include_str!("../../Doc/captures/accounts.json");

    /// The account object out of the captured listing.
    fn cert_account() -> String {
        let listing: serde_json::Value =
            serde_json::from_str(ACCOUNTS_CAPTURE).expect("the capture is valid JSON");
        listing["items"][0]["account"].to_string()
    }

    /// The production shape: `is-test-drive` present, none of the keys that
    /// only certification was observed to send.
    const PRODUCTION_ACCOUNT: &str = r#"{
        "account-number": "5WX54321",
        "external-id": "A1b2C3",
        "opened-at": "2024-03-02T09:00:00.000+00:00",
        "nickname": "Main",
        "account-type-name": "Individual",
        "day-trader-status": false,
        "is-firm-error": false,
        "is-firm-proprietary": false,
        "is-test-drive": false,
        "margin-or-cash": "Margin",
        "is-foreign": false,
        "funding-date": "2024-03-05"
    }"#;

    #[test]
    fn parses_the_certification_payload() {
        let account: AccountDetails =
            serde_json::from_str(&cert_account()).expect("certification accounts must parse");

        assert_eq!(account.account_number.0, "REDACTED");
        // Absent in certification, defaulted rather than fatal.
        assert!(!account.is_test_drive);
        assert_eq!(account.external_id, None);
        assert_eq!(account.funding_date, None);
        // Sent by certification, so reported as the venue stated it.
        assert_eq!(account.day_trader_status, Some(false));
        assert_eq!(account.is_firm_error, Some(false));
        // Present in certification, previously discarded.
        assert_eq!(account.is_closed, Some(false));
        // Present rather than absent, which is the distinction the type makes.
        assert_eq!(account.is_futures_approved, Some(false));
        // Present, and parsed. The values are placeholders — an account's
        // options level and open date are its owner's financial profile, and
        // this fixture is packaged and published — so what is asserted is that
        // the field arrived and went through the date path, not what it said.
        assert!(account.suitable_options_level.is_some());
        assert_eq!(
            account.created_at.map(|t| t.to_rfc3339()),
            Some("2020-01-01T00:00:00+00:00".to_string()),
            "the timestamp must be parsed, not carried as text"
        );
    }

    /// A flag the venue did not send is unknown, not false. Reporting `false`
    /// for an omitted firm-error or day-trader signal would let a caller act on
    /// an answer the broker never gave.
    #[test]
    fn an_omitted_flag_is_unknown_rather_than_false() {
        const WITHOUT_FLAGS: &str = r#"{
            "account-number": "5WX12345",
            "account-type-name": "Individual",
            "margin-or-cash": "Margin",
            "nickname": "Individual",
            "opened-at": "2025-01-14T10:22:41.000+00:00"
        }"#;

        let account: AccountDetails =
            serde_json::from_str(WITHOUT_FLAGS).expect("missing flags must not be fatal");

        assert_eq!(account.is_firm_error, None);
        assert_eq!(account.is_firm_proprietary, None);
        assert_eq!(account.day_trader_status, None);
        assert_eq!(account.is_foreign, None);
    }

    #[test]
    fn parses_the_production_payload() {
        let account: AccountDetails =
            serde_json::from_str(PRODUCTION_ACCOUNT).expect("production accounts must parse");

        assert_eq!(account.account_number.0, "5WX54321");
        assert!(!account.is_test_drive);
        assert_eq!(account.external_id.as_deref(), Some("A1b2C3"));
        assert_eq!(account.is_firm_error, Some(false));
        // Not sent by production, so absent rather than wrong.
        assert_eq!(account.is_closed, None);
        assert_eq!(account.investment_objective, None);
        assert_eq!(account.created_at, None);
    }

    /// The bug as the caller experienced it: `Items<T>` skips what it cannot
    /// parse, so one strict field turned a live sandbox account into an empty
    /// list and `TastyTrade::account` reported the account as not on the
    /// session.
    #[test]
    fn certification_accounts_survive_the_items_envelope() {
        let body = ACCOUNTS_CAPTURE.to_string();

        let items: Items<AccountInner> =
            serde_json::from_str(&body).expect("the envelope is well formed");

        assert_eq!(items.items.len(), 1, "the sandbox account must survive");
        assert_eq!(items.items[0].account.account_number.0, "REDACTED");
        // Present, which is the distinction that matters; the value is a
        // placeholder because this fixture is packaged and published.
        assert!(items.items[0].authority_level.is_some());
    }

    /// The listing sends the decorator and the single fetch does not, and the
    /// difference survives decoding rather than being flattened.
    ///
    /// Both values are **decoded**, not constructed: a test that built an
    /// `AccountInner` by hand would assert what this crate writes rather than
    /// what it reads, and the reading is where the empty string came from.
    #[test]
    fn an_absent_authority_level_decodes_as_unknown_rather_than_empty() {
        let listed: AccountInner = serde_json::from_str(&format!(
            r#"{{"account":{},"authority-level":"owner"}}"#,
            cert_account()
        ))
        .expect("the listing shape decodes");
        assert_eq!(listed.authority_level.as_deref(), Some("owner"));

        // The single-account endpoint answers with the account itself, so the
        // key is not there at all. It used to require a value, which is why
        // the call site synthesised one.
        let alone: AccountInner =
            serde_json::from_str(&format!(r#"{{"account":{}}}"#, cert_account()))
                .expect("an account with no decorator must still decode");
        assert_eq!(alone.authority_level, None);

        // And a level the venue really did send as empty stays empty. That is
        // a value it sent; reading it as absent would be this crate deciding
        // otherwise, which is the mistake in the other direction.
        let blank: AccountInner = serde_json::from_str(&format!(
            r#"{{"account":{},"authority-level":""}}"#,
            cert_account()
        ))
        .expect("an empty level decodes");
        assert_eq!(blank.authority_level.as_deref(), Some(""));
    }
}

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

    #[test]
    fn a_redacted_number_identifies_without_revealing() {
        let account = AccountNumber::from("5WX123456");
        let redacted = account.redacted();

        assert_eq!(redacted, "5W…456");
        assert!(
            !redacted.contains("X1234"),
            "the middle must not survive: {redacted}"
        );
    }

    /// Two accounts must still be distinguishable in a support thread.
    #[test]
    fn different_accounts_redact_differently() {
        assert_ne!(
            AccountNumber::from("5WX123456").redacted(),
            AccountNumber::from("5WX123789").redacted()
        );
    }

    /// A number short enough that a prefix and a suffix would reveal most of
    /// it is not partially redacted, it is hidden.
    #[test]
    fn a_short_number_is_masked_entirely() {
        for short in ["", "1", "12345"] {
            let redacted = AccountNumber::from(short).redacted();
            assert!(
                redacted.chars().all(|c| c == '*'),
                "{short:?} should be fully masked, got {redacted}"
            );
        }
    }
}