alpaca-trader-rs 0.6.0

Alpaca Markets trading toolkit — async REST client library and interactive TUI trading terminal
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
//! Domain types used throughout the library and the binary crate.
use chrono::DateTime;
use serde::{Deserialize, Serialize};

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

    // ── Enum as_str ──────────────────────────────────────────────────────────

    #[test]
    fn order_side_buy_str() {
        assert_eq!(OrderSide::Buy.as_str(), "buy");
    }

    #[test]
    fn order_side_sell_str() {
        assert_eq!(OrderSide::Sell.as_str(), "sell");
    }

    #[test]
    fn order_type_market_str() {
        assert_eq!(OrderType::Market.as_str(), "market");
    }

    #[test]
    fn order_type_limit_str() {
        assert_eq!(OrderType::Limit.as_str(), "limit");
    }

    #[test]
    fn time_in_force_day_str() {
        assert_eq!(TimeInForce::Day.as_str(), "day");
    }

    #[test]
    fn time_in_force_gtc_str() {
        assert_eq!(TimeInForce::Gtc.as_str(), "gtc");
    }

    // ── Serde deserialization ─────────────────────────────────────────────────

    #[test]
    fn account_info_deserializes() {
        let json = r#"{
            "status": "ACTIVE",
            "equity": "100000",
            "buying_power": "200000",
            "cash": "100000",
            "long_market_value": "0",
            "daytrade_count": 0,
            "pattern_day_trader": false,
            "currency": "USD"
        }"#;
        let acc: AccountInfo = serde_json::from_str(json).unwrap();
        assert_eq!(acc.status, "ACTIVE");
        assert_eq!(acc.equity, "100000");
        assert_eq!(acc.buying_power, "200000");
        assert_eq!(acc.cash, "100000");
        assert_eq!(acc.daytrade_count, 0);
        assert!(!acc.pattern_day_trader);
        assert_eq!(acc.currency, "USD");
        assert!(acc.portfolio_value.is_none());
        // New fields default to empty string when absent
        assert_eq!(acc.last_equity, "");
        assert_eq!(acc.account_number, "");
    }

    #[test]
    fn account_info_deserializes_pl_and_account_number() {
        let json = r#"{
            "status": "ACTIVE",
            "equity": "125432.18",
            "last_equity": "124588.96",
            "buying_power": "48210.00",
            "cash": "48210.00",
            "long_market_value": "77222.18",
            "daytrade_count": 1,
            "pattern_day_trader": false,
            "currency": "USD",
            "account_number": "PA1234567"
        }"#;
        let acc: AccountInfo = serde_json::from_str(json).unwrap();
        assert_eq!(acc.last_equity, "124588.96");
        assert_eq!(acc.account_number, "PA1234567");
        let equity: f64 = acc.equity.parse().unwrap();
        let last: f64 = acc.last_equity.parse().unwrap();
        let day_pl = equity - last;
        assert!(
            (day_pl - 843.22).abs() < 0.01,
            "Day P&L should be ~843.22, got {day_pl}"
        );
    }

    #[test]
    fn order_notional_qty_null() {
        let json = r#"{
            "id": "abc",
            "symbol": "AAPL",
            "side": "buy",
            "qty": null,
            "notional": "500",
            "order_type": "market",
            "status": "accepted",
            "filled_qty": "0",
            "time_in_force": "day"
        }"#;
        let order: Order = serde_json::from_str(json).unwrap();
        assert!(order.qty.is_none());
        assert_eq!(order.notional.as_deref(), Some("500"));
        assert!(order.limit_price.is_none());
        assert!(order.filled_avg_price.is_none());
    }

    #[test]
    fn order_filled_avg_price_deserializes() {
        let json = r#"{
            "id": "xyz",
            "symbol": "TSLA",
            "side": "buy",
            "qty": "5",
            "order_type": "market",
            "status": "filled",
            "filled_qty": "5",
            "filled_avg_price": "312.45",
            "time_in_force": "day"
        }"#;
        let order: Order = serde_json::from_str(json).unwrap();
        assert_eq!(order.filled_avg_price.as_deref(), Some("312.45"));
        assert_eq!(order.filled_qty, "5");
    }

    #[test]
    fn watchlist_empty_assets_default() {
        let json = r#"{"id": "wl1", "name": "Test"}"#;
        let wl: Watchlist = serde_json::from_str(json).unwrap();
        assert!(wl.assets.is_empty());
    }

    // ── OrderRequest serde rename ─────────────────────────────────────────────

    #[test]
    fn order_request_serializes_type_field() {
        let req = OrderRequest {
            symbol: "AAPL".into(),
            qty: Some("10".into()),
            notional: None,
            side: "buy".into(),
            order_type: "limit".into(),
            time_in_force: "day".into(),
            limit_price: Some("185.00".into()),
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(
            json.contains("\"type\""),
            "body should use 'type' key: {json}"
        );
        assert!(
            !json.contains("\"order_type\""),
            "body must not use 'order_type': {json}"
        );
    }

    #[test]
    fn order_request_omits_none_fields() {
        let req = OrderRequest {
            symbol: "TSLA".into(),
            qty: None,
            notional: Some("1000".into()),
            side: "buy".into(),
            order_type: "market".into(),
            time_in_force: "day".into(),
            limit_price: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(!json.contains("\"qty\""), "qty should be omitted: {json}");
        assert!(
            !json.contains("\"limit_price\""),
            "limit_price should be omitted: {json}"
        );
        assert!(
            json.contains("\"notional\""),
            "notional should be present: {json}"
        );
    }

    // ── MarketClock::market_state ─────────────────────────────────────────────

    fn make_clock(
        is_open: bool,
        timestamp: &str,
        next_open: &str,
        next_close: &str,
    ) -> MarketClock {
        MarketClock {
            is_open,
            timestamp: timestamp.into(),
            next_open: next_open.into(),
            next_close: next_close.into(),
        }
    }

    #[test]
    fn market_state_open() {
        // is_open=true always returns Open regardless of timestamps
        let clock = make_clock(
            true,
            "2026-05-12T15:00:00Z",
            "2026-05-13T13:30:00Z",
            "2026-05-12T20:00:00Z",
        );
        assert_eq!(clock.market_state(), MarketState::Open);
    }

    #[test]
    fn market_state_pre_market() {
        // 2 hours before next open → PRE-MARKET
        let next_open = "2026-05-13T13:30:00Z"; // 9:30 AM ET
        let now = "2026-05-13T11:30:00Z"; // 7:30 AM ET, 2h before open
        let clock = make_clock(false, now, next_open, "2026-05-13T20:00:00Z");
        assert_eq!(clock.market_state(), MarketState::PreMarket);
    }

    #[test]
    fn market_state_pre_market_boundary() {
        // Exactly 4 hours before next open → still PRE-MARKET
        let next_open = "2026-05-13T13:30:00Z";
        let now = "2026-05-13T09:30:00Z"; // exactly 4h before
        let clock = make_clock(false, now, next_open, "2026-05-13T20:00:00Z");
        assert_eq!(clock.market_state(), MarketState::PreMarket);
    }

    #[test]
    fn market_state_after_hours() {
        // 5 hours after close (4 PM → 9 PM), ~16.5h before next open
        let next_open = "2026-05-13T13:30:00Z"; // next morning 9:30 AM ET
        let now = "2026-05-12T21:00:00Z"; // 5 PM ET (17:00 UTC−4 = 21:00 UTC)
        let clock = make_clock(false, now, next_open, "2026-05-13T20:00:00Z");
        assert_eq!(clock.market_state(), MarketState::AfterHours);
    }

    #[test]
    fn market_state_closed_weekend() {
        // Friday close to Monday open: ~65.5 hours → CLOSED
        let next_open = "2026-05-18T13:30:00Z"; // Monday 9:30 AM ET
        let now = "2026-05-16T00:00:00Z"; // Saturday midnight UTC
        let clock = make_clock(false, now, next_open, "2026-05-18T20:00:00Z");
        assert_eq!(clock.market_state(), MarketState::Closed);
    }

    #[test]
    fn market_state_closed_overnight() {
        // ~22h before open (e.g. 11 PM ET before next 9:30 AM) → CLOSED
        let next_open = "2026-05-13T13:30:00Z";
        let now = "2026-05-12T15:30:00Z"; // ~22h before
        let clock = make_clock(false, now, next_open, "2026-05-13T20:00:00Z");
        assert_eq!(clock.market_state(), MarketState::Closed);
    }

    #[test]
    fn market_state_invalid_timestamp_falls_back_to_closed() {
        let clock = make_clock(false, "not-a-date", "also-bad", "2026-05-13T20:00:00Z");
        assert_eq!(clock.market_state(), MarketState::Closed);
    }

    #[test]
    fn market_state_as_str_values() {
        assert_eq!(MarketState::Open.as_str(), "OPEN");
        assert_eq!(MarketState::PreMarket.as_str(), "PRE-MARKET");
        assert_eq!(MarketState::AfterHours.as_str(), "AFTER-HOURS");
        assert_eq!(MarketState::Closed.as_str(), "CLOSED");
    }

    // ── Snapshot serde ────────────────────────────────────────────────────────

    #[test]
    fn snapshot_deserializes_full() {
        let json = r#"{
            "latestTrade": { "p": 176.0 },
            "latestQuote": { "ap": 176.1, "bp": 175.9 },
            "dailyBar":     { "c": 175.5, "v": 1234567.0 },
            "prevDailyBar": { "c": 170.0, "v":  987654.0 }
        }"#;
        let snap: Snapshot = serde_json::from_str(json).unwrap();
        let lt = snap.latest_trade.expect("latestTrade expected");
        assert!((lt.p - 176.0).abs() < 0.01);
        let lq = snap.latest_quote.expect("latestQuote expected");
        assert_eq!(lq.ap, Some(176.1));
        assert_eq!(lq.bp, Some(175.9));
        let daily = snap.daily_bar.expect("dailyBar expected");
        assert!((daily.c - 175.5).abs() < 0.01);
        assert!((daily.v - 1_234_567.0).abs() < 1.0);
        let prev = snap.prev_daily_bar.expect("prevDailyBar expected");
        assert!((prev.c - 170.0).abs() < 0.01);
    }

    #[test]
    fn snapshot_deserializes_missing_bars() {
        let json = r#"{}"#;
        let snap: Snapshot = serde_json::from_str(json).unwrap();
        assert!(snap.latest_trade.is_none());
        assert!(snap.latest_quote.is_none());
        assert!(snap.daily_bar.is_none());
        assert!(snap.prev_daily_bar.is_none());
    }

    #[test]
    fn snapshot_deserializes_trade_only_no_quote() {
        // Regression: snapshot with latestTrade but no latestQuote
        let json = r#"{ "latestTrade": { "p": 150.25 } }"#;
        let snap: Snapshot = serde_json::from_str(json).unwrap();
        let lt = snap.latest_trade.expect("latestTrade expected");
        assert!((lt.p - 150.25).abs() < 0.001);
        assert!(snap.latest_quote.is_none());
    }

    #[test]
    fn snapshot_map_deserializes() {
        use std::collections::HashMap;
        let json = r#"{
            "AAPL": {
                "latestTrade":  { "p": 201.0 },
                "latestQuote":  { "ap": 201.1, "bp": 200.9 },
                "dailyBar":     { "c": 200.0, "v": 5000000.0 },
                "prevDailyBar": { "c": 195.0, "v": 4500000.0 }
            },
            "TSLA": {}
        }"#;
        let map: HashMap<String, Snapshot> = serde_json::from_str(json).unwrap();
        assert_eq!(map.len(), 2);
        assert!(map["AAPL"].latest_trade.is_some());
        assert!(map["AAPL"].daily_bar.is_some());
        assert!(map["TSLA"].latest_trade.is_none());
        assert!(map["TSLA"].daily_bar.is_none());
    }
}

