schwab 0.3.1

Unofficial Rust client library for the Schwab API, unaffiliated with Schwab brokerage or thinkorswim
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
use clap::{ArgGroup, Args, Parser, Subcommand};

/// Agent-oriented JSON CLI porcelain for Charles Schwab workflows.
#[derive(Debug, Parser)]
#[command(
    name = "schwab-agent",
    version,
    about = "Agent-oriented JSON CLI porcelain for Charles Schwab workflows",
    long_about = "All normal command output is compact JSON. Use --help on any command for examples and flags. Trading commands intentionally start with draft and validate workflows before placement.",
    arg_required_else_help = true,
    propagate_version = true,
    help_template = "{name} {version}\n{about-section}\n{usage-heading} {usage}\n\n{all-args}{tab}"
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Command,
}

impl Cli {
    /// Returns the stable dotted command name used in JSON envelopes.
    #[must_use]
    pub fn command_name(&self) -> &'static str {
        match &self.command {
            Command::Analyze(_) => "analyze",
            Command::Auth(AuthCommand::Status) => "auth.status",
            Command::Auth(AuthCommand::Login(_)) => "auth.login",
            Command::Auth(AuthCommand::LoginUrl(_)) => "auth.login_url",
            Command::Auth(AuthCommand::Exchange(_)) => "auth.exchange",
            Command::Auth(AuthCommand::Refresh) => "auth.refresh",
            Command::Option(OptionCommand::Expirations(_)) => "option.expirations",
            Command::Option(OptionCommand::Chain(_)) => "option.chain",
            Command::Option(OptionCommand::Screen(_)) => "option.screen",
            Command::Option(OptionCommand::Contract(_)) => "option.contract",
            Command::Market(MarketCommand::History(_)) => "market.history",
            Command::Market(MarketCommand::Quote(_)) => "market.quote",
            Command::Order(_) => "order",
            Command::Ta(TaCommand::Dashboard(_)) => "ta.dashboard",
            Command::Ta(TaCommand::ExpectedMove(_)) => "ta.expected-move",
            Command::Account(_) => "account",
        }
    }
}

/// Top-level command groups.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Multi-symbol analysis combining quote and technical analysis dashboard.
    Analyze(AnalyzeArgs),
    /// Authentication commands for token setup and inspection.
    #[command(subcommand)]
    Auth(AuthCommand),
    /// Market-data workflows with compact JSON summaries.
    #[command(subcommand)]
    Market(MarketCommand),
    /// Option chain, screening, and contract lookup workflows.
    #[command(subcommand)]
    Option(OptionCommand),
    /// Unified order construction, preview, placement, and lifecycle workflows.
    #[command(subcommand)]
    Order(OrderCommand),
    /// Technical analysis indicator workflows.
    #[command(subcommand)]
    Ta(TaCommand),
    /// Account discovery, balances, positions, and resolution workflows.
    ///
    /// Without a selector, returns account hashes, nicknames, balance summaries
    /// (margin or cash), day-trader and closing-only flags, and optionally open
    /// positions. With a selector alone, resolves an account hash or nickname to
    /// its canonical account hash. With a selector plus `--positions`, returns
    /// the matching account summary.
    #[command(after_help = "LLM workflow:\n  \
        schwab-agent account\n      \
        List account hashes, nicknames, account types, balance summaries, and account flags for every linked account.\n\n  \
        schwab-agent account --positions\n      \
        Include holdings as compact position objects for every linked account. Use this before allocation or order-planning decisions.\n\n  \
        schwab-agent account HASH_OR_NICKNAME\n      \
        Resolve a raw account hash or unique nickname to the canonical hash for --account on stock and order commands.\n\n  \
        schwab-agent account HASH_OR_NICKNAME --positions\n      \
        Return the selected account summary plus compact position objects instead of only resolving the hash.\n\n\
        Position objects include symbol, description, asset_type, long_quantity, short_quantity, average_price, market_value, current_day_profit_loss, and current_day_profit_loss_percentage when Schwab provides them.")]
    Account(AccountArgs),
}

/// Technical analysis commands.
#[derive(Debug, Subcommand)]
pub enum TaCommand {
    /// Run all indicators for a symbol and return a category-grouped dashboard.
    Dashboard(DashboardArgs),
    /// Compute expected move from the option chain's ATM straddle.
    #[command(name = "expected-move")]
    ExpectedMove(ExpectedMoveArgs),
}

/// Arguments for `ta dashboard`.
#[derive(Debug, Args)]
pub struct DashboardArgs {
    /// Ticker symbol, for example AAPL.
    #[arg(required = true)]
    pub symbol: String,
    /// Candle interval.
    #[arg(long, default_value = "daily")]
    pub interval: String,
    /// Number of data points to return per indicator series.
    #[arg(long, default_value = "20")]
    pub points: usize,
}

/// Arguments for `ta expected-move`.
#[derive(Debug, Args)]
pub struct ExpectedMoveArgs {
    /// Ticker symbol, for example AAPL.
    #[arg(required = true)]
    pub symbol: String,
    /// Target days to expiration for the option chain.
    #[arg(long, default_value = "30")]
    pub dte: u32,
}

