digdigdig3 0.1.19

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
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
//! Alpaca connector implementation

use async_trait::async_trait;
use reqwest::Client;
use std::collections::HashMap;
use serde_json::{json, Value};

use crate::core::types::*;
use crate::core::traits::*;
use crate::core::utils::precision::PrecisionCache;

use super::endpoints::*;
use super::auth::*;
use super::parser::*;

// ─────────────────────────────────────────────────────────────────────────────
// Helper: map TimeInForce → Alpaca time_in_force string
// ─────────────────────────────────────────────────────────────────────────────

fn tif_str(tif: TimeInForce) -> &'static str {
    match tif {
        TimeInForce::Gtc => "gtc",
        TimeInForce::Ioc => "ioc",
        TimeInForce::Fok => "fok",
        TimeInForce::PostOnly => "gtc", // Alpaca has no post-only TIF — caller should not reach here
        TimeInForce::Gtd => "gtc", // Unsupported, caller guards this
        TimeInForce::GoodTilBlock { .. } => "gtc",
    }
}

/// Alpaca connector
///
/// Supports both market data and trading operations for US stocks.
pub struct AlpacaConnector {
    client: Client,
    auth: AlpacaAuth,
    endpoints: AlpacaEndpoints,
    testnet: bool,
    feed: DataFeed,
    precision: PrecisionCache,
}

/// Data feed selection
#[derive(Debug, Clone, Copy, Default)]
pub enum DataFeed {
    /// IEX exchange only (~2.5% market volume) - FREE
    #[default]
    Iex,
    /// All US exchanges (100% market volume) - PAID
    Sip,
}

impl AlpacaConnector {
    /// Create new connector (paper trading by default)
    pub fn new(auth: AlpacaAuth) -> Self {
        Self {
            client: Client::new(),
            auth,
            endpoints: AlpacaEndpoints::paper(),
            testnet: true, // Paper trading is testnet
            feed: DataFeed::Iex,
            precision: PrecisionCache::new(),
        }
    }

    /// Create connector with custom environment
    pub fn with_env(auth: AlpacaAuth, live: bool) -> Self {
        let endpoints = if live {
            AlpacaEndpoints::live()
        } else {
            AlpacaEndpoints::paper()
        };

        Self {
            client: Client::new(),
            auth,
            endpoints,
            testnet: !live,
            feed: DataFeed::Iex,
            precision: PrecisionCache::new(),
        }
    }

    /// Create connector from environment variables
    pub fn from_env() -> Self {
        Self::new(AlpacaAuth::from_env())
    }

    /// Create public crypto-only connector (no API keys required)
    ///
    /// This connector can access crypto market data without authentication.
    /// All crypto endpoints on Alpaca work without API keys.
    ///
    /// Limitations:
    /// - Only crypto symbols work (e.g., BTC/USD, ETH/USD)
    /// - Stock data, trading, and account operations require auth
    pub fn crypto_only() -> Self {
        Self {
            client: Client::new(),
            auth: AlpacaAuth::none(),
            endpoints: AlpacaEndpoints::live(),
            testnet: false,
            feed: DataFeed::Iex,
            precision: PrecisionCache::new(),
        }
    }

    /// Set data feed (IEX free vs SIP paid)
    pub fn with_feed(mut self, feed: DataFeed) -> Self {
        self.feed = feed;
        self
    }

    /// Internal: Make GET request to Trading API
    async fn get_trading(
        &self,
        endpoint: AlpacaEndpoint,
        params: HashMap<String, String>,
    ) -> ExchangeResult<Value> {
        let (path, _) = endpoint.path();
        let url = format!("{}{}", self.endpoints.trading_base, path);

        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);

        let mut request = self.client.get(&url);

        // Add headers
        for (key, value) in headers {
            request = request.header(key, value);
        }

        // Add query params
        if !params.is_empty() {
            request = request.query(&params);
        }