/// Snapshot of account balances and status from `GET /account`.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct AccountInfo {
    /// Account status (e.g., `"ACTIVE"`).
    pub status: String,
    /// Total account equity as a dollar string.
    pub equity: String,
    /// Account equity at the close of the previous trading day, as a dollar string.
    /// Used to compute Day P&L.
    #[serde(default)]
    pub last_equity: String,
    /// Buying power available for new orders, as a dollar string.
    pub buying_power: String,
    /// Cash balance, as a dollar string.
    pub cash: String,
    /// Total long market value of all positions, as a dollar string.
    pub long_market_value: String,
    /// Number of day trades made in the rolling 5-business-day window.
    pub daytrade_count: u32,
    /// Whether the account has been flagged as a pattern day trader.
    pub pattern_day_trader: bool,
    /// Account currency (typically `"USD"`).
    pub currency: String,
    /// Total portfolio value; may be absent on some account types.
    #[serde(default)]
    pub portfolio_value: Option<String>,
    /// Unique account identifier (e.g. `"PA1234567"` for paper accounts).
    #[serde(default)]
    pub account_number: String,
}

/// A single open or closed position held in the account.
#[derive(Debug, Clone, Deserialize)]
pub struct Position {
    /// Ticker symbol (e.g., `"AAPL"`).
    pub symbol: String,
    /// Number of shares held (positive = long, may be fractional).
    pub qty: String,
    /// Average cost basis per share, as a dollar string.
    pub avg_entry_price: String,
    /// Current price per share, as a dollar string.
    pub current_price: String,
    /// Current market value of the entire position, as a dollar string.
    pub market_value: String,
    /// Total unrealised profit/loss, as a dollar string.
    pub unrealized_pl: String,
    /// Total unrealised profit/loss percentage, as a decimal string.
    pub unrealized_plpc: String,
    /// Position side: `"long"` or `"short"`.
    pub side: String,
    /// Asset class (e.g., `"us_equity"`, `"crypto"`).
    #[serde(default)]
    pub asset_class: String,
}