/// Arguments for the top-level `analyze` command.
#[derive(Debug, Args)]
pub struct AnalyzeArgs {
    /// One or more ticker symbols to analyze.
    #[arg(required = true)]
    pub symbols: Vec<String>,
    /// Candle interval for the dashboard.
    #[arg(long, default_value = "daily")]
    pub interval: String,
    /// Number of data points to return per indicator series.
    #[arg(long, default_value = "1")]
    pub points: usize,
}

/// Authentication commands.
#[derive(Debug, Subcommand)]
pub enum AuthCommand {
    /// Show local token state without printing secrets.
    Status,
    /// Full interactive login: open browser, wait for a complete callback, exchange and save token.
    Login(LoginArgs),
    /// Build a browser authorization URL and open it in the default browser.
    LoginUrl(LoginUrlArgs),
    /// Exchange a pasted browser redirect URL for a saved token file.
    Exchange(AuthExchangeArgs),
    /// Force-refresh the saved token file.
    Refresh,
}

/// Arguments for `auth login`.
#[derive(Debug, Args)]
pub struct LoginArgs {
    /// Skip opening the authorization URL in the default browser.
    #[arg(long)]
    pub no_browser: bool,

    /// Seconds to wait for the callback before timing out.
    #[arg(long, default_value = "300")]
    pub timeout: u64,
}

/// Arguments for `auth login-url`.
#[derive(Debug, Args)]
pub struct LoginUrlArgs {
    /// Skip opening the authorization URL in the default browser.
    #[arg(long)]
    pub no_browser: bool,
}

/// Arguments for `auth exchange`.
#[derive(Debug, Args)]
pub struct AuthExchangeArgs {
    /// CSRF state returned by `auth login-url`.
    #[arg(long)]
    pub state: String,

    /// Full redirect URL copied from the browser address bar.
    #[arg(long)]
    pub redirect_url: String,
}

/// Market-data commands.
#[derive(Debug, Subcommand)]
pub enum MarketCommand {
    /// Get price history candles for a symbol.
    History(HistoryArgs),
    /// Get compact quote summaries for one or more symbols.
    Quote(QuoteArgs),
}

/// Option-chain, screening, and contract lookup commands.
#[derive(Debug, Subcommand)]
pub enum OptionCommand {
    /// Get expiration dates for an option symbol.
    Expirations(OptionExpirationsArgs),
    /// Get an option chain for a symbol.
    Chain(ChainArgs),
    /// Screen option chains with liquidity and pricing filters.
    Screen(ScreenArgs),
    /// Look up a single option contract.
    Contract(ContractArgs),
}

/// Arguments for `option expirations`.
#[derive(Debug, Args)]
pub struct OptionExpirationsArgs {
    /// Underlying symbol, for example AAPL.
    #[arg(required = true)]
    pub symbol: String,
}

/// Arguments for `option chain`.
#[derive(Debug, Args)]
pub struct ChainArgs {
    /// Underlying symbol, for example AAPL.
    #[arg(required = true)]
    pub symbol: String,

    /// Contract type filter, call, put, or all.
    #[arg(long = "type")]
    pub contract_type: Option<String>,

    /// Nearest expiration by days to expiration.
    #[arg(long, conflicts_with = "expiration")]
    pub dte: Option<i32>,

    /// Exact expiration date in YYYY-MM-DD format.
    #[arg(long, conflicts_with = "dte")]
    pub expiration: Option<String>,

    /// Minimum delta filter.
    #[arg(long)]
    pub delta_min: Option<f64>,

    /// Maximum delta filter.
    #[arg(long)]
    pub delta_max: Option<f64>,

    /// Comma-separated field list.
    #[arg(long)]
    pub fields: Option<String>,

    /// Number of strikes around at-the-money to include.
    #[arg(long)]
    pub strike_count: Option<u32>,

    /// Exact strike price.
    #[arg(long, conflicts_with_all = ["strike_min", "strike_max", "strike_count"])]
    pub strike: Option<f64>,

    /// Minimum strike price.
    #[arg(long)]
    pub strike_min: Option<f64>,

    /// Maximum strike price.
    #[arg(long)]
    pub strike_max: Option<f64>,

    /// Schwab strike range filter.
    #[arg(long)]
    pub strike_range: Option<String>,
}

/// Arguments for `option screen`.
#[derive(Debug, Args)]
pub struct ScreenArgs {
    /// Underlying symbol, for example AAPL.
    #[arg(required = true)]
    pub symbol: String,

    /// Contract type filter, call, put, or all.
    #[arg(long = "type")]
    pub contract_type: Option<String>,

    /// Minimum days to expiration.
    #[arg(long = "dte-min")]
    pub dte_min: Option<i32>,

    /// Maximum days to expiration.
    #[arg(long = "dte-max")]
    pub dte_max: Option<i32>,

    /// Exact expiration date in YYYY-MM-DD format.
    #[arg(long)]
    pub expiration: Option<String>,

    /// Minimum delta filter.
    #[arg(long)]
    pub delta_min: Option<f64>,

