alpaca-sdk 0.0.0

Unofficial Rust SDK for the Alpaca trading, market data, and broker APIs
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
//! Request types for the trading API, ported from `alpaca/trading/requests.py`.
//!
//! alpaca-py builds these with keyword arguments and validates the combinations
//! in `model_validator` hooks. Rust has no kwargs, so each Python subclass
//! becomes a constructor, and several of the validators disappear because the
//! invalid states cannot be constructed:
//!
//! - "exactly one of `qty` or `notional`" is [`OrderAmount`]
//! - "exactly one of `trail_price` or `trail_percent`" is [`Trail`]
//! - "`limit_price` is not supported for market orders" is enforced by there
//!   being no way to set it on one
//!
//! What remains — the bracket/OCO/OTO leg requirements and the multi-leg rules —
//! is checked in [`OrderRequest::validate`], which the client calls before
//! sending.
//!
//! Optional fields are skipped when absent, which is what alpaca-py's
//! `NonEmptyRequest::to_request_fields` reimplements by hand.

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

use crate::error::{Error, Result};
use crate::trading::enums::{
    AssetClass, AssetExchange, AssetStatus, CorporateActionDateType, CorporateActionType,
    ExerciseStyle, OrderClass, OrderSide, OrderType, PositionIntent, QueryOrderStatus, TimeInForce,
};
use crate::types::{ContractType, Sort};

/// How much of an asset to trade.
///
/// Alpaca accepts a share quantity or a dollar amount, never both. alpaca-py
/// takes two optional fields and rejects the invalid combinations at runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrderAmount {
    /// A number of shares. Fractional quantities are supported for stocks with
    /// market orders and for crypto.
    Qty(Decimal),
    /// A dollar amount. Stocks only, and only with market orders.
    Notional(Decimal),
}

/// How far a trailing stop trails the high water mark.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Trail {
    /// A dollar amount away from the high water mark.
    Price(Decimal),
    /// A percentage away from the high water mark.
    Percent(Decimal),
}

/// The profit-taking leg of a bracket, OCO, or OTO order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TakeProfitRequest {
    /// The limit price to exit a profitable trade at.
    #[serde(with = "crate::types::decimal")]
    pub limit_price: Decimal,
}

impl TakeProfitRequest {
    /// A take-profit leg at `limit_price`.
    #[must_use]
    pub fn new(limit_price: Decimal) -> Self {
        Self { limit_price }
    }
}

/// The loss-limiting leg of a bracket, OCO, or OTO order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StopLossRequest {
    /// The stop price to exit a losing trade at.
    #[serde(with = "crate::types::decimal")]
    pub stop_price: Decimal,
    /// An optional limit price, making the exit a stop-limit rather than a stop.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub limit_price: Option<Decimal>,
}

impl StopLossRequest {
    /// A stop-loss leg at `stop_price`.
    #[must_use]
    pub fn new(stop_price: Decimal) -> Self {
        Self {
            stop_price,
            limit_price: None,
        }
    }

    /// Adds a limit price, making this a stop-limit exit.
    #[must_use]
    pub fn limit_price(mut self, limit_price: Decimal) -> Self {
        self.limit_price = Some(limit_price);
        self
    }
}

/// One leg of a multi-leg option order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OptionLegRequest {
    /// The option contract symbol.
    pub symbol: String,
    /// This leg's proportional quantity within the order.
    #[serde(with = "crate::types::decimal")]
    pub ratio_qty: Decimal,
    /// Whether this leg buys or sells.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub side: Option<OrderSide>,
    /// The desired position strategy for this leg.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub position_intent: Option<PositionIntent>,
}

impl OptionLegRequest {
    /// A leg identified by side.
    #[must_use]
    pub fn new(symbol: impl Into<String>, ratio_qty: Decimal, side: OrderSide) -> Self {
        Self {
            symbol: symbol.into(),
            ratio_qty,
            side: Some(side),
            position_intent: None,
        }
    }

    /// A leg identified by position intent instead of side.
    ///
    /// alpaca-py requires at least one of the two; this constructor and
    /// [`OptionLegRequest::new`] are the only ways to build one, so the check is
    /// unnecessary here.
    #[must_use]
    pub fn with_position_intent(
        symbol: impl Into<String>,
        ratio_qty: Decimal,
        position_intent: PositionIntent,
    ) -> Self {
        Self {
            symbol: symbol.into(),
            ratio_qty,
            side: None,
            position_intent: Some(position_intent),
        }
    }