/// An order placed with the broker (open, filled, cancelled, etc.).
#[derive(Debug, Clone, Deserialize)]
pub struct Order {
    /// Unique order ID assigned by Alpaca.
    pub id: String,
    /// Ticker symbol the order is for.
    pub symbol: String,
    /// Order direction: `"buy"` or `"sell"`.
    pub side: String,
    /// Whole-share quantity. Mutually exclusive with `notional`.
    #[serde(default)]
    pub qty: Option<String>,
    /// Dollar notional amount. Mutually exclusive with `qty`.
    #[serde(default)]
    pub notional: Option<String>,
    /// Order type: `"market"`, `"limit"`, etc.
    pub order_type: String,
    /// Limit price for limit orders; absent for market orders.
    #[serde(default)]
    pub limit_price: Option<String>,
    /// Current order status (e.g., `"new"`, `"filled"`, `"canceled"`).
    pub status: String,
    /// ISO 8601 timestamp of when the order was submitted.
    #[serde(default)]
    pub submitted_at: Option<String>,
    /// ISO 8601 timestamp of when the order was fully filled.
    #[serde(default)]
    pub filled_at: Option<String>,
    /// Number of shares filled so far.
    pub filled_qty: String,
    /// Average price at which the order was filled; `None` if not yet filled.
    #[serde(default)]
    pub filled_avg_price: Option<String>,
    /// Time-in-force: `"day"`, `"gtc"`, etc.
    pub time_in_force: String,
}