    /// Maximum delta filter.
    #[arg(long)]
    pub delta_max: Option<f64>,

    /// Comma-separated field list.
    #[arg(long)]
    pub fields: Option<String>,

    /// Number of strikes around at-the-money to include.
    #[arg(long)]
    pub strike_count: Option<u32>,

    /// Exact strike price.
    #[arg(long, conflicts_with_all = ["strike_min", "strike_max", "strike_count"])]
    pub strike: Option<f64>,

    /// Minimum strike price.
    #[arg(long)]
    pub strike_min: Option<f64>,

    /// Maximum strike price.
    #[arg(long)]
    pub strike_max: Option<f64>,

    /// Schwab strike range filter.
    #[arg(long)]
    pub strike_range: Option<String>,

    /// Minimum bid price.
    #[arg(long = "min-bid")]
    pub min_bid: Option<f64>,

    /// Maximum ask price.
    #[arg(long = "max-ask")]
    pub max_ask: Option<f64>,

    /// Minimum volume.
    #[arg(long = "min-volume")]
    pub min_volume: Option<u64>,

    /// Minimum open interest.
    #[arg(long = "min-oi")]
    pub min_oi: Option<u64>,

    /// Maximum spread percent.
    #[arg(long = "max-spread-pct")]
    pub max_spread_pct: Option<f64>,

    /// Minimum premium.
    #[arg(long = "min-premium")]
    pub min_premium: Option<f64>,

    /// Maximum premium.
    #[arg(long = "max-premium")]
    pub max_premium: Option<f64>,

    /// Sort field.
    #[arg(long)]
    pub sort: Option<String>,

    /// Maximum number of results.
    #[arg(long)]
    pub limit: Option<usize>,
}

/// Arguments for `option contract`.
#[derive(Debug, Args)]
#[command(group(
    ArgGroup::new("contract-side")
        .required(true)
        .args(["call", "put"])
))]
pub struct ContractArgs {
    /// Underlying symbol, for example AAPL.
    #[arg(required = true)]
    pub symbol: String,

    /// Exact expiration date in YYYY-MM-DD format.
    #[arg(long)]
    pub expiration: String,

    /// Exact strike price.
    #[arg(long)]
    pub strike: f64,

    /// Select a call contract.
    #[arg(long, conflicts_with = "put")]
    pub call: bool,

    /// Select a put contract.
    #[arg(long, conflicts_with = "call")]
    pub put: bool,
}

/// Arguments for `market history`.
#[derive(Debug, Args)]
pub struct HistoryArgs {
    /// Ticker symbol, for example AAPL.
    #[arg(required = true)]
    pub symbol: String,

    /// Comma-separated output fields. Defaults to ts,open,high,low,close,vol.
    #[arg(long, conflicts_with = "all_fields")]
    pub fields: Option<String>,

    /// Return the full Schwab price history object instead of compact rows.
    #[arg(long, conflicts_with = "fields")]
    pub all_fields: bool,

    /// Period type (day, month, year, ytd).
    #[arg(long)]
    pub period_type: Option<String>,

    /// Number of periods to return.
    #[arg(long)]
    pub period: Option<i64>,

    /// Frequency type (minute, daily, weekly, monthly).
    #[arg(long)]
    pub frequency_type: Option<String>,

    /// Frequency value (e.g. 1, 5, 15).
    #[arg(long)]
    pub frequency: Option<i64>,

    /// Start date in milliseconds since epoch.
    #[arg(long)]
    pub from: Option<i64>,

    /// End date in milliseconds since epoch.
    #[arg(long)]
    pub to: Option<i64>,

    /// Include extended-hours data.
    #[arg(long)]
    pub extended_hours: bool,
}

/// Arguments for `market quote`.
#[derive(Debug, Args)]
pub struct QuoteArgs {
    /// Symbols to quote, for example AAPL MSFT $SPX.
    #[arg(required = true)]
    pub symbols: Vec<String>,

    /// Comma-separated output fields. Defaults to req,sym,bid,ask,last,mark,chg,pct,vol,err.
    #[arg(long, conflicts_with = "all_fields")]
    pub fields: Option<String>,

    /// Return the full detailed quote object instead of compact rows.
    #[arg(long, conflicts_with = "fields")]
    pub all_fields: bool,

    /// Schwab quote field groups to request from the API, for example quote,reference.
    #[arg(long)]
    pub api_fields: Option<String>,
}

/// Arguments for `account`.
#[derive(Debug, Args)]
pub struct AccountArgs {
    /// Account hash or nickname to resolve. Omit to list account summaries.
    pub selector: Option<String>,

    /// Include individual positions in each account summary.
    #[arg(long)]
    pub positions: bool,
}

impl AccountArgs {
    /// Whether position data should be fetched from the API.
    ///
    /// Returns `true` when position data is explicitly requested.
    #[must_use]
    pub fn include_positions(&self) -> bool {
        self.positions
    }

    /// Whether the selector should return an account summary instead of a hash resolution.
    #[must_use]
    pub fn requests_summary(&self) -> bool {
        self.include_positions()
    }
}