    /// Sets the position intent alongside the side.
    #[must_use]
    pub fn position_intent(mut self, position_intent: PositionIntent) -> Self {
        self.position_intent = Some(position_intent);
        self
    }
}

/// An order to submit.
///
/// Build one with [`OrderRequest::market`], [`OrderRequest::limit`],
/// [`OrderRequest::stop`], [`OrderRequest::stop_limit`],
/// [`OrderRequest::trailing_stop`], or [`OrderRequest::multi_leg`], then chain
/// the optional setters.
///
/// ```
/// # use alpaca_sdk::trading::{OrderAmount, OrderRequest, OrderSide, TimeInForce};
/// # use rust_decimal::Decimal;
/// let order = OrderRequest::market(
///     "AAPL",
///     OrderSide::Buy,
///     OrderAmount::Qty(Decimal::from(1)),
///     TimeInForce::Day,
/// )
/// .client_order_id("my-order-1")
/// .extended_hours(true);
///
/// assert!(order.validate().is_ok());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrderRequest {
    /// The symbol being traded. Required for every order class except mleg.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
    /// Number of shares to trade.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub qty: Option<Decimal>,
    /// Dollar value to trade.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub notional: Option<Decimal>,
    /// Whether the order buys or sells. Required for every class except mleg.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub side: Option<OrderSide>,
    /// The execution logic of the order.
    #[serde(rename = "type")]
    pub order_type: OrderType,
    /// How long the order stays in force.
    pub time_in_force: TimeInForce,
    /// The order class.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub order_class: Option<OrderClass>,
    /// Whether the order may execute outside regular trading hours.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extended_hours: Option<bool>,
    /// A caller-supplied identifier for the order.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_order_id: Option<String>,
    /// The legs of a multi-leg option order.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub legs: Option<Vec<OptionLegRequest>>,
    /// The profit-taking exit, for bracket, OCO, and OTO orders.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub take_profit: Option<TakeProfitRequest>,
    /// The loss-limiting exit, for bracket, OCO, and OTO orders.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_loss: Option<StopLossRequest>,
    /// The desired position strategy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub position_intent: Option<PositionIntent>,
    /// Limit price, for limit and stop-limit orders.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub limit_price: Option<Decimal>,
    /// Stop price, for stop and stop-limit orders.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub stop_price: Option<Decimal>,
    /// Dollar trail, for trailing stop orders.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub trail_price: Option<Decimal>,
    /// Percentage trail, for trailing stop orders.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub trail_percent: Option<Decimal>,
}

impl OrderRequest {
    fn base(order_type: OrderType, time_in_force: TimeInForce) -> Self {
        Self {
            symbol: None,
            qty: None,
            notional: None,
            side: None,
            order_type,
            time_in_force,
            order_class: None,
            extended_hours: None,
            client_order_id: None,
            legs: None,
            take_profit: None,
            stop_loss: None,
            position_intent: None,
            limit_price: None,
            stop_price: None,
            trail_price: None,
            trail_percent: None,
        }
    }

    fn single_leg(
        order_type: OrderType,
        symbol: impl Into<String>,
        side: OrderSide,
        amount: OrderAmount,
        time_in_force: TimeInForce,
    ) -> Self {
        let mut request = Self::base(order_type, time_in_force);
        request.symbol = Some(symbol.into());
        request.side = Some(side);
        match amount {
            OrderAmount::Qty(qty) => request.qty = Some(qty),
            OrderAmount::Notional(notional) => request.notional = Some(notional),
        }
        request
    }

    /// A market order.
    #[must_use]
    pub fn market(
        symbol: impl Into<String>,
        side: OrderSide,
        amount: OrderAmount,
        time_in_force: TimeInForce,
    ) -> Self {
        Self::single_leg(OrderType::Market, symbol, side, amount, time_in_force)
    }

    /// A limit order.
    #[must_use]
    pub fn limit(
        symbol: impl Into<String>,
        side: OrderSide,
        amount: OrderAmount,
        time_in_force: TimeInForce,
        limit_price: Decimal,
    ) -> Self {
        let mut request = Self::single_leg(OrderType::Limit, symbol, side, amount, time_in_force);
        request.limit_price = Some(limit_price);
        request
    }