/// Direction of an order.
#[derive(Debug, Clone, PartialEq)]
pub enum OrderSide {
    /// Buy (long) order.
    Buy,
    /// Sell (short or close-long) order.
    Sell,
}

impl OrderSide {
    /// Returns the lowercase API string for this side: `"buy"` or `"sell"`.
    pub fn as_str(&self) -> &'static str {
        match self {
            OrderSide::Buy => "buy",
            OrderSide::Sell => "sell",
        }
    }
}

/// Execution type of an order.
#[derive(Debug, Clone, PartialEq)]
pub enum OrderType {
    /// Execute immediately at the best available price.
    Market,
    /// Execute only at the specified limit price or better.
    Limit,
}

impl OrderType {
    /// Returns the lowercase API string: `"market"` or `"limit"`.
    pub fn as_str(&self) -> &'static str {
        match self {
            OrderType::Market => "market",
            OrderType::Limit => "limit",
        }
    }
}

/// How long an order remains active before it is automatically cancelled.
#[derive(Debug, Clone)]
pub enum TimeInForce {
    /// Active only for the current trading day.
    Day,
    /// Active until explicitly cancelled (Good Till Cancelled).
    Gtc,
}

impl TimeInForce {
    /// Returns the lowercase API string: `"day"` or `"gtc"`.
    pub fn as_str(&self) -> &'static str {
        match self {
            TimeInForce::Day => "day",
            TimeInForce::Gtc => "gtc",
        }
    }
}