// ---------------------------------------------------------------------------
// Unified order command types
// ---------------------------------------------------------------------------

/// Unified order command covering equity and option workflows.
///
/// Use `order equity` for stock trades and `order option` for option trades.
/// The `get`, `cancel`, `replace`, `repeat`, `place-from-preview`, `preview-raw`, and
/// `place-raw` subcommands work with orders of any type.
#[derive(Debug, Subcommand)]
pub enum OrderCommand {
    /// Equity (stock) order: buy, sell, sell-short, buy-to-cover.
    #[command(subcommand)]
    Equity(EquityArgs),
    /// Option order: buy-to-open, sell-to-open, buy-to-close, sell-to-close (OCC symbol required).
    #[command(subcommand)]
    Option(OptionArgs),
    /// Get active orders, symbol-filtered orders, or one exact order.
    #[command(
        after_help = "LLM selection guide:\n  schwab-agent order get\n      Get all active/open orders across every linked account. Use this first when you need current open orders and do not already know the account.\n\n  schwab-agent order get --account HASH_OR_NICKNAME\n      Get all active/open orders for one account. Use this when you already know which account to inspect.\n\n  schwab-agent order get --symbol IBM\n      Get active/open orders whose orderLegCollection includes an IBM instrument symbol. Matching is case-insensitive and includes multi-leg orders when any leg matches. Add --account to limit this to one account.\n\n  schwab-agent order get --include-inactive\n      Get active plus inactive orders across every linked account. Any returned status not listed in the active_statuses output field is treated as inactive. Add --account to limit this to one account.\n\n  schwab-agent order get --account HASH_OR_NICKNAME --order ORDER_ID\n      Get one exact order. Use this only when both the account and order ID are known. Do not combine --order with discovery filters such as --recent, --from, --to, --symbol, or --include-inactive.\n\nActive statuses are exact strings returned in the active_statuses output field."
    )]
    Get(crate::order::lifecycle::OrderGetArgs),
    /// Cancel an order by ID.
    ///
    /// After cancellation, verifies the status via a follow-up GET so
    /// the agent can confirm the order was actually canceled.
    Cancel(crate::order::lifecycle::OrderCancelArgs),
    /// Replace an existing order.
    Replace(ReplaceArgs),
    /// Repeat an existing order by rebuilding it as a new order payload.
    Repeat(crate::order::lifecycle::OrderRepeatArgs),
    /// Place an order from a previously saved preview digest.
    #[command(name = "place-from-preview")]
    PlaceFromPreview(PlaceFromPreviewArgs),
    /// Preview an arbitrary JSON order payload (for brackets, OCO, etc.).
    #[command(name = "preview-raw")]
    PreviewRaw(PreviewRawArgs),
    /// Place an arbitrary JSON order payload (for brackets, OCO, etc.).
    #[command(name = "place-raw")]
    PlaceRaw(PlaceRawArgs),
}

/// Equity (stock) order actions.
#[derive(Debug, Subcommand)]
pub enum EquityArgs {
    /// Buy shares.
    Buy(EquityOrderArgs),
    /// Sell shares.
    Sell(EquityOrderArgs),
    /// Sell shares short.
    #[command(name = "sell-short")]
    SellShort(EquityOrderArgs),
    /// Buy to cover a short position.
    #[command(name = "buy-to-cover")]
    BuyToCover(EquityOrderArgs),
}

/// Arguments for an equity order action.
#[derive(Debug, Args)]
pub struct EquityOrderArgs {
    /// Ticker symbol (e.g. AAPL, SPY).
    pub symbol: String,
    /// Number of shares.
    #[arg(short, long)]
    pub quantity: f64,
    /// Limit price (omit for market order; with --stop becomes stop-limit).
    #[arg(short, long)]
    pub price: Option<f64>,
    /// Stop trigger price (omit for market/limit; with --price becomes stop-limit).
    #[arg(long)]
    pub stop: Option<f64>,
    #[command(flatten)]
    pub common: CommonOrderArgs,
}

/// Option order actions using OCC symbols.
#[derive(Debug, Subcommand)]
pub enum OptionArgs {
    /// Buy to open a new option position.
    #[command(name = "buy-to-open")]
    BuyToOpen(OptionOrderArgs),
    /// Sell to open a new option position.
    #[command(name = "sell-to-open")]
    SellToOpen(OptionOrderArgs),
    /// Buy to close an existing option position.
    #[command(name = "buy-to-close")]
    BuyToClose(OptionOrderArgs),
    /// Sell to close an existing option position.
    #[command(name = "sell-to-close")]
    SellToClose(OptionOrderArgs),
}

/// Arguments for an option order action.
#[derive(Debug, Args)]
pub struct OptionOrderArgs {
    /// OCC option symbol (e.g. AAPL  250117C00150000).
    pub symbol: String,
    /// Number of contracts.
    #[arg(short, long)]
    pub quantity: f64,
    /// Limit price (omit for market order).
    #[arg(short, long)]
    pub price: Option<f64>,
    #[command(flatten)]
    pub common: CommonOrderArgs,
}