    /// A stop order.
    #[must_use]
    pub fn stop(
        symbol: impl Into<String>,
        side: OrderSide,
        amount: OrderAmount,
        time_in_force: TimeInForce,
        stop_price: Decimal,
    ) -> Self {
        let mut request = Self::single_leg(OrderType::Stop, symbol, side, amount, time_in_force);
        request.stop_price = Some(stop_price);
        request
    }

    /// A stop-limit order.
    #[must_use]
    pub fn stop_limit(
        symbol: impl Into<String>,
        side: OrderSide,
        amount: OrderAmount,
        time_in_force: TimeInForce,
        stop_price: Decimal,
        limit_price: Decimal,
    ) -> Self {
        let mut request =
            Self::single_leg(OrderType::StopLimit, symbol, side, amount, time_in_force);
        request.stop_price = Some(stop_price);
        request.limit_price = Some(limit_price);
        request
    }

    /// A trailing stop order.
    #[must_use]
    pub fn trailing_stop(
        symbol: impl Into<String>,
        side: OrderSide,
        amount: OrderAmount,
        time_in_force: TimeInForce,
        trail: Trail,
    ) -> Self {
        let mut request =
            Self::single_leg(OrderType::TrailingStop, symbol, side, amount, time_in_force);
        match trail {
            Trail::Price(price) => request.trail_price = Some(price),
            Trail::Percent(percent) => request.trail_percent = Some(percent),
        }
        request
    }

    /// A multi-leg option order.
    ///
    /// Only market and limit orders are supported for this class; pass
    /// `limit_price` to make it a limit order.
    #[must_use]
    pub fn multi_leg(
        qty: Decimal,
        time_in_force: TimeInForce,
        legs: Vec<OptionLegRequest>,
        limit_price: Option<Decimal>,
    ) -> Self {
        let order_type = if limit_price.is_some() {
            OrderType::Limit
        } else {
            OrderType::Market
        };
        let mut request = Self::base(order_type, time_in_force);
        request.order_class = Some(OrderClass::Mleg);
        request.qty = Some(qty);
        request.legs = Some(legs);
        request.limit_price = limit_price;
        request
    }

    /// Makes this a bracket order with both exits.
    #[must_use]
    pub fn bracket(mut self, take_profit: TakeProfitRequest, stop_loss: StopLossRequest) -> Self {
        self.order_class = Some(OrderClass::Bracket);
        self.take_profit = Some(take_profit);
        self.stop_loss = Some(stop_loss);
        self
    }

    /// Makes this a one-cancels-other order with both exits.
    #[must_use]
    pub fn oco(mut self, take_profit: TakeProfitRequest, stop_loss: StopLossRequest) -> Self {
        self.order_class = Some(OrderClass::Oco);
        self.take_profit = Some(take_profit);
        self.stop_loss = Some(stop_loss);
        self
    }

    /// Makes this a one-triggers-other order with a take-profit exit.
    #[must_use]
    pub fn oto_take_profit(mut self, take_profit: TakeProfitRequest) -> Self {
        self.order_class = Some(OrderClass::Oto);
        self.take_profit = Some(take_profit);
        self
    }

    /// Makes this a one-triggers-other order with a stop-loss exit.
    #[must_use]
    pub fn oto_stop_loss(mut self, stop_loss: StopLossRequest) -> Self {
        self.order_class = Some(OrderClass::Oto);
        self.stop_loss = Some(stop_loss);
        self
    }

    /// Sets whether the order may execute outside regular trading hours.
    #[must_use]
    pub fn extended_hours(mut self, extended_hours: bool) -> Self {
        self.extended_hours = Some(extended_hours);
        self
    }

    /// Sets a caller-supplied identifier for the order.
    #[must_use]
    pub fn client_order_id(mut self, client_order_id: impl Into<String>) -> Self {
        self.client_order_id = Some(client_order_id.into());
        self
    }

    /// Sets the desired position strategy.
    #[must_use]
    pub fn position_intent(mut self, position_intent: PositionIntent) -> Self {
        self.position_intent = Some(position_intent);
        self
    }

