rpaca 0.8.1

A rust crate wrapping the Alpaca 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
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
//! Stock market data module for Alpaca API v2.
//!
//! This module provides functionality for accessing stock market data from Alpaca's v2 API,
//! including historical bars, quotes, trades, auctions, and snapshots. It offers comprehensive
//! methods for retrieving and analyzing various types of stock market data.
//!
//! The module includes functionality for:
//! - Historical and latest bars (OHLCV data)
//! - Historical and latest quotes (bid/ask data)
//! - Historical and latest trades
//! - Auction data (opening and closing)
//! - Market snapshots
//! - Exchange and trade condition codes

use crate::auth::{Alpaca, TradingType};
use crate::request::create_data_request;
use reqwest::Method;
use serde::{Deserialize, Serialize, Serializer};
use std::collections::HashMap;
use typed_builder::TypedBuilder;

/// Serializes a vector of stock symbols into a comma-separated string.
///
/// This function is used by serde to convert a Vec<String> of stock symbols
/// into a single comma-separated string for API requests.
///
/// # Arguments
/// * `symbols` - A vector of stock symbols to serialize
/// * `serializer` - The serializer to use
///
/// # Returns
/// * Result containing the serialized string or an error
fn serialize_symbols<S>(symbols: &[String], serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let joined = symbols.join(",");
    serializer.serialize_str(&joined)
}
/// Parameters for retrieving historical auction data from the Alpaca API.
///
/// This struct is used to build requests for historical auction data, including
/// opening and closing auctions for specified stock symbols.
#[derive(Debug, TypedBuilder, Serialize)]
pub struct HistoricalAuctionsParams {
    /// List of stock symbols to retrieve auction data for.
    /// Will be serialized as a comma-separated string.
    #[serde(serialize_with = "serialize_symbols")]
    pub symbols: Vec<String>,

    /// Start time for the data query in ISO 8601 format.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<String>,

    /// End time for the data query in ISO 8601 format.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<String>,

    /// Maximum number of data points to return.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u16>,

    /// Query for data as of this date (for historical snapshots).
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "asof")]
    pub asof_date: Option<String>,

    /// Data feed to use (e.g., "sip", "iex").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed: Option<String>,

    /// Currency to use for the data (e.g., "USD").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,

    /// Token for pagination to get the next page of results.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_token: Option<String>,

    /// Sort order for results, defaults to "asc" (ascending).
    #[builder(default =Some("asc".to_string()), setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<String>,
}