/// Arguments shared by equity and option order actions.
#[derive(Debug, Args)]
pub struct CommonOrderArgs {
    /// Account hash or nickname (omit for dry-run mode).
    #[arg(short, long)]
    pub account: Option<String>,
    /// Trading session.
    #[arg(long, default_value = "normal")]
    pub session: crate::shared::SessionChoice,
    /// Order duration.
    #[arg(long, default_value = "day")]
    pub duration: crate::shared::DurationChoice,
    /// Save order preview to disk (requires --account).
    #[arg(long, requires = "account")]
    pub save_preview: bool,
    /// Preview order first, then place automatically (requires --account).
    #[arg(long, requires = "account")]
    pub preview_first: bool,
}

/// Arguments for `order replace`.
#[derive(Debug, Args)]
pub struct ReplaceArgs {
    /// Account hash or nickname.
    #[arg(short, long)]
    pub account: String,
    /// Order ID to replace.
    #[arg(long, value_parser = clap::value_parser!(i64).range(1..))]
    pub order_id: i64,
    /// The replacement order.
    #[command(subcommand)]
    pub order_spec: ReplaceOrderSpec,
}

/// Replacement order payload (equity or option).
#[derive(Debug, Subcommand)]
pub enum ReplaceOrderSpec {
    /// Replace with an equity order.
    #[command(subcommand)]
    Equity(EquityArgs),
    /// Replace with an option order.
    #[command(subcommand)]
    Option(OptionArgs),
}

/// Arguments for `order place-from-preview`.
#[derive(Debug, Args)]
pub struct PlaceFromPreviewArgs {
    /// Account hash or nickname.
    #[arg(short, long)]
    pub account: String,
    /// SHA-256 digest from a previous preview --save-preview run.
    #[arg(short, long)]
    pub digest: String,
}

/// Arguments for `order preview-raw`.
#[derive(Debug, Args)]
pub struct PreviewRawArgs {
    /// Account hash or nickname.
    #[arg(long)]
    pub account: String,
    /// Save preview to disk after previewing.
    #[arg(long)]
    pub save_preview: bool,
    /// Complete order JSON payload (for brackets, OCO, triggers, etc.).
    #[arg(long)]
    pub json: String,
}

/// Arguments for `order place-raw`.
#[derive(Debug, Args)]
pub struct PlaceRawArgs {
    /// Account hash or nickname.
    #[arg(long)]
    pub account: String,
    /// Complete order JSON payload.
    #[arg(long)]
    pub json: String,
}

#[cfg(test)]
mod tests {
    use clap::{CommandFactory, Parser, error::ErrorKind};

    use super::{Cli, Command, MarketCommand, OrderCommand, TaCommand};

    #[test]
    fn command_tree_is_valid() {
        Cli::command().debug_assert();
    }

    #[test]
    fn order_get_help_renders_llm_guide_once() {
        let mut command = Cli::command();
        let help = command
            .find_subcommand_mut("order")
            .and_then(|order| order.find_subcommand_mut("get"))
            .map(|get| get.render_long_help().to_string())
            .expect("order get command exists");

        assert_eq!(help.matches("LLM selection guide:").count(), 1);
        assert!(help.contains("active_statuses output field"));
        assert!(help.contains("discovery filters"));
        assert!(help.contains("--symbol IBM"));
        assert!(help.contains("Matching is case-insensitive"));
    }

    #[test]
    fn account_help_includes_llm_workflow() {
        let mut command = Cli::command();
        let help = command
            .find_subcommand_mut("account")
            .map(|account| account.render_long_help().to_string())
            .expect("account command exists");

        assert_eq!(help.matches("LLM workflow:").count(), 1);
        assert!(!help.contains("Examples:"));
        assert!(!help.contains("--with-positions-only"));
        assert!(help.contains("schwab-agent account --positions"));
        assert!(help.contains("compact position objects"));
        assert!(help.contains("--account"));
    }

    #[test]
    fn command_name_auth_status() {
        let cli = Cli::parse_from(["schwab-agent", "auth", "status"]);
        assert_eq!(cli.command_name(), "auth.status");
    }

    #[test]
    fn command_name_auth_login() {
        let cli = Cli::parse_from(["schwab-agent", "auth", "login"]);
        assert_eq!(cli.command_name(), "auth.login");
    }

    #[test]
    fn command_name_analyze() {
        let cli = Cli::parse_from(["schwab-agent", "analyze", "AAPL"]);
        assert_eq!(cli.command_name(), "analyze");
    }

    #[test]
    fn command_name_auth_login_url() {
        let cli = Cli::parse_from(["schwab-agent", "auth", "login-url"]);
        assert_eq!(cli.command_name(), "auth.login_url");
    }