    /// Checks the combinations Alpaca rejects, before the request is sent.
    ///
    /// # Errors
    /// Returns [`Error::InvalidRequest`] when a bracket or OCO order is missing
    /// an exit, an OTO order has neither, or the multi-leg rules are violated:
    /// wrong order type, missing or duplicate legs, or a leg count outside 2 to 4.
    pub fn validate(&self) -> Result<()> {
        let invalid = |reason: String| Err(Error::InvalidRequest(reason));

        match self.order_class {
            Some(OrderClass::Bracket | OrderClass::Oco) => {
                let class = self.order_class.as_ref().map_or("", OrderClass::as_str);
                if self.take_profit.is_none() {
                    return invalid(format!("{class} orders require take_profit.limit_price"));
                }
                if self.stop_loss.is_none() {
                    return invalid(format!("{class} orders require stop_loss.stop_price"));
                }
            }
            Some(OrderClass::Oto) if self.take_profit.is_none() && self.stop_loss.is_none() => {
                return invalid("oto orders require either take_profit or stop_loss".to_owned());
            }
            _ => {}
        }

        if self.order_class == Some(OrderClass::Mleg) {
            if !matches!(self.order_type, OrderType::Market | OrderType::Limit) {
                return invalid(
                    "mleg order class only supports market and limit orders".to_owned(),
                );
            }
            if self.qty.is_none() {
                return invalid("qty is required for the mleg order class".to_owned());
            }

            let legs = self.legs.as_deref().unwrap_or_default();
            if legs.is_empty() {
                return invalid("legs is required for the mleg order class".to_owned());
            }
            if legs.len() > 4 {
                return invalid("at most 4 legs are allowed for the mleg order class".to_owned());
            }
            if legs.len() < 2 {
                return invalid("at least 2 legs are required for the mleg order class".to_owned());
            }

            let mut symbols: Vec<&str> = legs.iter().map(|leg| leg.symbol.as_str()).collect();
            symbols.sort_unstable();
            symbols.dedup();
            if symbols.len() != legs.len() {
                return invalid("all legs must have unique symbols".to_owned());
            }
        } else {
            if self.symbol.is_none() {
                return invalid(
                    "symbol is required for all order classes other than mleg".to_owned(),
                );
            }
            if self.side.is_none() {
                return invalid(
                    "side is required for all order classes other than mleg".to_owned(),
                );
            }
        }

        Ok(())
    }
}

/// Changes to apply to an existing order.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplaceOrderRequest {
    /// The new number of shares.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub qty: Option<Decimal>,
    /// The new expiration logic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<TimeInForce>,
    /// The new limit price. Required when replacing a limit or stop-limit order.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub limit_price: Option<Decimal>,
    /// The new stop price. Required when replacing a stop or stop-limit order.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub stop_price: Option<Decimal>,
    /// The new trail value, for trailing stop orders.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub trail: Option<Decimal>,
    /// A new caller-supplied identifier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_order_id: Option<String>,
}

impl ReplaceOrderRequest {
    /// An empty replacement, changing nothing.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Sets the new time in force.
    #[must_use]
    pub fn time_in_force(mut self, time_in_force: TimeInForce) -> Self {
        self.time_in_force = Some(time_in_force);
        self
    }

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

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

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

    /// Sets the new client order id.
    #[must_use]
    pub fn client_order_id(mut self, client_order_id: impl Into<String>) -> Self {
        self.client_order_id = Some(client_order_id.into());
        self
    }

    /// Checks that the supplied values are positive.
    ///
    /// # Errors
    /// Returns [`Error::InvalidRequest`] if `qty`, `stop_price`, or `trail` is
    /// zero or negative.
    pub fn validate(&self) -> Result<()> {
        for (name, value) in [
            ("qty", self.qty),
            ("stop_price", self.stop_price),
            ("trail", self.trail),
        ] {
            if let Some(value) = value
                && value <= Decimal::ZERO
            {
                return Err(Error::InvalidRequest(format!(
                    "{name} must be greater than 0"
                )));
            }
        }
        Ok(())
    }
}

/// How much of a position to close.
///
/// alpaca-py takes two optional fields and rejects both-or-neither at runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClosePositionRequest {
    /// Close this number of shares.
    Qty(Decimal),
    /// Close this percentage of the position, between 0 and 100.
    Percentage(Decimal),
}