/// Request body sent to `POST /orders`.
///
/// Either `qty` or `notional` must be set; not both.
#[derive(Debug, Clone, Serialize)]
pub struct OrderRequest {
    /// Ticker symbol to trade.
    pub symbol: String,
    /// Whole-share quantity; omitted when using notional.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qty: Option<String>,
    /// Dollar notional; omitted when using share quantity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notional: Option<String>,
    /// Order direction — `"buy"` or `"sell"`.
    pub side: String,
    /// Order type — `"market"`, `"limit"`, etc.
    #[serde(rename = "type")]
    pub order_type: String,
    /// Time-in-force — `"day"`, `"gtc"`, etc.
    pub time_in_force: String,
    /// Required for limit orders; omitted for market orders.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_price: Option<String>,
}

/// Current market clock from `GET /clock`.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct MarketClock {
    /// `true` if the primary US equity market is currently open.
    pub is_open: bool,
    /// ISO 8601 timestamp of the next market open.
    pub next_open: String,
    /// ISO 8601 timestamp of the next market close.
    pub next_close: String,
    /// Current server timestamp in ISO 8601 format.
    pub timestamp: String,
}

/// The current trading session state derived from [`MarketClock`] fields.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MarketState {
    /// Primary session — 9:30 AM – 4:00 PM ET.
    Open,
    /// Pre-market session — up to 4 hours before the next open.
    PreMarket,
    /// After-hours session — between close and ~20 hours before next open.
    AfterHours,
    /// Market is closed (overnight / weekend).
    Closed,
}

impl MarketState {
    /// Display string shown in the header.
    pub fn as_str(&self) -> &'static str {
        match self {
            MarketState::Open => "OPEN",
            MarketState::PreMarket => "PRE-MARKET",
            MarketState::AfterHours => "AFTER-HOURS",
            MarketState::Closed => "CLOSED",
        }
    }
}

impl MarketClock {
    /// Derive the current [`MarketState`] from the clock's fields.
    ///
    /// Decision tree:
    /// 1. `is_open == true` → [`MarketState::Open`]
    /// 2. Parse `timestamp` (current ET time) and `next_open` (next session open).
    /// 3. `time_to_open ≤ 4 h` → [`MarketState::PreMarket`]  (pre-market starts ~4 AM)
    /// 4. `4 h < time_to_open ≤ 20 h` → [`MarketState::AfterHours`]  (same trading day, ~4–8 PM ET)
    /// 5. Otherwise → [`MarketState::Closed`]  (overnight / weekend gap > 20 h)
    ///
    /// Falls back to [`MarketState::Closed`] when the timestamp strings cannot be parsed.
    pub fn market_state(&self) -> MarketState {
        if self.is_open {
            return MarketState::Open;
        }
        let now = DateTime::parse_from_rfc3339(&self.timestamp).ok();
        let next_open = DateTime::parse_from_rfc3339(&self.next_open).ok();
        match (now, next_open) {
            (Some(now), Some(open)) => {
                let secs = (open - now).num_seconds();
                if secs <= 0 {
                    // next_open is in the past — shouldn't happen normally
                    MarketState::Closed
                } else if secs <= 4 * 3600 {
                    MarketState::PreMarket
                } else if secs <= 20 * 3600 {
                    MarketState::AfterHours
                } else {
                    MarketState::Closed
                }
            }
            _ => MarketState::Closed,
        }
    }
}

/// Latest NBBO quote for a symbol from the market data stream.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct Quote {
    /// Ticker symbol this quote is for.
    pub symbol: String,
    /// Ask price (best offer), absent before the first quote arrives.
    #[serde(default)]
    pub ap: Option<f64>,
    /// Bid price (best bid), absent before the first quote arrives.
    #[serde(default)]
    pub bp: Option<f64>,
    /// Ask size in round lots.
    #[serde(default)]
    pub as_: Option<u64>,
    /// Bid size in round lots.
    #[serde(default)]
    pub bs: Option<u64>,
}

/// Brief watchlist descriptor returned by `GET /watchlists`.
///
/// For the full asset list use [`Watchlist`] via [`AlpacaClient::get_watchlist`].
///
/// [`AlpacaClient::get_watchlist`]: crate::client::AlpacaClient::get_watchlist
#[derive(Debug, Clone, Deserialize)]
pub struct WatchlistSummary {
    /// Unique watchlist identifier (UUID).
    pub id: String,
    /// Human-readable watchlist name.
    pub name: String,
}