        let response = request.send().await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Api {
                code: status.as_u16() as i32,
                message: error_text,
            });
        }

        response.json().await
            .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
    }

    /// Internal: Make POST request to Trading API
    async fn post_trading(
        &self,
        endpoint: AlpacaEndpoint,
        body: Value,
    ) -> ExchangeResult<Value> {
        let (path, _) = endpoint.path();
        let url = format!("{}{}", self.endpoints.trading_base, path);

        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);

        let mut request = self.client.post(&url);

        // Add headers
        for (key, value) in headers {
            request = request.header(key, value);
        }

        // Add JSON body
        request = request.json(&body);

        let response = request.send().await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Api {
                code: status.as_u16() as i32,
                message: error_text,
            });
        }

        response.json().await
            .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
    }

    /// Internal: Make DELETE request to Trading API
    async fn delete_trading(
        &self,
        endpoint: AlpacaEndpoint,
        params: HashMap<String, String>,
    ) -> ExchangeResult<Value> {
        let (path, _) = endpoint.path();
        let url = format!("{}{}", self.endpoints.trading_base, path);

        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);

        let mut request = self.client.delete(&url);

        // Add headers
        for (key, value) in headers {
            request = request.header(key, value);
        }

        // Add query params
        if !params.is_empty() {
            request = request.query(&params);
        }

        let response = request.send().await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Api {
                code: status.as_u16() as i32,
                message: error_text,
            });
        }

        response.json().await
            .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
    }

    /// Internal: DELETE that accepts 207 Multi-Status (cancel-all returns 207)
    async fn delete_trading_multi(
        &self,
        endpoint: AlpacaEndpoint,
        params: HashMap<String, String>,
    ) -> ExchangeResult<Value> {
        let (path, _) = endpoint.path();
        let url = format!("{}{}", self.endpoints.trading_base, path);

        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);

        let mut request = self.client.delete(&url);
        for (key, value) in headers {
            request = request.header(key, value);
        }
        if !params.is_empty() {
            request = request.query(&params);
        }

        let response = request.send().await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        let status = response.status();
        // 200 OK, 207 Multi-Status are both acceptable for cancel-all
        if !status.is_success() && status.as_u16() != 207 {
            let error_text = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Api {
                code: status.as_u16() as i32,
                message: error_text,
            });
        }

        // Body may be empty on full success
        let text = response.text().await
            .map_err(|e| ExchangeError::Network(format!("Response read failed: {}", e)))?;

        if text.is_empty() {
            Ok(Value::Array(vec![]))
        } else {
            serde_json::from_str(&text)
                .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
        }
    }

    /// Internal: PATCH request to Trading API (amend order)
    async fn patch_trading(
        &self,
        endpoint: AlpacaEndpoint,
        body: Value,
    ) -> ExchangeResult<Value> {
        let (path, _) = endpoint.path();
        let url = format!("{}{}", self.endpoints.trading_base, path);

        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);

        let mut request = self.client.patch(&url);
        for (key, value) in headers {
            request = request.header(key, value);
        }
        request = request.json(&body);

        let response = request.send().await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Api {
                code: status.as_u16() as i32,
                message: error_text,
            });
        }

        response.json().await
            .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
    }

    /// Internal: Make GET request to Market Data API
    async fn get_market_data(
        &self,
        endpoint: AlpacaEndpoint,
        mut params: HashMap<String, String>,
    ) -> ExchangeResult<Value> {
        let (path, _) = endpoint.path();
        let url = format!("{}{}", self.endpoints.market_data_base, path);

        // Add feed parameter for stock data (not needed for crypto)
        if !path.contains("/crypto/") {
            let feed_str = match self.feed {
                DataFeed::Iex => "iex",
                DataFeed::Sip => "sip",
            };
            params.insert("feed".to_string(), feed_str.to_string());
        }

        let mut headers = HashMap::new();
        // Only add auth headers if we have credentials
        if self.auth.has_credentials() {
            self.auth.sign_headers(&mut headers);
        }

        let mut request = self.client.get(&url);

        // Add headers
        for (key, value) in headers {
            request = request.header(key, value);
        }

        // Add query params
        if !params.is_empty() {
            request = request.query(&params);
        }

        let response = request.send().await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Api {
                code: status.as_u16() as i32,
                message: error_text,
            });
        }

        response.json().await
            .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
    }

    // ═══════════════════════════════════════════════════════════════════
    // EXTENDED METHODS — Watchlists
    // ═══════════════════════════════════════════════════════════════════

    /// List all watchlists — `GET /v2/watchlists`
    pub async fn get_watchlists(&self) -> ExchangeResult<Value> {
        self.get_trading(AlpacaEndpoint::Watchlists, HashMap::new()).await
    }

    /// Create watchlist — `POST /v2/watchlists`
    ///
    /// `name` is the unique watchlist name; `symbols` is an optional list of tickers.
    pub async fn create_watchlist(&self, name: &str, symbols: Vec<&str>) -> ExchangeResult<Value> {
        let body = json!({
            "name": name,
            "symbols": symbols,
        });
        self.post_trading(AlpacaEndpoint::Watchlists, body).await
    }

    /// Get watchlist by ID — `GET /v2/watchlists/{id}`
    pub async fn get_watchlist(&self, id: &str) -> ExchangeResult<Value> {
        self.get_trading(AlpacaEndpoint::WatchlistById(id.to_string()), HashMap::new()).await
    }

    /// Update watchlist — `PUT /v2/watchlists/{id}`
    ///
    /// Replaces the name and/or symbols list of an existing watchlist.
    pub async fn update_watchlist(
        &self,
        id: &str,
        name: Option<&str>,
        symbols: Option<Vec<&str>>,
    ) -> ExchangeResult<Value> {
        let mut body = json!({});
        if let Some(n) = name {
            body["name"] = json!(n);
        }
        if let Some(s) = symbols {
            body["symbols"] = json!(s);
        }
        let (path, _) = AlpacaEndpoint::WatchlistById(id.to_string()).path();
        let url = format!("{}{}", self.endpoints.trading_base, path);
        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);
        let mut request = self.client.put(&url);
        for (key, value) in headers {
            request = request.header(key, value);
        }
        request = request.json(&body);
        let response = request.send().await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;
        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Api { code: status.as_u16() as i32, message: error_text });
        }
        response.json().await
            .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
    }

    /// Delete watchlist — `DELETE /v2/watchlists/{id}`
    pub async fn delete_watchlist(&self, id: &str) -> ExchangeResult<Value> {
        self.delete_trading(AlpacaEndpoint::WatchlistById(id.to_string()), HashMap::new()).await
    }

    /// Add symbol to watchlist — `POST /v2/watchlists/{id}`
    pub async fn add_symbol_to_watchlist(&self, id: &str, symbol: &str) -> ExchangeResult<Value> {
        let body = json!({ "symbol": symbol });
        self.post_trading(AlpacaEndpoint::WatchlistAddSymbol(id.to_string()), body).await
    }

    // ═══════════════════════════════════════════════════════════════════
    // EXTENDED METHODS — Positions
    // ═══════════════════════════════════════════════════════════════════

    /// Close all open positions — `DELETE /v2/positions`
    ///
    /// Pass `cancel_orders: true` to cancel open orders before liquidating.
    pub async fn close_all_positions(&self, cancel_orders: bool) -> ExchangeResult<Value> {
        let mut params = HashMap::new();
        params.insert("cancel_orders".to_string(), cancel_orders.to_string());
        self.delete_trading_multi(AlpacaEndpoint::Positions, params).await
    }

    /// Close a single position — `DELETE /v2/positions/{symbol_or_asset_id}`
    ///
    /// Optionally pass `qty` or `percentage` to partially close.
    pub async fn close_position(
        &self,
        symbol_or_asset_id: &str,
        qty: Option<f64>,
        percentage: Option<f64>,
    ) -> ExchangeResult<Value> {
        let mut params = HashMap::new();
        if let Some(q) = qty {
            params.insert("qty".to_string(), q.to_string());
        }
        if let Some(p) = percentage {
            params.insert("percentage".to_string(), p.to_string());
        }
        self.delete_trading(
            AlpacaEndpoint::PositionBySymbol(symbol_or_asset_id.to_string()),
            params,
        ).await
    }

    // ═══════════════════════════════════════════════════════════════════
    // EXTENDED METHODS — Account Configurations
    // ═══════════════════════════════════════════════════════════════════

    /// Get account configurations — `GET /v2/account/configurations`
    pub async fn get_account_configurations(&self) -> ExchangeResult<Value> {
        self.get_trading(AlpacaEndpoint::AccountConfigurations, HashMap::new()).await
    }

    /// Update account configurations — `PATCH /v2/account/configurations`
    ///
    /// Pass a JSON object with only the configuration fields to update.
    pub async fn patch_account_configurations(&self, config: Value) -> ExchangeResult<Value> {
        self.patch_trading(AlpacaEndpoint::AccountConfigurations, config).await
    }

    // ═══════════════════════════════════════════════════════════════════
    // EXTENDED METHODS — Options Chain
    // ═══════════════════════════════════════════════════════════════════

    /// Get options chain for a symbol — `GET /v1beta1/options/chain`
    ///
    /// `underlying_symbol` is required (e.g. `"AAPL"`).
    /// Optional `params`: `expiration_date`, `strike_price_gte`, `strike_price_lte`, `type`.
    pub async fn get_options_chain(
        &self,
        underlying_symbol: &str,
        params: HashMap<String, String>,
    ) -> ExchangeResult<Value> {
        let mut full_params = params;
        full_params.insert("underlying_symbol".to_string(), underlying_symbol.to_string());
        self.get_market_data(AlpacaEndpoint::OptionsChain, full_params).await
    }

    // ═══════════════════════════════════════════════════════════════════
    // EXTENDED METHODS — Screener
    // ═══════════════════════════════════════════════════════════════════

    /// Most active stocks screener — `GET /v1beta1/screener/most-actives`
    ///
    /// Optional `params`: `by` ("trades" or "volume"), `top` (count, default 10).
    pub async fn get_most_actives(&self, params: HashMap<String, String>) -> ExchangeResult<Value> {
        self.get_market_data(AlpacaEndpoint::MostActives, params).await
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: ExchangeIdentity
// ═══════════════════════════════════════════════════════════════════════════

impl ExchangeIdentity for AlpacaConnector {
    fn exchange_id(&self) -> ExchangeId {
        ExchangeId::Alpaca
    }

    fn is_testnet(&self) -> bool {
        self.testnet
    }

    fn supported_account_types(&self) -> Vec<AccountType> {
        // Alpaca is primarily a stock broker - use Spot as the account type
        vec![AccountType::Spot]
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: MarketData
// ═══════════════════════════════════════════════════════════════════════════

#[async_trait]
impl MarketData for AlpacaConnector {
    async fn get_price(
        &self,
        symbol: Symbol,
        _account_type: AccountType,
    ) -> ExchangeResult<Price> {
        let symbol_str = format_symbol(&symbol);

        // Use snapshot endpoint to get latest price
        let mut params = HashMap::new();
        params.insert("symbols".to_string(), symbol_str.clone());

        // Determine if this is a crypto symbol (has "/" in it)
        let is_crypto = symbol_str.contains('/');
        let endpoint = if is_crypto {
            AlpacaEndpoint::CryptoSnapshots
        } else {
            AlpacaEndpoint::StockSnapshots
        };

        let response = self.get_market_data(endpoint, params).await?;

        // For crypto, the response has a "snapshots" wrapper
        let snapshots = if is_crypto {
            response.get("snapshots")
                .ok_or_else(|| ExchangeError::Parse("Missing 'snapshots' field for crypto".to_string()))?
        } else {
            &response
        };

        // Extract snapshot for this symbol
        let snapshot = snapshots
            .get(&symbol_str)
            .ok_or_else(|| ExchangeError::Parse(format!("No snapshot for {}", symbol_str)))?;

        AlpacaParser::parse_price(snapshot)
    }

    async fn get_orderbook(
        &self,
        symbol: Symbol,
        _depth: Option<u16>,
        _account_type: AccountType,
    ) -> ExchangeResult<OrderBook> {
        // Orderbook only available for crypto
        let symbol_str = format_symbol(&symbol);

        // Check if this is a crypto symbol (has "/" in it)
        if !symbol_str.contains('/') {
            return Err(ExchangeError::UnsupportedOperation(
                "Orderbook only available for crypto, not stocks".to_string()
            ));
        }

        let mut params = HashMap::new();
        params.insert("symbols".to_string(), symbol_str.clone());

        let response = self.get_market_data(AlpacaEndpoint::CryptoOrderbooks, params).await?;

        AlpacaParser::parse_orderbook(&response, &symbol_str)
    }

    async fn get_klines(
        &self,
        symbol: Symbol,
        interval: &str,
        limit: Option<u16>,
        _account_type: AccountType,
        _end_time: Option<i64>,
    ) -> ExchangeResult<Vec<Kline>> {
        let symbol_str = format_symbol(&symbol);

        // Map interval to Alpaca format
        // Supported: 1Min, 5Min, 15Min, 30Min, 1Hour, 4Hour, 1Day, 1Week
        let timeframe = match interval {
            "1m" => "1Min",
            "5m" => "5Min",
            "15m" => "15Min",
            "30m" => "30Min",
            "1h" => "1Hour",
            "4h" => "4Hour",
            "1d" => "1Day",
            "1w" => "1Week",
            other => other, // Pass through as-is
        };

        let mut params = HashMap::new();
        params.insert("symbols".to_string(), symbol_str.clone());
        params.insert("timeframe".to_string(), timeframe.to_string());

        if let Some(lim) = limit {
            params.insert("limit".to_string(), lim.to_string());
        } else {
            params.insert("limit".to_string(), "1000".to_string()); // Default limit
        }

        // Determine if this is a crypto symbol (has "/" in it)
        let is_crypto = symbol_str.contains('/');
        let endpoint = if is_crypto {
            AlpacaEndpoint::CryptoBars
        } else {
            AlpacaEndpoint::StockBars
        };

        let response = self.get_market_data(endpoint, params).await?;

        AlpacaParser::parse_klines(&response, &symbol_str)
    }

    async fn get_ticker(
        &self,
        symbol: Symbol,
        _account_type: AccountType,
    ) -> ExchangeResult<Ticker> {
        let symbol_str = format_symbol(&symbol);

        // Use snapshot endpoint
        let mut params = HashMap::new();
        params.insert("symbols".to_string(), symbol_str.clone());

        // Determine if this is a crypto symbol (has "/" in it)
        let is_crypto = symbol_str.contains('/');
        let endpoint = if is_crypto {
            AlpacaEndpoint::CryptoSnapshots
        } else {
            AlpacaEndpoint::StockSnapshots
        };

        let response = self.get_market_data(endpoint, params).await?;

        // For crypto, the response has a "snapshots" wrapper
        let snapshots = if is_crypto {
            response.get("snapshots")
                .ok_or_else(|| ExchangeError::Parse("Missing 'snapshots' field for crypto".to_string()))?
        } else {
            &response
        };

        // Extract snapshot for this symbol
        let snapshot = snapshots
            .get(&symbol_str)
            .ok_or_else(|| ExchangeError::Parse(format!("No snapshot for {}", symbol_str)))?;

        AlpacaParser::parse_ticker(snapshot, &symbol_str)
    }

    async fn ping(&self) -> ExchangeResult<()> {
        // If no auth, use crypto endpoint which works without API keys
        if !self.auth.has_credentials() {
            let mut params = HashMap::new();
            params.insert("symbols".to_string(), "BTC/USD".to_string());
            self.get_market_data(AlpacaEndpoint::CryptoSnapshots, params).await?;
            Ok(())
        } else {
            // Use clock endpoint as ping for authenticated connections
            self.get_trading(AlpacaEndpoint::Clock, HashMap::new()).await?;
            Ok(())
        }
    }

    /// Get exchange info — returns list of active, tradable US equity assets
    async fn get_exchange_info(&self, account_type: AccountType) -> ExchangeResult<Vec<SymbolInfo>> {
        let mut params = HashMap::new();
        params.insert("status".to_string(), "active".to_string());
        params.insert("tradable".to_string(), "true".to_string());
        params.insert("asset_class".to_string(), "us_equity".to_string());

        let response = self.get_trading(AlpacaEndpoint::Assets, params).await?;

        // Response is an array of asset objects
        let arr = response.as_array()
            .ok_or_else(|| ExchangeError::Parse("Expected array of assets".to_string()))?;

        let infos: Vec<SymbolInfo> = arr.iter().filter_map(|item| {
            let symbol = item.get("symbol")?.as_str()?.to_string();
            let tradable = item.get("tradable").and_then(|v| v.as_bool()).unwrap_or(false);
            if !tradable {
                return None;
            }
            let status = item.get("status")
                .and_then(|v| v.as_str())
                .unwrap_or("active")
                .to_uppercase();

            // Alpaca provides price_increment (tick size) and min_trade_increment (qty step)
            // Both are string-encoded floats in the assets response
            let tick_size = item.get("price_increment")
                .and_then(|v| v.as_str())
                .and_then(|s| s.parse::<f64>().ok())
                .filter(|&v| v > 0.0);
            let step_size = item.get("min_trade_increment")
                .and_then(|v| v.as_str())
                .and_then(|s| s.parse::<f64>().ok())
                .filter(|&v| v > 0.0)
                .or(Some(1.0));

            Some(SymbolInfo {
                symbol: symbol.clone(),
                base_asset: symbol,
                quote_asset: "USD".to_string(),
                status,
                price_precision: 2,
                quantity_precision: 0,
                min_quantity: Some(1.0),
                max_quantity: None,
                tick_size,
                step_size,
                min_notional: None,
                account_type,
            })
        }).collect();

        self.precision.load_from_symbols(&infos);

        Ok(infos)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: Trading
// ═══════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Trading for AlpacaConnector {
    async fn place_order(&self, req: OrderRequest) -> ExchangeResult<PlaceOrderResponse> {
        let symbol_str = format_symbol(&req.symbol);
        let side_str = req.side.as_str().to_lowercase();
        let qty_str = self.precision.qty(&symbol_str, req.quantity);
        let client_oid = req.client_order_id.clone();

        // Build base body fields shared by most order types
        let mut base = serde_json::Map::new();
        base.insert("symbol".to_string(), json!(symbol_str));
        base.insert("qty".to_string(), json!(qty_str));
        base.insert("side".to_string(), json!(side_str));

        if let Some(coid) = client_oid {
            base.insert("client_order_id".to_string(), json!(coid));
        }

        let body: Value = match req.order_type {
            OrderType::Market => {
                base.insert("type".to_string(), json!("market"));
                base.insert("time_in_force".to_string(), json!("day"));
                Value::Object(base)
            }

            OrderType::Limit { price } => {
                let tif = tif_str(req.time_in_force);
                base.insert("type".to_string(), json!("limit"));
                base.insert("time_in_force".to_string(), json!(tif));
                base.insert("limit_price".to_string(), json!(self.precision.price(&symbol_str, price)));
                Value::Object(base)
            }

            OrderType::StopMarket { stop_price } => {
                let tif = tif_str(req.time_in_force);
                base.insert("type".to_string(), json!("stop"));
                base.insert("time_in_force".to_string(), json!(tif));
                base.insert("stop_price".to_string(), json!(self.precision.price(&symbol_str, stop_price)));
                Value::Object(base)
            }

            OrderType::StopLimit { stop_price, limit_price } => {
                let tif = tif_str(req.time_in_force);
                base.insert("type".to_string(), json!("stop_limit"));
                base.insert("time_in_force".to_string(), json!(tif));
                base.insert("stop_price".to_string(), json!(self.precision.price(&symbol_str, stop_price)));
                base.insert("limit_price".to_string(), json!(self.precision.price(&symbol_str, limit_price)));
                Value::Object(base)
            }

            OrderType::TrailingStop { callback_rate, activation_price: _ } => {
                // Alpaca accepts trail_percent (percentage offset).
                // activation_price has no Alpaca equivalent — ignored.
                base.insert("type".to_string(), json!("trailing_stop"));
                base.insert("time_in_force".to_string(), json!("gtc"));
                base.insert("trail_percent".to_string(), json!(callback_rate.to_string()));
                Value::Object(base)
            }

            OrderType::Oco { price, stop_price, stop_limit_price } => {
                // Alpaca OCO: limit take-profit + stop(-limit) stop-loss, linked via order_class=oco
                // The side refers to the closing leg — entry must already be open.
                base.insert("type".to_string(), json!("limit"));
                base.insert("time_in_force".to_string(), json!("gtc"));
                base.insert("order_class".to_string(), json!("oco"));
                base.insert("take_profit".to_string(), json!({ "limit_price": self.precision.price(&symbol_str, price) }));
                let sl_obj = if let Some(slp) = stop_limit_price {
                    json!({ "stop_price": self.precision.price(&symbol_str, stop_price), "limit_price": self.precision.price(&symbol_str, slp) })
                } else {
                    json!({ "stop_price": self.precision.price(&symbol_str, stop_price) })
                };
                base.insert("stop_loss".to_string(), sl_obj);
                Value::Object(base)
            }

            OrderType::Bracket { price, take_profit, stop_loss } => {
                // Entry type: market if price is None, limit otherwise
                if let Some(entry_price) = price {
                    base.insert("type".to_string(), json!("limit"));
                    base.insert("limit_price".to_string(), json!(self.precision.price(&symbol_str, entry_price)));
                } else {
                    base.insert("type".to_string(), json!("market"));
                }
                base.insert("time_in_force".to_string(), json!("gtc"));
                base.insert("order_class".to_string(), json!("bracket"));
                base.insert("take_profit".to_string(), json!({ "limit_price": self.precision.price(&symbol_str, take_profit) }));
                // Alpaca requires at minimum a stop_price in stop_loss object
                base.insert("stop_loss".to_string(), json!({ "stop_price": self.precision.price(&symbol_str, stop_loss) }));
                Value::Object(base)
            }

            OrderType::Ioc { price } => {
                base.insert("time_in_force".to_string(), json!("ioc"));
                if let Some(p) = price {
                    base.insert("type".to_string(), json!("limit"));
                    base.insert("limit_price".to_string(), json!(self.precision.price(&symbol_str, p)));
                } else {
                    base.insert("type".to_string(), json!("market"));
                }
                Value::Object(base)
            }

            OrderType::Fok { price } => {
                base.insert("type".to_string(), json!("limit"));
                base.insert("time_in_force".to_string(), json!("fok"));
                base.insert("limit_price".to_string(), json!(self.precision.price(&symbol_str, price)));
                Value::Object(base)
            }

            // Alpaca has no post-only flag for equities
            OrderType::PostOnly { .. } => {
                return Err(ExchangeError::UnsupportedOperation(
                    "PostOnly orders are not supported on Alpaca (US equities broker)".to_string()
                ));
            }

            // Alpaca does not support iceberg orders
            OrderType::Iceberg { .. } => {
                return Err(ExchangeError::UnsupportedOperation(
                    "Iceberg orders are not supported on Alpaca".to_string()
                ));
            }

            // Alpaca does not support algorithmic TWAP
            OrderType::Twap { .. } => {
                return Err(ExchangeError::UnsupportedOperation(
                    "TWAP orders are not supported on Alpaca".to_string()
                ));
            }

            // Alpaca has no GTD — only day / gtc
            OrderType::Gtd { .. } => {
                return Err(ExchangeError::UnsupportedOperation(
                    "GTD orders are not supported on Alpaca (use GTC or day instead)".to_string()
                ));
            }

            // Alpaca is a stock broker — no futures, no reduce-only
            OrderType::ReduceOnly { .. } => {
                return Err(ExchangeError::UnsupportedOperation(
                    "ReduceOnly orders are not supported on Alpaca (stock broker, no futures)".to_string()
                ));
            }

            OrderType::Oto { .. } | OrderType::ConditionalPlan { .. } | OrderType::DcaRecurring { .. } => {
                return Err(ExchangeError::UnsupportedOperation(
                    "Oto/ConditionalPlan/DcaRecurring orders are not supported on Alpaca".to_string()
                ));
            }
        };

        let response = self.post_trading(AlpacaEndpoint::Orders, body).await?;

        // Bracket and OCO orders return an order that embeds legs.
        // We parse the primary (outer) order; legs are accessible via nested field.
        AlpacaParser::parse_order(&response).map(PlaceOrderResponse::Simple)
    }

    async fn cancel_order(&self, req: CancelRequest) -> ExchangeResult<Order> {
        match req.scope {
            CancelScope::Single { ref order_id } => {
                let endpoint = AlpacaEndpoint::OrderById(order_id.clone());
                let response = self.delete_trading(endpoint, HashMap::new()).await?;
                AlpacaParser::parse_order(&response)
            }
            _ => Err(ExchangeError::UnsupportedOperation(
                format!("{:?} cancel scope not supported directly on Trading trait — use CancelAll trait", req.scope)
            )),
        }
    }

    async fn get_order(
        &self,
        _symbol: &str,
        order_id: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<Order> {
        // Alpaca lookup by order ID — symbol not required
        let endpoint = AlpacaEndpoint::OrderById(order_id.to_string());
        let response = self.get_trading(endpoint, HashMap::new()).await?;
        AlpacaParser::parse_order(&response)
    }

    async fn get_open_orders(
        &self,
        symbol: Option<&str>,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        let mut params = HashMap::new();
        params.insert("status".to_string(), "open".to_string());
        params.insert("nested".to_string(), "true".to_string());
        params.insert("limit".to_string(), "500".to_string());

        if let Some(sym) = symbol {
            // Alpaca uses "symbols" query param for filtering by ticker
            params.insert("symbols".to_string(), sym.to_uppercase());
        }

        let response = self.get_trading(AlpacaEndpoint::Orders, params).await?;
        AlpacaParser::parse_orders(&response)
    }

    async fn get_order_history(
        &self,
        filter: OrderHistoryFilter,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        let mut params = HashMap::new();
        params.insert("status".to_string(), "closed".to_string());
        params.insert("nested".to_string(), "true".to_string());

        if let Some(limit) = filter.limit {
            params.insert("limit".to_string(), limit.to_string());
        } else {
            params.insert("limit".to_string(), "500".to_string());
        }

        if let Some(start_ms) = filter.start_time {
            // Alpaca expects RFC-3339 for "after" param
            let dt = chrono::DateTime::from_timestamp_millis(start_ms)
                .unwrap_or(chrono::DateTime::UNIX_EPOCH);
            params.insert("after".to_string(), dt.to_rfc3339());
        }

        if let Some(end_ms) = filter.end_time {
            let dt = chrono::DateTime::from_timestamp_millis(end_ms)
                .unwrap_or(chrono::DateTime::UNIX_EPOCH);
            params.insert("until".to_string(), dt.to_rfc3339());
        }

        if let Some(sym) = filter.symbol {
            params.insert("symbols".to_string(), format_symbol(&sym));
        }

        // direction=desc gives newest first
        params.insert("direction".to_string(), "desc".to_string());

        let response = self.get_trading(AlpacaEndpoint::Orders, params).await?;
        AlpacaParser::parse_orders(&response)
    }

    /// Get user fill history via `GET /v2/account/activities/FILL`.
    ///
    /// Alpaca models each executed order-fill as an "account activity" of type
    /// `FILL`. The endpoint returns a time-ordered array of fill records.
    ///
    /// Pagination: controlled by `page_size` (max 100) and `page_token`
    /// (cursor). This implementation fetches a single page limited by
    /// `filter.limit` (default 100).
    async fn get_user_trades(
        &self,
        filter: UserTradeFilter,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<UserTrade>> {
        let mut params = HashMap::new();

        // Symbol filter — Alpaca accepts "symbols" (comma-separated) for activities
        if let Some(sym) = &filter.symbol {
            params.insert("symbols".to_string(), sym.to_uppercase());
        }

        // Time range — RFC-3339 datetime strings
        if let Some(start_ms) = filter.start_time {
            let dt = chrono::DateTime::from_timestamp_millis(start_ms as i64)
                .unwrap_or(chrono::DateTime::UNIX_EPOCH);
            params.insert("after".to_string(), dt.to_rfc3339());
        }
        if let Some(end_ms) = filter.end_time {
            let dt = chrono::DateTime::from_timestamp_millis(end_ms as i64)
                .unwrap_or(chrono::DateTime::UNIX_EPOCH);
            params.insert("until".to_string(), dt.to_rfc3339());
        }

        // Page size (max 100)
        let page_size = filter.limit.unwrap_or(100).min(100);
        params.insert("page_size".to_string(), page_size.to_string());

        // Newest first
        params.insert("direction".to_string(), "desc".to_string());

        let response = self.get_trading(
            AlpacaEndpoint::AccountActivitiesByType("FILL".to_string()),
            params,
        ).await?;

        AlpacaParser::parse_activities(&response)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: Account
// ═══════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Account for AlpacaConnector {
    async fn get_balance(&self, query: BalanceQuery) -> ExchangeResult<Vec<Balance>> {
        let response = self.get_trading(AlpacaEndpoint::Account, HashMap::new()).await?;
        let balances = AlpacaParser::parse_balance(&response)?;

        if let Some(asset_filter) = query.asset {
            Ok(balances.into_iter().filter(|b| b.asset == asset_filter).collect())
        } else {
            Ok(balances)
        }
    }

    async fn get_account_info(&self, account_type: AccountType) -> ExchangeResult<AccountInfo> {
        let response = self.get_trading(AlpacaEndpoint::Account, HashMap::new()).await?;
        AlpacaParser::parse_account_info(&response, account_type)
    }

    /// Alpaca is commission-free — returns zero rates rather than UnsupportedOperation
    async fn get_fees(&self, symbol: Option<&str>) -> ExchangeResult<FeeInfo> {
        Ok(FeeInfo {
            maker_rate: 0.0,
            taker_rate: 0.0,
            symbol: symbol.map(|s| s.to_string()),
            tier: Some("commission-free".to_string()),
        })
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: Positions
// ═══════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Positions for AlpacaConnector {
    async fn get_positions(&self, query: PositionQuery) -> ExchangeResult<Vec<Position>> {
        if let Some(sym) = query.symbol {
            let symbol_str = format_symbol(&sym);
            let endpoint = AlpacaEndpoint::PositionBySymbol(symbol_str);
            let response = self.get_trading(endpoint, HashMap::new()).await?;
            let position = AlpacaParser::parse_position(&response)?;
            Ok(vec![position])
        } else {
            let response = self.get_trading(AlpacaEndpoint::Positions, HashMap::new()).await?;
            AlpacaParser::parse_positions(&response)
        }
    }

    /// Alpaca is a stock broker — funding rates are not applicable
    async fn get_funding_rate(
        &self,
        _symbol: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<FundingRate> {
        Err(ExchangeError::UnsupportedOperation(
            "Funding rates are not available on Alpaca (stock broker, no perpetual futures)".to_string()
        ))
    }

    async fn modify_position(&self, req: PositionModification) -> ExchangeResult<()> {
        match req {
            PositionModification::ClosePosition { symbol, .. } => {
                // Alpaca natively supports closing a single position via DELETE /v2/positions/{symbol}
                let symbol_str = format_symbol(&symbol);
                let endpoint = AlpacaEndpoint::PositionBySymbol(symbol_str);
                // DELETE /v2/positions/{symbol} returns the closing order
                self.delete_trading(endpoint, HashMap::new()).await?;
                Ok(())
            }

            PositionModification::SetLeverage { .. } => {
                Err(ExchangeError::UnsupportedOperation(
                    "SetLeverage is not supported on Alpaca (stock broker, no leveraged futures positions)".to_string()
                ))
            }

            PositionModification::SetMarginMode { .. } => {
                Err(ExchangeError::UnsupportedOperation(
                    "SetMarginMode is not supported on Alpaca".to_string()
                ))
            }

            PositionModification::AddMargin { .. } => {
                Err(ExchangeError::UnsupportedOperation(
                    "AddMargin is not supported on Alpaca".to_string()
                ))
            }

            PositionModification::RemoveMargin { .. } => {
                Err(ExchangeError::UnsupportedOperation(
                    "RemoveMargin is not supported on Alpaca".to_string()
                ))
            }

            PositionModification::SetTpSl { .. } => {
                Err(ExchangeError::UnsupportedOperation(
                    "SetTpSl is not supported on Alpaca positions directly — use Bracket orders instead".to_string()
                ))
            }

            PositionModification::SwitchPositionMode { .. } | PositionModification::MovePositions { .. } => {
                Err(ExchangeError::UnsupportedOperation(
                    "SwitchPositionMode/MovePositions not supported on Alpaca".to_string()
                ))
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// OPTIONAL TRAIT: CancelAll
// ═══════════════════════════════════════════════════════════════════════════

#[async_trait]
impl CancelAll for AlpacaConnector {
    /// Cancel all open orders via DELETE /v2/orders
    ///
    /// Alpaca returns HTTP 207 Multi-Status with per-order sub-statuses.
    /// The native endpoint cancels all orders atomically.
    async fn cancel_all_orders(
        &self,
        scope: CancelScope,
        _account_type: AccountType,
    ) -> ExchangeResult<CancelAllResponse> {
        let mut params = HashMap::new();

        // If scoped to a symbol, pass it as query param
        match &scope {
            CancelScope::BySymbol { symbol } => {
                params.insert("symbols".to_string(), format_symbol(symbol));
            }
            CancelScope::All { symbol: Some(sym) } => {
                params.insert("symbols".to_string(), format_symbol(sym));
            }
            CancelScope::All { symbol: None } => {
                // Cancel all — no filter
            }
            _ => {
                return Err(ExchangeError::UnsupportedOperation(
                    "CancelAll only supports CancelScope::All and CancelScope::BySymbol".to_string()
                ));
            }
        }

        // DELETE /v2/orders returns 207 Multi-Status array
        let response = self.delete_trading_multi(AlpacaEndpoint::Orders, params).await?;

        AlpacaParser::parse_cancel_all(&response)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// OPTIONAL TRAIT: AmendOrder
// ═══════════════════════════════════════════════════════════════════════════

#[async_trait]
impl AmendOrder for AlpacaConnector {
    /// Amend an open order via PATCH /v2/orders/{order_id}
    ///
    /// Alpaca creates a new order atomically and cancels the original.
    /// The returned order has a new exchange-assigned ID.
    async fn amend_order(&self, req: AmendRequest) -> ExchangeResult<Order> {
        let mut body = serde_json::Map::new();
        let symbol_str = format_symbol(&req.symbol);

        if let Some(qty) = req.fields.quantity {
            body.insert("qty".to_string(), json!(self.precision.qty(&symbol_str, qty)));
        }

        if let Some(price) = req.fields.price {
            body.insert("limit_price".to_string(), json!(self.precision.price(&symbol_str, price)));
        }

        if let Some(trigger) = req.fields.trigger_price {
            body.insert("stop_price".to_string(), json!(self.precision.price(&symbol_str, trigger)));
        }

        if body.is_empty() {
            return Err(ExchangeError::InvalidRequest(
                "AmendRequest must specify at least one field to change (qty, price, or trigger_price)".to_string()
            ));
        }

        let endpoint = AlpacaEndpoint::OrderById(req.order_id);
        let response = self.patch_trading(endpoint, Value::Object(body)).await?;
        AlpacaParser::parse_order(&response)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// EXTENDED METHODS (Alpaca-specific)
// ═══════════════════════════════════════════════════════════════════════════

impl AlpacaConnector {
    /// Get list of all tradable assets
    pub async fn get_assets(&self) -> ExchangeResult<Vec<String>> {
        let mut params = HashMap::new();
        params.insert("status".to_string(), "active".to_string());
        params.insert("tradable".to_string(), "true".to_string());

        let response = self.get_trading(AlpacaEndpoint::Assets, params).await?;
        AlpacaParser::parse_symbols(&response)
    }

    /// Get market clock (is market open?)
    pub async fn get_clock(&self) -> ExchangeResult<Value> {
        self.get_trading(AlpacaEndpoint::Clock, HashMap::new()).await
    }

    /// Get trading calendar
    pub async fn get_calendar(&self, start: Option<&str>, end: Option<&str>) -> ExchangeResult<Value> {
        let mut params = HashMap::new();
        if let Some(s) = start {
            params.insert("start".to_string(), s.to_string());
        }
        if let Some(e) = end {
            params.insert("end".to_string(), e.to_string());
        }

        self.get_trading(AlpacaEndpoint::Calendar, params).await
    }

    /// Cancel all orders
    pub async fn cancel_all_orders(&self) -> ExchangeResult<Vec<Order>> {
        let response = self.delete_trading(AlpacaEndpoint::Orders, HashMap::new()).await?;
        AlpacaParser::parse_orders(&response)
    }

    /// Get news
    pub async fn get_news(&self, symbols: Option<Vec<String>>, limit: Option<u32>) -> ExchangeResult<Value> {
        let mut params = HashMap::new();

        if let Some(syms) = symbols {
            params.insert("symbols".to_string(), syms.join(","));
        }

        if let Some(lim) = limit {
            params.insert("limit".to_string(), lim.to_string());
        }

        self.get_market_data(AlpacaEndpoint::News, params).await
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// ACCOUNT LEDGER
// ═══════════════════════════════════════════════════════════════════════════

#[async_trait]
impl AccountLedger for AlpacaConnector {
    /// Get account activity history from `GET /v2/account/activities`.
    ///
    /// Alpaca activities include:
    /// - `FILL` → Trade fills (stocks and crypto)
    /// - `CSD` / `CSW` → Cash deposit / withdrawal
    /// - `FEE` → Fees
    /// - `DIV`, `INT` → Dividends, interest
    /// - `JNLC`, `JNLS`, `ACATC`, `ACATS` → Transfers
    ///
    /// Filter mapping:
    /// - `filter.entry_type` → `activity_types` query param
    /// - `filter.start_time` → `after` (RFC3339 UTC)
    /// - `filter.end_time`   → `until` (RFC3339 UTC)
    /// - `filter.limit`      → `page_size` (max 100)
    /// - `filter.asset`      → client-side filter by symbol after fetch
    async fn get_ledger(
        &self,
        filter: LedgerFilter,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<LedgerEntry>> {
        let mut params = HashMap::new();

        // Map LedgerEntryType to Alpaca activity_types
        if let Some(ref entry_type) = filter.entry_type {
            let types_str = match entry_type {
                LedgerEntryType::Trade => "FILL",
                LedgerEntryType::Deposit => "CSD",
                LedgerEntryType::Withdrawal => "CSW",
                LedgerEntryType::Fee => "FEE",
                LedgerEntryType::Transfer => "JNLC,JNLS,ACATC,ACATS",
                LedgerEntryType::Other(s) => s.as_str(),
                _ => "",
            };
            if !types_str.is_empty() {
                params.insert("activity_types".to_string(), types_str.to_string());
            }
        }

        // Alpaca uses RFC3339 timestamps
        if let Some(start_ms) = filter.start_time {
            if let Some(ts) = ms_to_rfc3339(start_ms) {
                params.insert("after".to_string(), ts);
            }
        }

        if let Some(end_ms) = filter.end_time {
            if let Some(ts) = ms_to_rfc3339(end_ms) {
                params.insert("until".to_string(), ts);
            }
        }

        if let Some(limit) = filter.limit {
            params.insert("page_size".to_string(), limit.min(100).to_string());
        }

        let response = self.get_trading(AlpacaEndpoint::AccountActivities, params).await?;
        let mut entries = AlpacaParser::parse_ledger(&response)?;

        // Client-side filter by asset (symbol) when requested.
        // Alpaca has no server-side asset filter on the activities endpoint.
        if let Some(ref asset) = filter.asset {
            let upper = asset.to_uppercase();
            entries.retain(|e| e.asset.to_uppercase() == upper);
        }

        Ok(entries)
    }
}

/// Convert Unix milliseconds to RFC3339 UTC string without external dependencies.
///
/// Output format: `YYYY-MM-DDTHH:MM:SS.mmmZ`
fn ms_to_rfc3339(unix_ms: u64) -> Option<String> {
    let secs = unix_ms / 1000;
    let millis = unix_ms % 1000;

    let days_since_epoch = secs / 86400;
    let secs_in_day = secs % 86400;
    let hh = secs_in_day / 3600;
    let mm = (secs_in_day % 3600) / 60;
    let ss = secs_in_day % 60;

    let (year, month, day) = days_to_date(days_since_epoch)?;

    Some(format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
        year, month, day, hh, mm, ss, millis
    ))
}

/// Convert days since Unix epoch (1970-01-01) to `(year, month, day)`.
///
/// Uses the algorithm from http://howardhinnant.github.io/date_algorithms.html
fn days_to_date(days: u64) -> Option<(u64, u64, u64)> {
    let z = days + 719468;
    let era = z / 146097;
    let doe = z % 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    Some((y, m, d))
}