impl ClosePositionRequest {
    /// The query parameters for this request.
    #[must_use]
    pub fn to_query(self) -> Vec<(&'static str, String)> {
        match self {
            Self::Qty(qty) => vec![("qty", qty.to_string())],
            Self::Percentage(percentage) => vec![("percentage", percentage.to_string())],
        }
    }
}

/// Filters for listing orders.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetOrdersRequest {
    /// Which orders to return: open, closed, or all. Defaults to open.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<QueryOrderStatus>,
    /// Maximum number of orders to return. Defaults to 50, maximum 500.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Only orders submitted after this time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub after: Option<DateTime<Utc>>,
    /// Only orders submitted until this time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub until: Option<DateTime<Utc>>,
    /// Chronological ordering of the response.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub direction: Option<Sort>,
    /// Whether to roll multi-leg orders up under their parent's `legs`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nested: Option<bool>,
    /// Only orders on this side.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub side: Option<OrderSide>,
    /// Only orders for these symbols.
    ///
    /// Sent as one comma-separated parameter, which is what Alpaca expects.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "crate::types::serde_util::comma_separated"
    )]
    pub symbols: Option<Vec<String>>,
}

/// Filters for fetching one order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetOrderByIdRequest {
    /// Whether to roll multi-leg orders up under their parent's `legs`.
    pub nested: bool,
}

/// Filters for listing assets.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetAssetsRequest {
    /// Only assets with this status.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<AssetStatus>,
    /// Only assets in this class.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub asset_class: Option<AssetClass>,
    /// Only assets on this exchange.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exchange: Option<AssetExchange>,
    /// Comma-separated attributes to filter on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<String>,
}

/// Filters for the market calendar.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetCalendarRequest {
    /// The first day to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start: Option<NaiveDate>,
    /// The last day to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end: Option<NaiveDate>,
}

/// Filters for portfolio history.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetPortfolioHistoryRequest {
    /// Duration of the data, as a number and unit such as `1D`, `1W`, `1M`, `1A`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub period: Option<String>,
    /// Resolution of each window: `1Min`, `5Min`, `15Min`, `1H`, or `1D`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeframe: Option<String>,
    /// How intraday data is reported.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intraday_reporting: Option<String>,
    /// Start of the window.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start: Option<DateTime<Utc>>,
    /// How profit and loss is reset between windows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pnl_reset: Option<String>,
    /// End of the window.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end: Option<DateTime<Utc>>,
    /// End date of the window.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub date_end: Option<NaiveDate>,
    /// Whether to include extended hours.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extended_hours: Option<bool>,
    /// Comma-separated cash flow activity types to include.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cashflow_types: Option<String>,
}

/// A new watchlist.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CreateWatchlistRequest {
    /// The watchlist name, up to 64 characters.
    pub name: String,
    /// The symbols to track.
    pub symbols: Vec<String>,
}

impl CreateWatchlistRequest {
    /// A watchlist named `name` tracking `symbols`.
    #[must_use]
    pub fn new(name: impl Into<String>, symbols: Vec<String>) -> Self {
        Self {
            name: name.into(),
            symbols,
        }
    }
}

/// Changes to apply to a watchlist.
///
/// At least one field must be set; [`UpdateWatchlistRequest::validate`] checks
/// it, mirroring alpaca-py's validator.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpdateWatchlistRequest {
    /// A new name for the watchlist.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// A new set of symbols, replacing the existing ones.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbols: Option<Vec<String>>,
}

impl UpdateWatchlistRequest {
    /// An empty update, changing nothing.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a new name.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets a new symbol list.
    #[must_use]
    pub fn symbols(mut self, symbols: Vec<String>) -> Self {
        self.symbols = Some(symbols);
        self
    }

    /// Checks that at least one field is set.
    ///
    /// # Errors
    /// Returns [`Error::InvalidRequest`] if neither `name` nor `symbols` is set.
    pub fn validate(&self) -> Result<()> {
        if self.name.is_none() && self.symbols.is_none() {
            return Err(Error::InvalidRequest(
                "one of name or symbols must be defined".to_owned(),
            ));
        }
        Ok(())
    }
}