/// Full watchlist including its constituent assets.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct Watchlist {
    /// Unique watchlist identifier (UUID).
    pub id: String,
    /// Human-readable watchlist name.
    pub name: String,
    /// Ordered list of assets in this watchlist.
    #[serde(default)]
    pub assets: Vec<Asset>,
}

/// An individual asset returned inside a [`Watchlist`] or from `GET /assets`.
#[derive(Debug, Clone, Deserialize)]
pub struct Asset {
    /// Unique asset identifier (UUID).
    pub id: String,
    /// Ticker symbol (e.g., `"AAPL"`).
    pub symbol: String,
    /// Full company or asset name.
    pub name: String,
    /// Exchange on which the asset trades (e.g., `"NASDAQ"`).
    pub exchange: String,
    /// Asset class (e.g., `"us_equity"`, `"crypto"`).
    #[serde(rename = "class")]
    pub asset_class: String,
    /// Whether the asset is currently tradable via the API.
    pub tradable: bool,
    /// Whether the asset can be sold short.
    pub shortable: bool,
    /// Whether fractional-share quantities are supported.
    pub fractionable: bool,
    /// Whether the asset is easy to borrow for shorting.
    #[serde(default)]
    pub easy_to_borrow: bool,
}

/// A single OHLCV bar returned inside a [`Snapshot`].
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SnapshotBar {
    /// Opening price for this bar.
    #[serde(default)]
    pub o: f64,
    /// High price for this bar.
    #[serde(default)]
    pub h: f64,
    /// Low price for this bar.
    #[serde(default)]
    pub l: f64,
    /// Closing price for this bar.
    pub c: f64,
    /// Volume traded during this bar.
    pub v: f64,
}

/// A single 1-minute OHLCV bar from `GET /v2/stocks/{symbol}/bars`.
///
/// Only the close price is stored for use in the intraday sparkline.
#[derive(Debug, Clone, Deserialize)]
pub struct MinuteBar {
    /// Closing price for this 1-minute bar.
    pub c: f64,
}

/// Response wrapper for `GET /v2/stocks/{symbol}/bars`.
#[derive(Debug, Clone, Deserialize)]
pub struct BarsResponse {
    /// Ordered list of 1-minute bars for the requested symbol and date range.
    pub bars: Vec<MinuteBar>,
}

/// Latest trade returned inside a [`Snapshot`].
#[derive(Debug, Clone, Deserialize)]
pub struct SnapshotTrade {
    /// Price of the most recent trade.
    pub p: f64,
}

/// Latest quote returned inside a [`Snapshot`].
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SnapshotQuote {
    /// Best ask price, if available.
    #[serde(default)]
    pub ap: Option<f64>,
    /// Best bid price, if available.
    #[serde(default)]
    pub bp: Option<f64>,
}

/// Latest market snapshot for a symbol from `GET /v2/stocks/snapshots`.
///
/// Contains the latest trade/quote (for current price), today's daily bar
/// (for volume), and the previous day's bar (for computing Change%).
#[derive(Debug, Clone, Deserialize, Default)]
pub struct Snapshot {
    /// Most recent trade.  Present in all snapshot responses; used as the
    /// price source when no real-time WebSocket quote is available.
    #[serde(rename = "latestTrade", default)]
    pub latest_trade: Option<SnapshotTrade>,
    /// Most recent quote (ask/bid).  Preferred over `latest_trade` when
    /// both are present because it reflects the current spread.
    #[serde(rename = "latestQuote", default)]
    pub latest_quote: Option<SnapshotQuote>,
    /// Today's daily bar (aggregated from market open to the latest bar).
    #[serde(rename = "dailyBar", default)]
    pub daily_bar: Option<SnapshotBar>,
    /// Previous trading day's closing bar.
    #[serde(rename = "prevDailyBar", default)]
    pub prev_daily_bar: Option<SnapshotBar>,
}

/// Response from `GET /v2/account/portfolio/history`.
///
/// The `equity` array contains one value per time bucket; entries are `null`
/// when the market was closed during that interval.
#[derive(Debug, Clone, Deserialize)]
pub struct PortfolioHistory {
    /// Dollar equity values per time bucket; `None` means market was closed.
    pub equity: Vec<Option<f64>>,
}