/// Response from the historical auctions API endpoint.
///
/// Contains auction data for requested symbols, organized by symbol and day.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuctionsResponse {
    /// Map of symbol to a vector of auction days.
    /// Each symbol has a list of days with auction data.
    pub auctions: HashMap<String, Vec<AuctionDay>>,

    /// Currency used for the price values (e.g., "USD").
    pub currency: Option<String>,

    /// Token for pagination to get the next page of results.
    #[serde(default)]
    pub next_page_token: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuctionDay {
    /// Date in RFC-3339 format.
    #[serde(rename = "d")]
    pub date: String,

    /// Opening auctions.
    #[serde(rename = "o")]
    pub opening: Vec<AuctionPrint>,

    /// Closing auctions (optional in your example).
    #[serde(rename = "c")]
    pub closing: Option<Vec<AuctionPrint>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuctionPrint {
    /// Timestamp in RFC-3339 with nanosecond precision.
    #[serde(rename = "t")]
    pub timestamp: String,

    /// Exchange code.
    #[serde(rename = "x")]
    pub exchange: String,

    /// Auction price.
    #[serde(rename = "p")]
    pub price: f64,

    /// Auction trade size.
    #[serde(rename = "s")]
    pub size: Option<i64>,

    /// Condition flag.
    #[serde(rename = "c")]
    pub condition: String,
}

/// Methods for accessing and manipulating auction data.
impl AuctionsResponse {
    /// Get auction days for a specific symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve data for
    ///
    /// # Returns
    /// * `Option<&Vec<AuctionDay>>` - Vector of auction days if the symbol exists, None otherwise
    pub fn get_symbol_data(&self, symbol: &str) -> Option<&Vec<AuctionDay>> {
        self.auctions.get(symbol)
    }

    /// Get all symbols in the response.
    ///
    /// # Returns
    /// * `Vec<&String>` - A vector of all symbols in the response
    pub fn symbols(&self) -> Vec<&String> {
        self.auctions.keys().collect()
    }

    /// Check if data exists for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to check
    ///
    /// # Returns
    /// * `bool` - True if the symbol exists in the response, false otherwise
    pub fn has_symbol(&self, symbol: &str) -> bool {
        self.auctions.contains_key(symbol)
    }

    /// Get the latest auction day for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the latest day for
    ///
    /// # Returns
    /// * `Option<&AuctionDay>` - The latest auction day if the symbol exists, None otherwise
    pub fn get_latest_day(&self, symbol: &str) -> Option<&AuctionDay> {
        self.auctions.get(symbol)?.last()
    }

    /// Get all opening prices for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve opening prices for
    ///
    /// # Returns
    /// * `Vec<f64>` - A vector of all opening prices for the symbol
    pub fn get_opening_prices(&self, symbol: &str) -> Vec<f64> {
        self.auctions
            .get(symbol)
            .map(|days| {
                days.iter()
                    .flat_map(|day| &day.opening)
                    .map(|auction| auction.price)
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get all closing prices for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve closing prices for
    ///
    /// # Returns
    /// * `Vec<f64>` - A vector of all closing prices for the symbol
    pub fn get_closing_prices(&self, symbol: &str) -> Vec<f64> {
        self.auctions
            .get(symbol)
            .map(|days| {
                days.iter()
                    .filter_map(|day| day.closing.as_ref())
                    .flatten()
                    .map(|auction| auction.price)
                    .collect()
            })
            .unwrap_or_default()
    }
}
/// Retrieves historical auction data from the Alpaca API.
///
/// This function fetches historical auction data for specified stock symbols,
/// including opening and closing auctions.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication
/// * `params` - Parameters for the historical auctions request
///
/// # Returns
/// * `Result<AuctionsResponse, Box<dyn std::error::Error>>` - The auction data or an error
///
/// # Examples
///
/// let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
/// let params = HistoricalAuctionsParams::builder()
///     .symbols(vec!["AAPL".to_string()])
///     .start("2024-01-03T00:00:00Z".to_string())
///     .end("2024-01-04T00:00:00Z".to_string())
///     .build();
/// let auctions = get_historical_auctions(&alpaca, params).await?;
///
pub async fn get_historical_auctions(
    alpaca: &Alpaca,
    params: HistoricalAuctionsParams,
) -> Result<AuctionsResponse, Box<dyn std::error::Error>> {
    let endpoint = "/v2/stocks/auctions";
    let query_string = serde_qs::to_string(&params)?;
    let endpoint_with_query = format!("{endpoint}?{query_string}");
    let response =
        create_data_request::<()>(alpaca, Method::GET, &endpoint_with_query, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting historical auctions failed: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_historial_auctions() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_historical_auctions(
        &alpaca,
        HistoricalAuctionsParams::builder()
            .symbols(vec!["AAPL".to_string()])
            .start("2024-01-03T00:00:00Z".to_string())
            .end("2024-01-04T01:02:03.123456789Z".to_string())
            .limit(1)
            .feed("sip".to_string())
            .currency("USD".to_string())
            .build(),
    )
    .await
    {
        Ok(res) => {
            assert!(res.has_symbol("AAPL"));
            assert_eq!(
                res.get_symbol_data("AAPL").unwrap().first().unwrap().date,
                "2024-01-03".to_string()
            );
            assert_eq!(*res.get_opening_prices("AAPL").first().unwrap(), 184.22);
            assert_eq!(*res.get_closing_prices("AAPL").first().unwrap(), 184.24);
            assert!(res.has_symbol("AAPL"));
        }
        Err(e) => panic!("Error getting historical auctions: {e}"),
    }
}

/// Parameters for retrieving historical bar (OHLC) data from the Alpaca API.
///
/// This struct is used to build requests for historical price bars (candles) with
/// open, high, low, close, and volume data for specified stock symbols.
#[derive(Debug, TypedBuilder, Serialize)]
pub struct HistoricalBarParams {
    /// List of stock symbols to retrieve bar data for.
    /// Will be serialized as a comma-separated string.
    #[serde(serialize_with = "serialize_symbols")]
    pub symbols: Vec<String>,

    /// Time frame for the bars, e.g., "1Min", "5Min", "1Hour", "1Day".
    pub timeframe: String,

    /// Start time for the data query in ISO 8601 format.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<String>,

    /// End time for the data query in ISO 8601 format.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<String>,

    /// Maximum number of bars to return.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u16>,

    /// Type of adjustment to apply to the data (e.g., "raw", "split", "dividend", "all").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adjustment: Option<String>,

    /// Query for data as of this date (for historical snapshots).
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asof: Option<String>,

    /// Data feed to use (e.g., "sip", "iex").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed: Option<String>,

    /// Currency to use for the data (e.g., "USD").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,

    /// Token for pagination to get the next page of results.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_token: Option<String>,

    /// Sort order for results (e.g., "asc", "desc").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<String>,
}
/// Response from the historical bars API endpoint.
///
/// Contains OHLC (Open, High, Low, Close) bar data for requested symbols.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BarResponse {
    /// Map of symbol to a vector of price bars.
    /// Each symbol has a list of bars representing price action over time.
    pub bars: HashMap<String, Vec<Bars>>,

    /// Token for pagination to get the next page of results.
    pub next_page_token: String,

    /// Currency used for the price values (e.g., "USD").
    pub currency: Option<String>,
}

/// Represents a single OHLC (Open, High, Low, Close) price bar.
///
/// Contains price and volume data for a specific time period.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bars {
    /// Timestamp in RFC-3339 format representing the start of the bar period.
    #[serde(rename = "t")]
    pub timestamp: String,

    /// Opening price for the period.
    #[serde(rename = "o")]
    pub open: f64,

    /// Highest price reached during the period.
    #[serde(rename = "h")]
    pub high: f64,

    /// Lowest price reached during the period.
    #[serde(rename = "l")]
    pub low: f64,

    /// Closing price for the period.
    #[serde(rename = "c")]
    pub close: f64,

    /// Total trading volume during the period.
    #[serde(rename = "v")]
    pub volume: i64,

    /// Number of trades executed during the period.
    #[serde(rename = "n")]
    pub count: i64,

    /// Volume-weighted average price (VWAP) for the period.
    #[serde(rename = "vw")]
    pub volume_weighted_average: f64,
}

/// Methods for accessing and manipulating bar data.
impl BarResponse {
    /* =========================
    Basic access / metadata
    ========================= */

    /// List all symbols present in the response.
    ///
    /// # Returns
    /// * An iterator over all symbol strings in the response
    pub fn symbols(&self) -> impl Iterator<Item = &str> {
        self.bars.keys().map(|s| s.as_str())
    }

    /// Borrow bars for a specific symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve bars for
    ///
    /// # Returns
    /// * A slice of bars if the symbol exists, None otherwise
    pub fn bars_for(&self, symbol: &str) -> Option<&[Bars]> {
        self.bars.get(symbol).map(|v| v.as_slice())
    }

    /// Get mutable access to bars for a symbol (for transforming/sorting).
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve mutable bars for
    ///
    /// # Returns
    /// * A mutable reference to the vector of bars if the symbol exists, None otherwise
    pub fn bars_for_mut(&mut self, symbol: &str) -> Option<&mut Vec<Bars>> {
        self.bars.get_mut(symbol)
    }

    /// Get the total number of bars across all symbols.
    ///
    /// # Returns
    /// * The total count of bars in the response
    pub fn len_total(&self) -> usize {
        self.bars.values().map(|v| v.len()).sum()
    }

    /// Check if there are no bars for any symbol.
    ///
    /// # Returns
    /// * `true` if there are no bars for any symbol, `false` otherwise
    pub fn is_empty(&self) -> bool {
        self.bars.values().all(|v| v.is_empty())
    }

    /// Get the next page token, treating empty string as "no more pages".
    ///
    /// # Returns
    /// * The next page token if it exists and is not empty, None otherwise
    pub fn next_page_token(&self) -> Option<&str> {
        if self.next_page_token.is_empty() {
            None
        } else {
            Some(self.next_page_token.as_str())
        }
    }

    /// Get the currency used for the price values.
    ///
    /// # Returns
    /// * The currency code (e.g., "USD") if available, None otherwise
    pub fn currency(&self) -> Option<&str> {
        self.currency.as_deref()
    }

    /* =========================
    Per-symbol convenience
    ========================= */

    /// Get the first bar for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the first bar for
    ///
    /// # Returns
    /// * The first bar if the symbol exists and has bars, None otherwise
    pub fn first_bar(&self, symbol: &str) -> Option<&Bars> {
        self.bars.get(symbol).and_then(|v| v.first())
    }

    /// Get the last bar for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the last bar for
    ///
    /// # Returns
    /// * The last bar if the symbol exists and has bars, None otherwise
    pub fn last_bar(&self, symbol: &str) -> Option<&Bars> {
        self.bars.get(symbol).and_then(|v| v.last())
    }

    /// Get all closing prices for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve closing prices for
    ///
    /// # Returns
    /// * A vector of closing prices for the symbol, empty if symbol doesn't exist
    pub fn closing_prices(&self, symbol: &str) -> Vec<f64> {
        self.bars
            .get(symbol)
            .map(|v| v.iter().map(|b| b.close).collect())
            .unwrap_or_default()
    }

    /// Get all opening prices for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve opening prices for
    ///
    /// # Returns
    /// * A vector of opening prices for the symbol, empty if symbol doesn't exist
    pub fn opening_prices(&self, symbol: &str) -> Vec<f64> {
        self.bars
            .get(symbol)
            .map(|v| v.iter().map(|b| b.open).collect())
            .unwrap_or_default()
    }

    /// Get all high prices for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve high prices for
    ///
    /// # Returns
    /// * A vector of high prices for the symbol, empty if symbol doesn't exist
    pub fn high_prices(&self, symbol: &str) -> Vec<f64> {
        self.bars
            .get(symbol)
            .map(|v| v.iter().map(|b| b.high).collect())
            .unwrap_or_default()
    }

    /// Get all low prices for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve low prices for
    ///
    /// # Returns
    /// * A vector of low prices for the symbol, empty if symbol doesn't exist
    pub fn low_prices(&self, symbol: &str) -> Vec<f64> {
        self.bars
            .get(symbol)
            .map(|v| v.iter().map(|b| b.low).collect())
            .unwrap_or_default()
    }

    /// Get all volume values for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve volumes for
    ///
    /// # Returns
    /// * A vector of volume values for the symbol, empty if symbol doesn't exist
    pub fn volumes(&self, symbol: &str) -> Vec<i64> {
        self.bars
            .get(symbol)
            .map(|v| v.iter().map(|b| b.volume).collect())
            .unwrap_or_default()
    }

    /// Get all trade count values for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve trade counts for
    ///
    /// # Returns
    /// * A vector of trade count values for the symbol, empty if symbol doesn't exist
    pub fn counts(&self, symbol: &str) -> Vec<i64> {
        self.bars
            .get(symbol)
            .map(|v| v.iter().map(|b| b.count).collect())
            .unwrap_or_default()
    }

    /// Get all volume-weighted average price (VWAP) values for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve VWAP values for
    ///
    /// # Returns
    /// * A vector of VWAP values for the symbol, empty if symbol doesn't exist
    pub fn vwap_values(&self, symbol: &str) -> Vec<f64> {
        self.bars
            .get(symbol)
            .map(|v| v.iter().map(|b| b.volume_weighted_average).collect())
            .unwrap_or_default()
    }

    /// Calculate the average closing price for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to calculate average close for
    ///
    /// # Returns
    /// * The average closing price if the symbol exists and has bars, None otherwise
    pub fn avg_close(&self, symbol: &str) -> Option<f64> {
        let v = self.bars.get(symbol)?;
        if v.is_empty() {
            return None;
        }
        Some(v.iter().map(|b| b.close).sum::<f64>() / v.len() as f64)
    }

    /// Find the maximum high price for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to find maximum high price for
    ///
    /// # Returns
    /// * The maximum high price if the symbol exists and has bars, None otherwise
    pub fn max_high(&self, symbol: &str) -> Option<f64> {
        self.bars
            .get(symbol)?
            .iter()
            .map(|b| b.high)
            .max_by(|a, b| a.partial_cmp(b).unwrap())
    }

    /// Find the minimum low price for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to find minimum low price for
    ///
    /// # Returns
    /// * The minimum low price if the symbol exists and has bars, None otherwise
    pub fn min_low(&self, symbol: &str) -> Option<f64> {
        self.bars
            .get(symbol)?
            .iter()
            .map(|b| b.low)
            .min_by(|a, b| a.partial_cmp(b).unwrap())
    }

    /// Calculate the total trading volume for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to calculate total volume for
    ///
    /// # Returns
    /// * The total volume if the symbol exists and has bars, None otherwise
    pub fn total_volume(&self, symbol: &str) -> Option<i64> {
        Some(self.bars.get(symbol)?.iter().map(|b| b.volume).sum())
    }

    /* =========================
    Cross-symbol utilities
    ========================= */

    /// Flatten an iterator over all bars for all symbols.
    ///
    /// This method provides a convenient way to iterate through all bars
    /// across all symbols, with each item containing both the symbol and the bar.
    ///
    /// # Returns
    /// * An iterator yielding tuples of (symbol, bar reference)
    pub fn iter_all(&self) -> impl Iterator<Item = (&str, &Bars)> {
        self.bars
            .iter()
            .flat_map(|(sym, v)| v.iter().map(move |b| (sym.as_str(), b)))
    }

    /// Find the maximum high price across all symbols and return the symbol and price.
    ///
    /// # Returns
    /// * A tuple containing the symbol and its maximum high price, or None if there are no bars
    pub fn max_high_all(&self) -> Option<(&str, f64)> {
        self.iter_all()
            .max_by(|(_, a), (_, b)| a.high.partial_cmp(&b.high).unwrap())
            .map(|(s, b)| (s, b.high))
    }

    /// Find the minimum low price across all symbols and return the symbol and price.
    ///
    /// # Returns
    /// * A tuple containing the symbol and its minimum low price, or None if there are no bars
    pub fn min_low_all(&self) -> Option<(&str, f64)> {
        self.iter_all()
            .min_by(|(_, a), (_, b)| a.low.partial_cmp(&b.low).unwrap())
            .map(|(s, b)| (s, b.low))
    }

    /// Calculate the total trading volume across all symbols.
    ///
    /// # Returns
    /// * The sum of all volume values across all bars for all symbols
    pub fn total_volume_all(&self) -> i64 {
        self.bars.values().flatten().map(|b| b.volume).sum()
    }
}

/// Retrieves historical price bars (OHLC) data from the Alpaca API.
///
/// This function fetches historical price bars for specified stock symbols,
/// with configurable timeframes (e.g., 1Min, 5Min, 1Hour, 1Day).
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication
/// * `params` - Parameters for the historical bars request
///
/// # Returns
/// * `Result<BarResponse, Box<dyn std::error::Error>>` - The bar data or an error
///
/// # Examples
///
/// let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
/// let params = HistoricalBarParams::builder()
///     .symbols(vec!["AAPL".to_string()])
///     .timeframe("1Day".to_string())
///     .start("2024-01-01T00:00:00Z".to_string())
///     .end("2024-01-31T00:00:00Z".to_string())
///     .build();
/// let bars = get_historical_bars(&alpaca, params).await?;
///
pub async fn get_historical_bars(
    alpaca: &Alpaca,
    params: HistoricalBarParams,
) -> Result<BarResponse, Box<dyn std::error::Error>> {
    let endpoint = "/v2/stocks/bars";
    let query_string = serde_qs::to_string(&params)?;
    let endpoint_with_query = format!("{endpoint}?{query_string}");
    let response =
        create_data_request::<()>(alpaca, Method::GET, &endpoint_with_query, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting historical bars failed: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_get_historical_bars() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_historical_bars(
        &alpaca,
        HistoricalBarParams::builder()
            .symbols(vec!["AAPL".to_string()])
            .timeframe("1Min".to_string())
            .start("2024-01-03T00:00:00Z".to_string())
            .end("2024-01-04T01:02:03.123456789Z".to_string())
            .limit(1)
            .feed("sip".to_string())
            .currency("USD".to_string())
            .build(),
    )
    .await
    {
        Ok(res) => {
            assert!(!res.is_empty());
            assert_eq!(res.len_total(), 1);
            assert_eq!(res.first_bar("AAPL").unwrap().close, 185.31);
            assert_eq!(res.last_bar("AAPL").unwrap().open, 185.31);
            assert_eq!(
                res.first_bar("AAPL").unwrap().timestamp,
                "2024-01-03T00:00:00Z"
            );
        }
        Err(e) => panic!("Error getting historical bars: {e}"),
    }
}
/// Parameters for retrieving the latest price bars from the Alpaca API.
///
/// This struct is used to build requests for the most recent price bars
/// for specified stock symbols.
#[derive(Debug, TypedBuilder, Serialize)]
pub struct LatestBarsParams {
    /// List of stock symbols to retrieve the latest bars for.
    /// Will be serialized as a comma-separated string.
    #[serde(serialize_with = "serialize_symbols")]
    pub symbols: Vec<String>,

    /// Data feed to use (e.g., "sip", "iex").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed: Option<String>,

    /// Currency to use for the data (e.g., "USD").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
}

/// Response from the latest bars API endpoint.
///
/// Contains the most recent OHLC (Open, High, Low, Close) bar data for requested symbols.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LatestBarsResponse {
    /// Map of symbol to its most recent price bar.
    /// Each symbol has exactly one bar representing the latest price action.
    pub bars: HashMap<String, Bars>,

    /// Token for pagination to get the next page of results.
    /// Usually absent for "latest" endpoints.
    #[serde(default)]
    pub next_page_token: Option<String>,

    /// Currency used for the price values (e.g., "USD").
    #[serde(default)]
    pub currency: Option<String>,
}

/// Helper methods for accessing latest bars data.
impl LatestBarsResponse {
    /// Get the latest bar for a specific symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the bar for
    ///
    /// # Returns
    /// * The latest bar if the symbol exists, None otherwise
    pub fn bar(&self, symbol: &str) -> Option<&Bars> {
        self.bars.get(symbol)
    }

    /// Get all symbols present in the response.
    ///
    /// # Returns
    /// * An iterator over all symbol strings in the response
    pub fn symbols(&self) -> impl Iterator<Item = &str> {
        self.bars.keys().map(|s| s.as_str())
    }

    /// Get the next page token, filtering out empty strings.
    ///
    /// # Returns
    /// * The next page token if it exists and is not empty, None otherwise
    pub fn next_page_token(&self) -> Option<&str> {
        self.next_page_token.as_deref().filter(|s| !s.is_empty())
    }

    /// Get the currency used for the price values.
    ///
    /// # Returns
    /// * The currency code (e.g., "USD") if available, None otherwise
    pub fn currency(&self) -> Option<&str> {
        self.currency.as_deref()
    }
}

/// Retrieves the latest price bars for specified stock symbols from the Alpaca API.
///
/// This function fetches the most recent OHLC (Open, High, Low, Close) bar
/// for each of the specified stock symbols.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication
/// * `params` - Parameters for the latest bars request
///
/// # Returns
/// * `Result<LatestBarsResponse, Box<dyn std::error::Error>>` - The latest bar data or an error
///
/// # Examples
///
/// let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
/// let params = LatestBarsParams::builder()
///     .symbols(vec!["AAPL".to_string(), "MSFT".to_string()])
///     .feed("iex".to_string())
///     .build();
/// let latest_bars = get_latest_bars(&alpaca, params).await?;
///
pub async fn get_latest_bars(
    alpaca: &Alpaca,
    params: LatestBarsParams,
) -> Result<LatestBarsResponse, Box<dyn std::error::Error>> {
    let endpoint = "/v2/stocks/bars/latest";
    let query_string = serde_qs::to_string(&params)?;
    let endpoint_with_query = format!("{endpoint}?{query_string}");
    let response =
        create_data_request::<()>(alpaca, Method::GET, &endpoint_with_query, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting latest bars failed: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_get_latest_bars() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_latest_bars(
        &alpaca,
        LatestBarsParams::builder()
            .symbols(vec!["AAPL".to_string()])
            .feed("iex".to_string())
            .currency("USD".to_string())
            .build(),
    )
    .await
    {
        Ok(res) => {
            assert!(res.symbols().any(|s| s == "AAPL"));
        }
        Err(e) => panic!("Error getting latest bar: {e}"),
    }
}

/// Response containing trade condition codes and their descriptions.
///
/// This struct maps single character condition codes to their human-readable descriptions.
/// Trade condition codes are used to indicate special circumstances for a trade.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TradeConditionResponse(pub HashMap<char, String>);

impl TradeConditionResponse {
    /// Look up a condition description by its single character code.
    ///
    /// # Arguments
    /// * `code` - The single character condition code (e.g., ' ', '4', 'B', 'T')
    ///
    /// # Returns
    /// * The human-readable description if the code exists, None otherwise
    pub fn describe(&self, code: char) -> Option<&str> {
        self.0.get(&code).map(|s| s.as_str())
    }

    /// Look up a condition description by a string code, taking only the first character.
    ///
    /// This is a convenience method that accepts a string like "B" or "4" and
    /// uses only the first character for the lookup.
    ///
    /// # Arguments
    /// * `code` - A string containing the condition code (only first char is used)
    ///
    /// # Returns
    /// * The human-readable description if the code exists, None otherwise
    pub fn describe_str(&self, code: &str) -> Option<&str> {
        code.chars().next().and_then(|c| self.describe(c))
    }
}
/// Query parameters for condition codes request.
///
/// Used to specify which tape (exchange group) to retrieve condition codes for.
#[derive(Serialize)]
struct CondQuery<'a> {
    /// The tape code (e.g., "A", "B", "C") representing an exchange group.
    pub tape: &'a str,
}

/// Retrieves trade condition codes and their descriptions from the Alpaca API.
///
/// Trade condition codes are single characters that indicate special circumstances
/// for a trade or quote. This function fetches the mapping of these codes to
/// their human-readable descriptions.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication
/// * `ticktype` - The type of tick data ("trade" or "quote")
/// * `tape` - The tape code (e.g., "A", "B", "C") representing an exchange group
///
/// # Returns
/// * `Result<TradeConditionResponse, Box<dyn std::error::Error>>` - The condition codes or an error
///
/// # Examples
///
/// let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
/// let conditions = get_condition_codes(&alpaca, "trade", "A").await?;
/// println!("Code '4' means: {}", conditions.describe('4').unwrap_or("Unknown"));
///
pub async fn get_condition_codes(
    alpaca: &Alpaca,
    ticktype: &str,
    tape: &str,
) -> Result<TradeConditionResponse, Box<dyn std::error::Error>> {
    let endpoint = format!("/v2/stocks/meta/conditions/{ticktype}");
    let query_string = serde_qs::to_string(&CondQuery { tape })?; // "tape=A"
    let endpoint_with_query = format!("{endpoint}?{query_string}");

    let response =
        create_data_request::<()>(alpaca, Method::GET, &endpoint_with_query, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting condition codes failed: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_get_condition_codes() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_condition_codes(&alpaca, "trade", "A").await {
        Ok(res) => {
            assert_eq!(res.describe('4'), Some("Derivatively Priced"));
            assert_eq!(res.describe('Z'), Some("Sold (Out Of Sequence)"))
        }
        Err(e) => panic!("Error getting condition codes: {e}"),
    }
}

/// Response containing exchange codes and their descriptions.
///
/// This struct maps single character exchange codes to their human-readable descriptions.
/// Exchange codes identify different stock exchanges and trading venues.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ExchangeCodesResponse(pub HashMap<char, String>);

impl ExchangeCodesResponse {
    /// Look up an exchange description by its single character code.
    ///
    /// # Arguments
    /// * `code` - The single character exchange code (e.g., 'A', 'P', 'Q')
    ///
    /// # Returns
    /// * The human-readable exchange description if the code exists, None otherwise
    pub fn describe(&self, code: char) -> Option<&str> {
        self.0.get(&code).map(|s| s.as_str())
    }

    /// Look up an exchange description by a string code, taking only the first character.
    ///
    /// This is a convenience method that accepts a string like "A" or "Q" and
    /// uses only the first character for the lookup.
    ///
    /// # Arguments
    /// * `code` - A string containing the exchange code (only first char is used)
    ///
    /// # Returns
    /// * The human-readable exchange description if the code exists, None otherwise
    pub fn describe_str(&self, code: &str) -> Option<&str> {
        code.chars().next().and_then(|c| self.describe(c))
    }
}

/// Retrieves exchange codes and their descriptions from the Alpaca API.
///
/// Exchange codes are single characters that identify different stock exchanges
/// and trading venues. This function fetches the mapping of these codes to
/// their human-readable descriptions.
///
/// Note: There's a typo in the function name ("exchance" instead of "exchange"),
/// but it's kept for backward compatibility.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication
///
/// # Returns
/// * `Result<ExchangeCodesResponse, Box<dyn std::error::Error>>` - The exchange codes or an error
///
/// # Examples
///
/// let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
/// let exchanges = get_exchance_codes(&alpaca).await?;
/// println!("Exchange 'A' is: {}", exchanges.describe('A').unwrap_or("Unknown"));
///
pub async fn get_exchance_codes(
    alpaca: &Alpaca,
) -> Result<ExchangeCodesResponse, Box<dyn std::error::Error>> {
    let endpoint = "/v2/stocks/meta/exchanges";
    let response = create_data_request::<()>(alpaca, Method::GET, endpoint, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting exchange codes failed: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_get_exchange_codes() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_exchance_codes(&alpaca).await {
        Ok(res) => {
            assert_eq!(res.describe('A'), Some("NYSE American (AMEX)"));
            assert_eq!(res.describe('Z'), Some("Cboe BZ"))
        }
        Err(e) => panic!("Error getting exchange codes: {e}"),
    }
}
/// Parameters for retrieving historical quotes data from the Alpaca API.
///
/// This struct is used to build requests for historical bid/ask quotes
/// for specified stock symbols.
#[derive(Debug, TypedBuilder, Serialize)]
pub struct HistoricalQuotesParams {
    /// List of stock symbols to retrieve quote data for.
    /// Will be serialized as a comma-separated string.
    #[serde(serialize_with = "serialize_symbols")]
    pub symbols: Vec<String>,

    /// Start time for the data query in ISO 8601 format.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<String>,

    /// End time for the data query in ISO 8601 format.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<String>,

    /// Maximum number of quotes to return.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,

    /// Query for data as of this date (for historical snapshots).
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asof: Option<String>,

    /// Data feed to use (e.g., "sip", "iex").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed: Option<String>,

    /// Currency to use for the data (e.g., "USD").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,

    /// Token for pagination to get the next page of results.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_token: Option<String>,

    /// Sort order for results (e.g., "asc", "desc").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<String>,
}

/// Response from the historical quotes API endpoint.
///
/// Contains bid/ask quote data for requested symbols, organized by symbol.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoricalQuotes {
    /// Map of symbol to a vector of quotes.
    /// Each symbol has a list of quotes representing the bid/ask data over time.
    pub quotes: HashMap<String, Vec<Quotes>>,

    /// Currency used for the price values (e.g., "USD").
    #[serde(default)]
    pub currency: Option<String>,

    /// Token for pagination to get the next page of results.
    pub next_page_token: Option<String>,
}

/// Represents a single bid/ask quote.
///
/// Contains information about the best bid and ask prices, sizes, and exchanges
/// at a specific point in time.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Quotes {
    /// Timestamp in RFC-3339 format when the quote was recorded.
    #[serde(rename = "t")]
    pub timestamp: String,

    /// Exchange code for the best bid.
    #[serde(rename = "bx")]
    pub bid_exchange: String,

    /// Best bid price.
    #[serde(rename = "bp")]
    pub bid_price: f64,

    /// Size of the best bid (number of shares).
    #[serde(rename = "bs")]
    pub bid_size: u64,

    /// Exchange code for the best ask.
    #[serde(rename = "ax")]
    pub ask_exchange: String,

    /// Best ask price.
    #[serde(rename = "ap")]
    pub ask_price: f64,

    /// Size of the best ask (number of shares).
    #[serde(rename = "as")]
    pub ask_size: u64,

    /// Condition flags for the quote.
    #[serde(rename = "c")]
    pub condition_flags: Vec<String>,

    /// Exchange code where the quote was recorded.
    #[serde(rename = "z")]
    pub exchange: String,
}
/// Methods for accessing and manipulating historical quotes data.
impl HistoricalQuotes {
    /// Get all quotes for a specific symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve quotes for
    ///
    /// # Returns
    /// * A vector of quotes if the symbol exists, None otherwise
    pub fn get_symbol_quotes(&self, symbol: &str) -> Option<&Vec<Quotes>> {
        self.quotes.get(symbol)
    }

    /// Get all symbols present in the response.
    ///
    /// # Returns
    /// * A vector of all symbols in the response
    pub fn symbols(&self) -> Vec<&String> {
        self.quotes.keys().collect()
    }

    /// Check if the response contains data for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to check
    ///
    /// # Returns
    /// * `true` if the symbol exists in the response, `false` otherwise
    pub fn has_symbol(&self, symbol: &str) -> bool {
        self.quotes.contains_key(symbol)
    }

    /// Get the most recent quote for a symbol (by last element in Vec).
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the latest quote for
    ///
    /// # Returns
    /// * The most recent quote if the symbol exists and has quotes, None otherwise
    pub fn get_last_quote(&self, symbol: &str) -> Option<&Quotes> {
        self.quotes.get(symbol)?.last()
    }

    /// Get all bid prices for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve bid prices for
    ///
    /// # Returns
    /// * A vector of bid prices for the symbol, empty if symbol doesn't exist
    pub fn get_bid_prices(&self, symbol: &str) -> Vec<f64> {
        self.quotes
            .get(symbol)
            .map(|qs| qs.iter().map(|q| q.bid_price).collect())
            .unwrap_or_default()
    }

    /// Get all ask prices for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve ask prices for
    ///
    /// # Returns
    /// * A vector of ask prices for the symbol, empty if symbol doesn't exist
    pub fn get_ask_prices(&self, symbol: &str) -> Vec<f64> {
        self.quotes
            .get(symbol)
            .map(|qs| qs.iter().map(|q| q.ask_price).collect())
            .unwrap_or_default()
    }

    /// Get all timestamps for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve timestamps for
    ///
    /// # Returns
    /// * A vector of timestamp strings for the symbol, empty if symbol doesn't exist
    pub fn get_timestamps(&self, symbol: &str) -> Vec<&str> {
        self.quotes
            .get(symbol)
            .map(|qs| qs.iter().map(|q| q.timestamp.as_str()).collect())
            .unwrap_or_default()
    }

    /// Check if there's another page of data available.
    ///
    /// # Returns
    /// * `true` if there's a non-empty next page token, `false` otherwise
    pub fn has_next_page(&self) -> bool {
        self.next_page_token
            .as_ref()
            .map(|s| !s.is_empty())
            .unwrap_or(false)
    }
}

/// Retrieves historical quote data from the Alpaca API.
///
/// This function fetches historical bid/ask quotes for specified stock symbols,
/// providing insight into the market's order book over time.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication
/// * `params` - Parameters for the historical quotes request
///
/// # Returns
/// * `Result<HistoricalQuotes, Box<dyn std::error::Error>>` - The quote data or an error
///
/// # Examples
///
/// let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
/// let params = HistoricalQuotesParams::builder()
///     .symbols(vec!["AAPL".to_string()])
///     .start("2024-01-03T00:00:00Z".to_string())
///     .end("2024-01-03T01:00:00Z".to_string())
///     .limit(100)
///     .build();
/// let quotes = get_historical_quotes(&alpaca, params).await?;
///
pub async fn get_historical_quotes(
    alpaca: &Alpaca,
    params: HistoricalQuotesParams,
) -> Result<HistoricalQuotes, Box<dyn std::error::Error>> {
    let endpoint = "/v2/stocks/quotes";
    let query_string = serde_qs::to_string(&params)?;
    let endpoint_with_query = format!("{endpoint}?{query_string}");
    let response =
        create_data_request::<()>(alpaca, Method::GET, &endpoint_with_query, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting historical quotes failed: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_get_historical_quotes() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_historical_quotes(
        &alpaca,
        HistoricalQuotesParams::builder()
            .symbols(vec!["AAPL".parse().unwrap()])
            .start("2024-01-03T00:00:00Z".to_string())
            .end("2024-01-04T01:02:03.123456789Z".to_string())
            .limit(1)
            .feed("iex".to_string())
            .build(),
    )
    .await
    {
        Ok(res) => {
            assert!(!res.quotes.is_empty());
            assert_eq!(res.get_bid_prices("AAPL").first(), Some(184.42).as_ref());
        }
        Err(e) => panic!("Error getting historical quotes: {e}"),
    }
}

/// Parameters for retrieving the latest quotes from the Alpaca API.
///
/// This struct is used to build requests for the most recent bid/ask quotes
/// for specified stock symbols.
#[derive(Debug, TypedBuilder, Serialize)]
pub struct LatestQuotesParams {
    /// List of stock symbols to retrieve the latest quotes for.
    /// Will be serialized as a comma-separated string.
    #[serde(serialize_with = "serialize_symbols")]
    pub symbols: Vec<String>,

    /// Data feed to use (e.g., "sip", "iex").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed: Option<String>,

    /// Currency to use for the data (e.g., "USD").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
}

/// Response from the latest quotes API endpoint.
///
/// Contains the most recent bid/ask quote data for requested symbols.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LatestQuotes {
    /// Map of symbol to its most recent quote.
    /// Each symbol has exactly one quote representing the latest bid/ask data.
    pub quotes: HashMap<String, Quotes>,

    /// Currency used for the price values (e.g., "USD").
    #[serde(default)]
    pub currency: Option<String>,
}

/// Helper methods for accessing latest quotes data.
impl LatestQuotes {
    /// Get the latest quote for a specific symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the quote for
    ///
    /// # Returns
    /// * The latest quote if the symbol exists, None otherwise
    pub fn get_symbol_quote(&self, symbol: &str) -> Option<&Quotes> {
        self.quotes.get(symbol)
    }

    /// Get all symbols present in the response.
    ///
    /// # Returns
    /// * A vector of all symbols in the response
    pub fn symbols(&self) -> Vec<&String> {
        self.quotes.keys().collect()
    }

    /// Check if the response contains data for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to check
    ///
    /// # Returns
    /// * `true` if the symbol exists in the response, `false` otherwise
    pub fn has_symbol(&self, symbol: &str) -> bool {
        self.quotes.contains_key(symbol)
    }

    /// Get the latest quote for a symbol (alias for get_symbol_quote).
    ///
    /// This method is kept for API compatibility with HistoricalQuotes.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the quote for
    ///
    /// # Returns
    /// * The latest quote if the symbol exists, None otherwise
    pub fn get_last_quote(&self, symbol: &str) -> Option<&Quotes> {
        // kept for API compatibility; same as get_symbol_quote now
        self.quotes.get(symbol)
    }

    /// Get the bid price for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the bid price for
    ///
    /// # Returns
    /// * The bid price if the symbol exists, None otherwise
    pub fn get_bid_price(&self, symbol: &str) -> Option<f64> {
        self.quotes.get(symbol).map(|q| q.bid_price)
    }

    /// Get the ask price for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the ask price for
    ///
    /// # Returns
    /// * The ask price if the symbol exists, None otherwise
    pub fn get_ask_price(&self, symbol: &str) -> Option<f64> {
        self.quotes.get(symbol).map(|q| q.ask_price)
    }

    /// Get the timestamp for a symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the timestamp for
    ///
    /// # Returns
    /// * The timestamp string if the symbol exists, None otherwise
    pub fn get_timestamp(&self, symbol: &str) -> Option<&str> {
        self.quotes.get(symbol).map(|q| q.timestamp.as_str())
    }
}

/// Retrieves the latest quotes for specified stock symbols from the Alpaca API.
///
/// This function fetches the most recent bid/ask quotes for each of the specified
/// stock symbols, providing the current state of the market's order book.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication
/// * `params` - Parameters for the latest quotes request
///
/// # Returns
/// * `Result<LatestQuotes, Box<dyn std::error::Error>>` - The latest quote data or an error
///
/// # Examples
///
/// let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
/// let params = LatestQuotesParams::builder()
///     .symbols(vec!["AAPL".to_string(), "MSFT".to_string()])
///     .feed("iex".to_string())
///     .build();
/// let latest_quotes = get_latest_quotes(&alpaca, params).await?;
///
pub async fn get_latest_quotes(
    alpaca: &Alpaca,
    params: LatestQuotesParams,
) -> Result<LatestQuotes, Box<dyn std::error::Error>> {
    let endpoint = "/v2/stocks/quotes/latest";
    let query_string = serde_qs::to_string(&params)?;
    let endpoint_with_query = format!("{endpoint}?{query_string}");
    let response =
        create_data_request::<()>(alpaca, Method::GET, &endpoint_with_query, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting latest quotes failed: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_get_latest_quotes() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_latest_quotes(
        &alpaca,
        LatestQuotesParams::builder()
            .symbols(vec!["AAPL".parse().unwrap()])
            .feed("iex".to_string())
            .currency("USD".to_string())
            .build(),
    )
    .await
    {
        Ok(res) => {
            assert!(res.has_symbol("AAPL"));
        }
        Err(e) => panic!("Error getting latest quotes: {e}"),
    }
}

/// Parameters for retrieving historical trades data from the Alpaca API.
///
/// This struct is used to build requests for historical executed trades
/// for specified stock symbols.
#[derive(Debug, TypedBuilder, Serialize)]
pub struct HistoricalTradesParams {
    /// List of stock symbols to retrieve trade data for.
    /// Will be serialized as a comma-separated string.
    #[serde(serialize_with = "serialize_symbols")]
    pub symbols: Vec<String>,

    /// Start time for the data query in ISO 8601 format.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<String>,

    /// End time for the data query in ISO 8601 format.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<String>,

    /// Maximum number of trades to return.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,

    /// Query for data as of this date (for historical snapshots).
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asof: Option<String>,

    /// Data feed to use (e.g., "sip", "iex").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed: Option<String>,

    /// Currency to use for the data (e.g., "USD").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,

    /// Token for pagination to get the next page of results.
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_token: Option<String>,

    /// Sort order for results (e.g., "asc", "desc").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<String>,
}

/// Response from the historical trades API endpoint.
///
/// Contains executed trade data for requested symbols, organized by symbol.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoricalTrades {
    /// Map of symbol to a vector of trades.
    /// Each symbol has a list of trades representing executed transactions over time.
    pub trades: HashMap<String, Vec<Trades>>,

    /// Currency used for the price values (e.g., "USD").
    #[serde(default)]
    pub currency: Option<String>,

    /// Token for pagination to get the next page of results.
    pub next_page_token: Option<String>,
}
/// Methods for accessing and manipulating historical trades data.
impl HistoricalTrades {
    /// Get all trades for a specific symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve trades for
    ///
    /// # Returns
    /// * A vector of trades if the symbol exists, None otherwise
    pub fn trades_for_symbol(&self, symbol: &str) -> Option<&Vec<Trades>> {
        self.trades.get(symbol)
    }

    /// Get the first (earliest) trade for a specific symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the first trade for
    ///
    /// # Returns
    /// * The first trade if the symbol exists and has trades, None otherwise
    pub fn first_trade(&self, symbol: &str) -> Option<&Trades> {
        self.trades.get(symbol)?.first()
    }

    /// Get the last (most recent) trade for a specific symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the last trade for
    ///
    /// # Returns
    /// * The last trade if the symbol exists and has trades, None otherwise
    pub fn last_trade(&self, symbol: &str) -> Option<&Trades> {
        self.trades.get(symbol)?.last()
    }

    /// Flatten all trades into a single vector with symbol references.
    ///
    /// This method provides a convenient way to iterate through all trades
    /// across all symbols, with each item containing both the symbol and the trade.
    ///
    /// # Returns
    /// * A vector of (symbol, trade) tuples containing all trades
    pub fn all_trades(&self) -> Vec<(&String, &Trades)> {
        self.trades
            .iter()
            .flat_map(|(sym, trades)| trades.iter().map(move |t| (sym, t)))
            .collect()
    }

    /// Count the total number of trades across all symbols.
    ///
    /// # Returns
    /// * The sum of trade counts for all symbols
    pub fn total_trade_count(&self) -> usize {
        self.trades.values().map(|v| v.len()).sum()
    }

    /// Get a map of symbol to number of trades.
    ///
    /// # Returns
    /// * A HashMap mapping each symbol to its trade count
    pub fn counts_per_symbol(&self) -> HashMap<&String, usize> {
        self.trades
            .iter()
            .map(|(sym, trades)| (sym, trades.len()))
            .collect()
    }
}
/// Represents a single executed trade.
///
/// Contains information about a specific trade transaction including
/// price, size, exchange, and condition flags.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Trades {
    /// Timestamp in RFC-3339 format when the trade was executed.
    #[serde(rename = "t")]
    pub timestamp: String,

    /// Exchange where the trade was executed.
    #[serde(rename = "x")]
    pub exchange: String,

    /// Price at which the trade was executed.
    #[serde(rename = "p")]
    pub price: f64,

    /// Size of the trade (number of shares).
    #[serde(rename = "s")]
    pub size: u64,

    /// Unique identifier for the trade.
    #[serde(rename = "i")]
    pub trade_id: u64,

    /// Condition flags indicating special circumstances for the trade.
    #[serde(rename = "c")]
    pub condition_flags: Vec<String>,

    /// Exchange code where the trade was executed.
    #[serde(rename = "z")]
    pub exchange_code: String,

    /// Optional update timestamp if the trade was updated.
    #[serde(rename = "u")]
    #[serde(default)]
    pub update: Option<String>,
}

/// Retrieves historical trade data from the Alpaca API.
///
/// This function fetches historical executed trades for specified stock symbols,
/// providing insight into actual market transactions over time.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication
/// * `params` - Parameters for the historical trades request
///
/// # Returns
/// * `Result<HistoricalTrades, Box<dyn std::error::Error>>` - The trade data or an error
///
/// # Examples
///
/// let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
/// let params = HistoricalTradesParams::builder()
///     .symbols(vec!["AAPL".to_string()])
///     .start("2024-01-03T00:00:00Z".to_string())
///     .end("2024-01-03T01:00:00Z".to_string())
///     .limit(100)
///     .build();
/// let trades = get_historical_trades(&alpaca, params).await?;
///
pub async fn get_historical_trades(
    alpaca: &Alpaca,
    params: HistoricalTradesParams,
) -> Result<HistoricalTrades, Box<dyn std::error::Error>> {
    let endpoint = "/v2/stocks/trades";
    let query_string = serde_qs::to_string(&params)?;
    let endpoint_with_query = format!("{endpoint}?{query_string}");
    let response =
        create_data_request::<()>(alpaca, Method::GET, &endpoint_with_query, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting historical trades failed: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_get_hisotrical_trades() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_historical_trades(
        &alpaca,
        HistoricalTradesParams::builder()
            .symbols(vec!["AAPL".parse().unwrap()])
            .start("2024-01-03T00:00:00Z".to_string())
            .end("2024-01-04T01:02:03.123456789Z".to_string())
            .limit(1)
            .feed("iex".to_string())
            .build(),
    )
    .await
    {
        Ok(res) => {
            assert!(res.first_trade("AAPL").is_some());
            assert_eq!(res.first_trade("AAPL").unwrap().price, 184.37);
            assert_eq!(
                res.last_trade("AAPL").unwrap().timestamp,
                "2024-01-03T13:00:13.51278393Z"
            );
        }
        Err(e) => panic!("Error getting historical trades: {e}"),
    }
}

/// Parameters for retrieving the latest trades from the Alpaca API.
///
/// This struct is used to build requests for the most recent executed trades
/// for specified stock symbols.
#[derive(Debug, TypedBuilder, Serialize)]
pub struct LatestTradesParams {
    /// List of stock symbols to retrieve the latest trades for.
    /// Will be serialized as a comma-separated string.
    #[serde(serialize_with = "serialize_symbols")]
    pub symbols: Vec<String>,

    /// Data feed to use (e.g., "sip", "iex").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed: Option<String>,

    /// Currency to use for the data (e.g., "USD").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
}

/// Response from the latest trades API endpoint.
///
/// Contains the most recent executed trade data for requested symbols.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LatestTrades {
    /// Map of symbol to its most recent trade.
    /// Each symbol has exactly one trade representing the latest executed transaction.
    pub trades: HashMap<String, Trades>,

    /// Currency used for the price values (e.g., "USD").
    #[serde(default)]
    pub currency: Option<String>,
}

/// Helper methods for accessing latest trades data.
impl LatestTrades {
    /// Get the latest trade for a specific symbol.
    ///
    /// # Arguments
    /// * `symbol` - The stock symbol to retrieve the trade for
    ///
    /// # Returns
    /// * The latest trade if the symbol exists, None otherwise
    pub fn trade_for_symbol(&self, symbol: &str) -> Option<&Trades> {
        self.trades.get(symbol)
    }

    /// Flatten all trades into a single vector with symbol references.
    ///
    /// This method provides a convenient way to iterate through all trades
    /// across all symbols, with each item containing both the symbol and the trade.
    ///
    /// # Returns
    /// * A vector of (symbol, trade) tuples containing all trades
    pub fn all_trades(&self) -> Vec<(&String, &Trades)> {
        self.trades.iter().collect()
    }

    /// Count the total number of trades (will equal number of symbols).
    ///
    /// Since this is a "latest trades" response, each symbol has exactly one trade.
    ///
    /// # Returns
    /// * The number of symbols/trades in the response
    pub fn total_trade_count(&self) -> usize {
        self.trades.len()
    }

    /// Get a map of symbol to trade count (always 1 for each symbol).
    ///
    /// This method is kept for API compatibility with HistoricalTrades.
    ///
    /// # Returns
    /// * A HashMap mapping each symbol to 1 (the count of trades per symbol)
    pub fn counts_per_symbol(&self) -> HashMap<&String, usize> {
        self.trades.keys().map(|sym| (sym, 1)).collect()
    }
}

/// Retrieves the latest trades for specified stock symbols from the Alpaca API.
///
/// This function fetches the most recent executed trade for each of the specified
/// stock symbols, providing the current state of market transactions.
///
/// # Arguments
/// * `alpaca` - The Alpaca client instance with authentication
/// * `params` - Parameters for the latest trades request
///
/// # Returns
/// * `Result<LatestTrades, Box<dyn std::error::Error>>` - The latest trade data or an error
///
/// # Examples
///
/// let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
/// let params = LatestTradesParams::builder()
///     .symbols(vec!["AAPL".to_string(), "MSFT".to_string()])
///     .feed("iex".to_string())
///     .build();
/// let latest_trades = get_latest_trades(&alpaca, params).await?;
///
pub async fn get_latest_trades(
    alpaca: &Alpaca,
    params: LatestTradesParams,
) -> Result<LatestTrades, Box<dyn std::error::Error>> {
    let endpoint = "/v2/stocks/trades/latest";
    let query_string = serde_qs::to_string(&params)?;
    let endpoint_with_query = format!("{endpoint}?{query_string}");
    let response =
        create_data_request::<()>(alpaca, Method::GET, &endpoint_with_query, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting latest trades failed: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_get_latest_trades() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_latest_trades(
        &alpaca,
        LatestTradesParams::builder()
            .symbols(vec!["AAPL".parse().unwrap()])
            .feed("iex".to_string())
            .currency("USD".to_string())
            .build(),
    )
    .await
    {
        Ok(res) => {
            assert!(res.trade_for_symbol("AAPL").is_some());
        }
        Err(e) => panic!("Error getting latest trades: {e}"),
    }
}

/// Parameters for retrieving market snapshots from the Alpaca API.
///
/// This struct is used to build requests for comprehensive market snapshots
/// that include bars, quotes, and trades for specified stock symbols.
#[derive(Debug, TypedBuilder, Serialize)]
pub struct SnapshotsParams {
    /// List of stock symbols to retrieve snapshots for.
    /// Will be serialized as a comma-separated string.
    #[serde(serialize_with = "serialize_symbols")]
    pub symbols: Vec<String>,

    /// Data feed to use (e.g., "sip", "iex").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feed: Option<String>,

    /// Currency to use for the data (e.g., "USD").
    #[builder(default, setter(strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
}

/// Response from the snapshots API endpoint.
///
/// Contains comprehensive market data for requested symbols, including
/// bars, quotes, and trades in a single response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnapshotResponse(pub HashMap<String, StockData>);

/// Comprehensive market data for a single stock symbol.
///
/// Contains various data points including daily and minute bars,
/// latest quote and trade information, and previous day's data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StockData {
    /// The current day's OHLC bar data.
    pub dailyBar: Bars,

    /// The latest bid/ask quote information.
    pub latestQuote: Quotes,

    /// The latest executed trade.
    pub latestTrade: Trades,

    /// The most recent 1-minute OHLC bar.
    pub minuteBar: Bars,

    /// The previous day's OHLC bar data.
    pub prevDailyBar: Bars,
}

impl SnapshotResponse {
    /// Get StockData for a symbol if it exists
    pub fn get(&self, symbol: &str) -> Option<&StockData> {
        self.0.get(symbol)
    }

    /// Mutable access to StockData
    pub fn get_mut(&mut self, symbol: &str) -> Option<&mut StockData> {
        self.0.get_mut(symbol)
    }

    /// List all symbols
    pub fn symbols(&self) -> Vec<&String> {
        self.0.keys().collect()
    }

    /// Return all StockData entries
    pub fn all(&self) -> impl Iterator<Item = (&String, &StockData)> {
        self.0.iter()
    }
}

impl StockData {
    /// Get the latest trade price
    pub fn latest_price(&self) -> f64 {
        self.latestTrade.price
    }

    /// Get the spread between bid and ask
    pub fn spread(&self) -> f64 {
        self.latestQuote.ask_price - self.latestQuote.bid_price
    }

    /// Get daily OHLC data as tuple
    pub fn daily_ohlc(&self) -> (f64, f64, f64, f64) {
        (
            self.dailyBar.open,
            self.dailyBar.high,
            self.dailyBar.low,
            self.dailyBar.close,
        )
    }

    /// Check if price is above previous daily close
    pub fn is_above_prev_close(&self) -> bool {
        self.latestTrade.price > self.prevDailyBar.close
    }
}

pub async fn get_snapshots(
    alpaca: &Alpaca,
    params: SnapshotsParams,
) -> Result<SnapshotResponse, Box<dyn std::error::Error>> {
    let endpoint = "/v2/stocks/snapshots";
    let query_string = serde_qs::to_string(&params)?;
    let endpoint_with_query = format!("{endpoint}?{query_string}");
    let response =
        create_data_request::<()>(alpaca, Method::GET, &endpoint_with_query, None).await?;
    if !response.status().is_success() {
        let text = response.text().await.unwrap_or_default();
        return Err(format!("Getting snapshot: {text}").into());
    }
    Ok(response.json().await?)
}

#[tokio::test]
async fn test_get_snapshots() {
    let alpaca = Alpaca::from_env(TradingType::Paper).unwrap();
    match get_snapshots(
        &alpaca,
        SnapshotsParams::builder()
            .symbols(vec!["AAPL".parse().unwrap()])
            .feed("iex".to_string())
            .currency("USD".to_string())
            .build(),
    )
    .await
    {
        Ok(res) => {
            assert!(res.get("AAPL").is_some());
        }
        Err(e) => panic!("Error getting snapshots: {e}"),
    }
}