/// Filters for corporate action announcements.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetCorporateAnnouncementsRequest {
    /// The action types to return. Alpaca allows at most 20.
    pub ca_types: Vec<CorporateActionType>,
    /// The earliest date to return, at most 90 days before `until`.
    pub since: NaiveDate,
    /// The latest date to return.
    pub until: NaiveDate,
    /// Only announcements for this symbol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
    /// Only announcements for this CUSIP.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cusip: Option<String>,
    /// Which date field `since` and `until` filter on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub date_type: Option<CorporateActionDateType>,
}

impl GetCorporateAnnouncementsRequest {
    /// Announcements of `ca_types` between `since` and `until`.
    #[must_use]
    pub fn new(ca_types: Vec<CorporateActionType>, since: NaiveDate, until: NaiveDate) -> Self {
        Self {
            ca_types,
            since,
            until,
            symbol: None,
            cusip: None,
            date_type: None,
        }
    }

    /// Only announcements for this symbol.
    #[must_use]
    pub fn symbol(mut self, symbol: impl Into<String>) -> Self {
        self.symbol = Some(symbol.into());
        self
    }

    /// Only announcements for this CUSIP.
    #[must_use]
    pub fn cusip(mut self, cusip: impl Into<String>) -> Self {
        self.cusip = Some(cusip.into());
        self
    }

    /// Which date field the window filters on.
    #[must_use]
    pub fn date_type(mut self, date_type: CorporateActionDateType) -> Self {
        self.date_type = Some(date_type);
        self
    }

    /// The query parameters for this request.
    ///
    /// `ca_types` is emitted once per value, which is what Python's `requests`
    /// does with a list and therefore what alpaca-py sends. It cannot go through
    /// the normal query serializer at all: `serde_urlencoded` has no
    /// representation for a sequence and fails the whole request.
    #[must_use]
    pub fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut query: Vec<(&'static str, String)> = self
            .ca_types
            .iter()
            .map(|ca_type| ("ca_types", ca_type.to_string()))
            .collect();

        query.push(("since", self.since.to_string()));
        query.push(("until", self.until.to_string()));

        if let Some(symbol) = &self.symbol {
            query.push(("symbol", symbol.clone()));
        }
        if let Some(cusip) = &self.cusip {
            query.push(("cusip", cusip.clone()));
        }
        if let Some(date_type) = &self.date_type {
            query.push(("date_type", date_type.to_string()));
        }

        query
    }

    /// Checks the range Alpaca accepts.
    ///
    /// # Errors
    /// Returns [`Error::InvalidRequest`] if the window exceeds 90 days.
    pub fn validate(&self) -> Result<()> {
        if (self.until - self.since).num_days() > 90 {
            return Err(Error::InvalidRequest(
                "the date range between since and until must be no more than 90 days".to_owned(),
            ));
        }
        Ok(())
    }
}

/// Filters for listing option contracts.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetOptionContractsRequest {
    /// Only contracts on these underlying symbols.
    ///
    /// Sent as one comma-separated parameter, which is what Alpaca expects.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "crate::types::serde_util::comma_separated"
    )]
    pub underlying_symbols: Option<Vec<String>>,
    /// Only contracts with this status. alpaca-py defaults this to active.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<AssetStatus>,
    /// Only contracts expiring on this date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expiration_date: Option<NaiveDate>,
    /// Only contracts expiring on or after this date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expiration_date_gte: Option<NaiveDate>,
    /// Only contracts expiring on or before this date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expiration_date_lte: Option<NaiveDate>,
    /// Only contracts with this root symbol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub root_symbol: Option<String>,
    /// Only calls or only puts.
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub contract_type: Option<ContractType>,
    /// Only contracts with this exercise style.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<ExerciseStyle>,
    /// Only contracts struck at or above this price.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub strike_price_gte: Option<Decimal>,
    /// Only contracts struck at or below this price.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "crate::types::option_decimal"
    )]
    pub strike_price_lte: Option<Decimal>,
    /// Maximum number of contracts to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Token for fetching the next page.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_token: Option<String>,
}

impl GetOptionContractsRequest {
    /// Contracts on `underlying_symbols`, with alpaca-py's default of active
    /// status applied.
    #[must_use]
    pub fn new(underlying_symbols: Vec<String>) -> Self {
        Self {
            underlying_symbols: Some(underlying_symbols),
            status: Some(AssetStatus::Active),
            ..Self::default()
        }
    }
}