    #[test]
    fn command_name_auth_exchange() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "auth",
            "exchange",
            "--state",
            "abc",
            "--redirect-url",
            "https://example.com",
        ]);
        assert_eq!(cli.command_name(), "auth.exchange");
    }

    #[test]
    fn command_name_auth_refresh() {
        let cli = Cli::parse_from(["schwab-agent", "auth", "refresh"]);
        assert_eq!(cli.command_name(), "auth.refresh");
    }

    #[test]
    fn command_name_market_history() {
        let cli = Cli::parse_from(["schwab-agent", "market", "history", "AAPL"]);
        assert_eq!(cli.command_name(), "market.history");
    }

    #[test]
    fn command_name_market_history_with_all_flags() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "market",
            "history",
            "AAPL",
            "--fields",
            "ts,close,vol",
            "--period-type",
            "month",
            "--period",
            "3",
            "--frequency-type",
            "daily",
            "--frequency",
            "1",
            "--from",
            "1735689600000",
            "--to",
            "1743379200000",
            "--extended-hours",
        ]);
        assert_eq!(cli.command_name(), "market.history");
    }

    #[test]
    fn market_history_fields_parse_output_fields() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "market",
            "history",
            "AAPL",
            "--fields",
            "ts,close,vol",
        ]);

        let Command::Market(MarketCommand::History(args)) = cli.command else {
            panic!("expected market history command");
        };
        assert_eq!(args.fields.as_deref(), Some("ts,close,vol"));
        assert!(!args.all_fields);
    }

    #[test]
    fn market_history_all_fields_parses() {
        let cli = Cli::parse_from(["schwab-agent", "market", "history", "AAPL", "--all-fields"]);

        let Command::Market(MarketCommand::History(args)) = cli.command else {
            panic!("expected market history command");
        };
        assert!(args.all_fields);
        assert!(args.fields.is_none());
    }

    #[test]
    fn command_name_market_quote() {
        let cli = Cli::parse_from(["schwab-agent", "market", "quote", "AAPL"]);
        assert_eq!(cli.command_name(), "market.quote");
    }

    #[test]
    fn market_quote_fields_parse_output_and_api_fields() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "market",
            "quote",
            "AAPL",
            "--fields",
            "sym,last",
            "--api-fields",
            "quote,reference",
        ]);

        let Command::Market(MarketCommand::Quote(args)) = cli.command else {
            panic!("expected market quote command");
        };
        assert_eq!(args.fields.as_deref(), Some("sym,last"));
        assert_eq!(args.api_fields.as_deref(), Some("quote,reference"));
        assert!(!args.all_fields);
    }

    #[test]
    fn market_quote_all_fields_parses() {
        let cli = Cli::parse_from(["schwab-agent", "market", "quote", "AAPL", "--all-fields"]);

        let Command::Market(MarketCommand::Quote(args)) = cli.command else {
            panic!("expected market quote command");
        };
        assert!(args.all_fields);
        assert!(args.fields.is_none());
    }

    #[test]
    fn command_name_option_expirations() {
        let cli = Cli::parse_from(["schwab-agent", "option", "expirations", "AAPL"]);
        assert_eq!(cli.command_name(), "option.expirations");
    }

    #[test]
    fn command_name_option_chain() {
        let cli = Cli::parse_from(["schwab-agent", "option", "chain", "AAPL"]);
        assert_eq!(cli.command_name(), "option.chain");
    }

    #[test]
    fn command_name_option_screen() {
        let cli = Cli::parse_from(["schwab-agent", "option", "screen", "AAPL"]);
        assert_eq!(cli.command_name(), "option.screen");
    }

    #[test]
    fn command_name_option_contract() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "option",
            "contract",
            "AAPL",
            "--expiration",
            "2026-01-17",
            "--strike",
            "200",
            "--call",
        ]);
        assert_eq!(cli.command_name(), "option.contract");
    }

    #[test]
    fn command_name_account() {
        let cli = Cli::parse_from(["schwab-agent", "account"]);
        assert_eq!(cli.command_name(), "account");
    }

    #[test]
    fn command_name_account_with_positions() {
        let cli = Cli::parse_from(["schwab-agent", "account", "--positions"]);
        assert_eq!(cli.command_name(), "account");
    }

    #[test]
    fn command_name_account_with_selector() {
        let cli = Cli::parse_from(["schwab-agent", "account", "Trading"]);
        assert_eq!(cli.command_name(), "account");
    }

    #[test]
    fn command_name_ta_dashboard() {
        let cli = Cli::parse_from(["schwab-agent", "ta", "dashboard", "AAPL"]);
        assert_eq!(cli.command_name(), "ta.dashboard");
    }

    #[test]
    fn command_name_ta_expected_move() {
        let cli = Cli::parse_from(["schwab-agent", "ta", "expected-move", "AAPL"]);
        assert_eq!(cli.command_name(), "ta.expected-move");
    }

    #[test]
    fn parse_account_no_flags() {
        let cli = Cli::parse_from(["schwab-agent", "account"]);

        let Command::Account(args) = cli.command else {
            panic!("expected account command");
        };
        assert!(args.selector.is_none());
        assert!(!args.positions);
    }

    #[test]
    fn parse_account_positions() {
        let cli = Cli::parse_from(["schwab-agent", "account", "--positions"]);

        let Command::Account(args) = cli.command else {
            panic!("expected account command");
        };
        assert!(args.selector.is_none());
        assert!(args.positions);
        assert!(args.include_positions());
    }

    #[test]
    fn parse_account_with_positions_only_is_rejected() {
        let err = Cli::try_parse_from(["schwab-agent", "account", "--with-positions-only"])
            .expect_err("removed account flag should be rejected");

        assert!(err.to_string().contains("--with-positions-only"));
    }

    #[test]
    fn parse_account_fields_is_rejected() {
        let err =
            Cli::try_parse_from(["schwab-agent", "account", "--positions", "--fields", "sym"])
                .expect_err("removed account flag should be rejected");

        assert!(err.to_string().contains("--fields"));
    }

    #[test]
    fn parse_account_all_fields_is_rejected() {
        let err = Cli::try_parse_from(["schwab-agent", "account", "--positions", "--all-fields"])
            .expect_err("removed account flag should be rejected");

        assert!(err.to_string().contains("--all-fields"));
    }

    #[test]
    fn parse_account_no_flags_include_positions_false() {
        let cli = Cli::parse_from(["schwab-agent", "account"]);

        let Command::Account(args) = cli.command else {
            panic!("expected account command");
        };
        assert!(!args.include_positions());
    }

    #[test]
    fn parse_account_selector() {
        let cli = Cli::parse_from(["schwab-agent", "account", "Trading"]);

        let Command::Account(args) = cli.command else {
            panic!("expected account command");
        };
        assert_eq!(args.selector.as_deref(), Some("Trading"));
    }

    #[test]
    fn parse_account_selector_with_positions() {
        let cli = Cli::parse_from(["schwab-agent", "account", "--positions", "Trading"]);

        let Command::Account(args) = cli.command else {
            panic!("expected account command");
        };
        assert_eq!(args.selector.as_deref(), Some("Trading"));
        assert!(args.positions);
        assert!(args.include_positions());
        assert!(args.requests_summary());
    }

    #[test]
    fn parse_account_selector_before_positions() {
        let cli = Cli::parse_from(["schwab-agent", "account", "Trading", "--positions"]);

        let Command::Account(args) = cli.command else {
            panic!("expected account command");
        };
        assert_eq!(args.selector.as_deref(), Some("Trading"));
        assert!(args.positions);
        assert!(args.requests_summary());
    }

    #[test]
    fn parse_ta_dashboard_defaults() {
        let cli = Cli::parse_from(["schwab-agent", "ta", "dashboard", "AAPL"]);

        let Command::Ta(TaCommand::Dashboard(args)) = cli.command else {
            panic!("expected ta dashboard command");
        };
        assert_eq!(args.symbol, "AAPL");
        assert_eq!(args.interval, "daily");
        assert_eq!(args.points, 20);
    }

    #[test]
    fn parse_ta_dashboard_custom_interval_and_points() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "ta",
            "dashboard",
            "AAPL",
            "--interval",
            "weekly",
            "--points",
            "10",
        ]);

        let Command::Ta(TaCommand::Dashboard(args)) = cli.command else {
            panic!("expected ta dashboard command");
        };
        assert_eq!(args.symbol, "AAPL");
        assert_eq!(args.interval, "weekly");
        assert_eq!(args.points, 10);
    }

    #[test]
    fn parse_ta_expected_move_defaults() {
        let cli = Cli::parse_from(["schwab-agent", "ta", "expected-move", "AAPL"]);

        let Command::Ta(TaCommand::ExpectedMove(args)) = cli.command else {
            panic!("expected ta expected-move command");
        };
        assert_eq!(args.symbol, "AAPL");
        assert_eq!(args.dte, 30);
    }

    #[test]
    fn parse_ta_expected_move_custom_dte() {
        let cli = Cli::parse_from(["schwab-agent", "ta", "expected-move", "AAPL", "--dte", "45"]);

        let Command::Ta(TaCommand::ExpectedMove(args)) = cli.command else {
            panic!("expected ta expected-move command");
        };
        assert_eq!(args.symbol, "AAPL");
        assert_eq!(args.dte, 45);
    }

    #[test]
    fn parse_analyze_multiple_symbols() {
        let cli = Cli::parse_from(["schwab-agent", "analyze", "AAPL", "MSFT"]);

        let Command::Analyze(args) = cli.command else {
            panic!("expected analyze command");
        };
        assert_eq!(args.symbols, ["AAPL", "MSFT"]);
        assert_eq!(args.interval, "daily");
        assert_eq!(args.points, 1);
    }

    #[test]
    fn parse_analyze_custom_interval_and_points() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "analyze",
            "AAPL",
            "--interval",
            "daily",
            "--points",
            "5",
        ]);

        let Command::Analyze(args) = cli.command else {
            panic!("expected analyze command");
        };
        assert_eq!(args.symbols, ["AAPL"]);
        assert_eq!(args.interval, "daily");
        assert_eq!(args.points, 5);
    }

    #[test]
    fn parse_order_equity_buy_dry_run() {
        let cli = Cli::parse_from(["schwab-agent", "order", "equity", "buy", "AAPL", "-q", "10"]);

        assert_eq!(cli.command_name(), "order");

        let Command::Order(OrderCommand::Equity(super::EquityArgs::Buy(args))) = cli.command else {
            panic!("expected order equity buy command");
        };
        assert_eq!(args.symbol, "AAPL");
        assert_eq!(args.quantity, 10.0);
        assert!(args.price.is_none());
        assert!(args.stop.is_none());
        assert!(args.common.account.is_none());
        assert!(!args.common.save_preview);
    }

    #[test]
    fn parse_order_equity_buy_with_account_and_price() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "order",
            "equity",
            "buy",
            "AAPL",
            "-q",
            "10",
            "-p",
            "150.00",
            "-a",
            "HASH123",
        ]);

        let Command::Order(OrderCommand::Equity(super::EquityArgs::Buy(args))) = cli.command else {
            panic!("expected order equity buy command");
        };
        assert_eq!(args.symbol, "AAPL");
        assert_eq!(args.quantity, 10.0);
        assert_eq!(args.price, Some(150.0));
        assert_eq!(args.common.account.as_deref(), Some("HASH123"));
    }

    #[test]
    fn parse_order_equity_sell_short() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "order",
            "equity",
            "sell-short",
            "TSLA",
            "-q",
            "5",
            "--stop",
            "200.00",
        ]);

        let Command::Order(OrderCommand::Equity(super::EquityArgs::SellShort(args))) = cli.command
        else {
            panic!("expected order equity sell-short command");
        };
        assert_eq!(args.symbol, "TSLA");
        assert_eq!(args.quantity, 5.0);
        assert_eq!(args.stop, Some(200.0));
    }

    #[test]
    fn parse_order_option_buy_to_open() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "order",
            "option",
            "buy-to-open",
            "AAPL  250117C00150000",
            "-q",
            "1",
            "-p",
            "3.50",
            "-a",
            "HASH123",
            "--save-preview",
        ]);

        let Command::Order(OrderCommand::Option(super::OptionArgs::BuyToOpen(args))) = cli.command
        else {
            panic!("expected order option buy-to-open command");
        };
        assert_eq!(args.symbol, "AAPL  250117C00150000");
        assert_eq!(args.quantity, 1.0);
        assert_eq!(args.price, Some(3.50));
        assert_eq!(args.common.account.as_deref(), Some("HASH123"));
        assert!(args.common.save_preview);
    }

    #[test]
    fn parse_order_option_sell_to_close() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "order",
            "option",
            "sell-to-close",
            "AAPL  250117C00150000",
            "-q",
            "2",
        ]);

        let Command::Order(OrderCommand::Option(super::OptionArgs::SellToClose(args))) =
            cli.command
        else {
            panic!("expected order option sell-to-close command");
        };
        assert_eq!(args.symbol, "AAPL  250117C00150000");
        assert_eq!(args.quantity, 2.0);
        assert!(args.price.is_none());
        assert!(args.common.account.is_none());
    }

    #[test]
    fn parse_order_replace() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "order",
            "replace",
            "-a",
            "HASH123",
            "--order-id",
            "12345",
            "equity",
            "buy",
            "AAPL",
            "-q",
            "10",
            "-p",
            "150.00",
        ]);

        let Command::Order(OrderCommand::Replace(args)) = cli.command else {
            panic!("expected order replace command");
        };
        assert_eq!(args.account, "HASH123");
        assert_eq!(args.order_id, 12345);
    }

    #[test]
    fn parse_order_place_from_preview() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "order",
            "place-from-preview",
            "-a",
            "HASH123",
            "-d",
            "abc123",
        ]);

        let Command::Order(OrderCommand::PlaceFromPreview(args)) = cli.command else {
            panic!("expected order place-from-preview command");
        };
        assert_eq!(args.account, "HASH123");
        assert_eq!(args.digest, "abc123");
    }

    #[test]
    fn parse_order_preview_raw() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "order",
            "preview-raw",
            "--account",
            "HASH123",
            "--json",
            "{\"orderType\":\"LIMIT\"}",
            "--save-preview",
        ]);

        let Command::Order(OrderCommand::PreviewRaw(args)) = cli.command else {
            panic!("expected order preview-raw command");
        };
        assert_eq!(args.account, "HASH123");
        assert!(args.save_preview);
    }

    #[test]
    fn parse_order_place_raw() {
        let cli = Cli::parse_from([
            "schwab-agent",
            "order",
            "place-raw",
            "--account",
            "HASH123",
            "--json",
            "{\"orderType\":\"MARKET\"}",
        ]);

        let Command::Order(OrderCommand::PlaceRaw(args)) = cli.command else {
            panic!("expected order place-raw command");
        };
        assert_eq!(args.account, "HASH123");
    }

    #[test]
    fn stock_subcommand_is_removed() {
        let result = Cli::try_parse_from(["schwab-agent", "stock", "buy", "AAPL", "-q", "10"]);
        assert!(result.is_err());
    }

    #[test]
    fn removed_global_credential_flags_are_unknown() {
        for flag in [
            "--token",
            "--client-id",
            "--client-secret",
            "--callback-url",
        ] {
            let result = Cli::try_parse_from(["schwab-agent", flag, "value", "auth", "status"]);
            assert_eq!(result.unwrap_err().kind(), ErrorKind::UnknownArgument);
        }
    }
}