/// The outcome of cancelling one order in a bulk cancel.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelOrderResponse {
    /// Id of the order.
    pub id: Uuid,
    /// Status code for this order's cancellation.
    #[serde(with = "crate::types::serde_util::int")]
    pub status: i64,
    /// Any additional detail returned for the cancellation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<serde_json::Value>,
}

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

    fn qty(value: i64) -> OrderAmount {
        OrderAmount::Qty(Decimal::from(value))
    }

    fn market() -> OrderRequest {
        OrderRequest::market("AAPL", OrderSide::Buy, qty(1), TimeInForce::Day)
    }

    #[test]
    fn market_order_serializes_only_the_fields_that_are_set() {
        // alpaca-py's NonEmptyRequest exists to strip the None fields; here that
        // is skip_serializing_if.
        let json = serde_json::to_value(market()).unwrap();

        assert_eq!(
            json,
            serde_json::json!({
                "symbol": "AAPL",
                "qty": "1",
                "side": "buy",
                "type": "market",
                "time_in_force": "day",
            })
        );
    }

    #[test]
    fn notional_orders_send_notional_instead_of_qty() {
        let order = OrderRequest::market(
            "AAPL",
            OrderSide::Buy,
            OrderAmount::Notional(Decimal::new(15_050, 2)),
            TimeInForce::Day,
        );
        let json = serde_json::to_value(&order).unwrap();

        assert_eq!(json["notional"], "150.50");
        assert!(json.get("qty").is_none());
    }

    #[test]
    fn limit_order_carries_its_price() {
        let order = OrderRequest::limit(
            "AAPL",
            OrderSide::Buy,
            qty(1),
            TimeInForce::Day,
            Decimal::new(1835, 1),
        );

        assert_eq!(order.order_type, OrderType::Limit);
        assert_eq!(
            serde_json::to_value(&order).unwrap()["limit_price"],
            "183.5"
        );
    }

    #[test]
    fn trailing_stop_sends_exactly_one_trail_field() {
        let by_price = OrderRequest::trailing_stop(
            "AAPL",
            OrderSide::Sell,
            qty(1),
            TimeInForce::Day,
            Trail::Price(Decimal::from(5)),
        );
        let by_percent = OrderRequest::trailing_stop(
            "AAPL",
            OrderSide::Sell,
            qty(1),
            TimeInForce::Day,
            Trail::Percent(Decimal::from(2)),
        );

        let price_json = serde_json::to_value(&by_price).unwrap();
        assert_eq!(price_json["trail_price"], "5");
        assert!(price_json.get("trail_percent").is_none());

        let percent_json = serde_json::to_value(&by_percent).unwrap();
        assert_eq!(percent_json["trail_percent"], "2");
        assert!(percent_json.get("trail_price").is_none());
    }

    #[test]
    fn bracket_orders_require_both_exits() {
        let take_profit = TakeProfitRequest::new(Decimal::from(200));
        let stop_loss = StopLossRequest::new(Decimal::from(150));

        assert!(
            market()
                .bracket(take_profit.clone(), stop_loss)
                .validate()
                .is_ok()
        );

        // Constructed by hand, since `bracket` sets both.
        let mut missing_stop = market();
        missing_stop.order_class = Some(OrderClass::Bracket);
        missing_stop.take_profit = Some(take_profit);
        assert!(missing_stop.validate().is_err());
    }

    #[test]
    fn oto_orders_require_at_least_one_exit() {
        assert!(
            market()
                .oto_take_profit(TakeProfitRequest::new(Decimal::from(200)))
                .validate()
                .is_ok()
        );
        assert!(
            market()
                .oto_stop_loss(StopLossRequest::new(Decimal::from(150)))
                .validate()
                .is_ok()
        );

        let mut neither = market();
        neither.order_class = Some(OrderClass::Oto);
        assert!(neither.validate().is_err());
    }

    #[test]
    fn multi_leg_orders_need_between_two_and_four_unique_legs() {
        let leg = |symbol: &str| OptionLegRequest::new(symbol, Decimal::from(1), OrderSide::Buy);

        let valid = OrderRequest::multi_leg(
            Decimal::from(1),
            TimeInForce::Day,
            vec![leg("AAPL240119C00150000"), leg("AAPL240119P00150000")],
            None,
        );
        assert!(valid.validate().is_ok());

        let too_few =
            OrderRequest::multi_leg(Decimal::from(1), TimeInForce::Day, vec![leg("A")], None);
        assert!(too_few.validate().is_err());

        let too_many = OrderRequest::multi_leg(
            Decimal::from(1),
            TimeInForce::Day,
            vec![leg("A"), leg("B"), leg("C"), leg("D"), leg("E")],
            None,
        );
        assert!(too_many.validate().is_err());

        let duplicate_symbols = OrderRequest::multi_leg(
            Decimal::from(1),
            TimeInForce::Day,
            vec![leg("A"), leg("A")],
            None,
        );
        assert!(duplicate_symbols.validate().is_err());
    }

    #[test]
    fn multi_leg_orders_reject_unsupported_order_types() {
        let mut order = OrderRequest::multi_leg(
            Decimal::from(1),
            TimeInForce::Day,
            vec![
                OptionLegRequest::new("A", Decimal::from(1), OrderSide::Buy),
                OptionLegRequest::new("B", Decimal::from(1), OrderSide::Sell),
            ],
            None,
        );
        order.order_type = OrderType::Stop;

        assert!(order.validate().is_err());
    }

    #[test]
    fn multi_leg_orders_omit_the_top_level_symbol_and_side() {
        let order = OrderRequest::multi_leg(
            Decimal::from(1),
            TimeInForce::Day,
            vec![
                OptionLegRequest::new("A", Decimal::from(1), OrderSide::Buy),
                OptionLegRequest::new("B", Decimal::from(1), OrderSide::Sell),
            ],
            None,
        );
        let json = serde_json::to_value(&order).unwrap();

        assert!(json.get("symbol").is_none());
        assert!(json.get("side").is_none());
        assert_eq!(json["order_class"], "mleg");
        assert_eq!(json["legs"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn single_leg_orders_require_a_symbol_and_side() {
        let mut order = market();
        order.symbol = None;
        assert!(order.validate().is_err());

        let mut order = market();
        order.side = None;
        assert!(order.validate().is_err());
    }

    #[test]
    fn replace_order_rejects_non_positive_values() {
        assert!(
            ReplaceOrderRequest::new()
                .qty(Decimal::from(1))
                .validate()
                .is_ok()
        );
        assert!(
            ReplaceOrderRequest::new()
                .qty(Decimal::ZERO)
                .validate()
                .is_err()
        );
        assert!(
            ReplaceOrderRequest::new()
                .trail(Decimal::from(-1))
                .validate()
                .is_err()
        );
    }

    #[test]
    fn watchlist_update_requires_at_least_one_field() {
        assert!(UpdateWatchlistRequest::new().validate().is_err());
        assert!(UpdateWatchlistRequest::new().name("x").validate().is_ok());
        assert!(
            UpdateWatchlistRequest::new()
                .symbols(vec!["AAPL".to_owned()])
                .validate()
                .is_ok()
        );
    }

    #[test]
    fn close_position_renders_one_query_parameter() {
        assert_eq!(
            ClosePositionRequest::Qty(Decimal::new(15, 1)).to_query(),
            vec![("qty", "1.5".to_owned())]
        );
        assert_eq!(
            ClosePositionRequest::Percentage(Decimal::from(50)).to_query(),
            vec![("percentage", "50".to_owned())]
        );
    }

    #[test]
    fn corporate_announcement_window_is_capped_at_ninety_days() {
        let since = NaiveDate::from_ymd_opt(2022, 1, 1).unwrap();

        let ok = GetCorporateAnnouncementsRequest::new(
            vec![CorporateActionType::Dividend],
            since,
            NaiveDate::from_ymd_opt(2022, 3, 1).unwrap(),
        );
        assert!(ok.validate().is_ok());

        let too_wide = GetCorporateAnnouncementsRequest::new(
            vec![CorporateActionType::Dividend],
            since,
            NaiveDate::from_ymd_opt(2022, 12, 1).unwrap(),
        );
        assert!(too_wide.validate().is_err());
    }

    #[test]
    fn option_contracts_request_defaults_to_active() {
        let request = GetOptionContractsRequest::new(vec!["AAPL".to_owned()]);
        assert_eq!(request.status, Some(AssetStatus::Active));
    }
}