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
//! Represents a trade record containing various details about a trade.
//!
//! This struct is used primarily for deserializing trade details from external data sources,
//! such as JSON feeds or APIs. Each field corresponds to a specific attribute within the
//! trade data, and custom serialization mappings are configured using the `#[serde(rename)]` attribute.
//!
//! # Fields
//! - `symbol` (`String`): The ticker symbol of the asset involved in the trade (e.g., "AAPL").
//! It is deserialized from the `"S"` field in the source data.
//! - `trade_id` (`i64`): A unique identifier for the trade within the exchange. It is deserialized
//! from the `"i"` field.
//! - `exchange` (`String`): The specific exchange where the trade occurred. It is deserialized
//! from the `"x"` field.
//! - `price` (`f64`): The price per unit of the asset that was traded. It is deserialized from the
//! `"p"` field.
//! - `size` (`i64`): The quantity of the asset that was traded. It is deserialized from the `"s"` field.
//!
//! # Examples
//! ```rust
//! use serde::Deserialize;
//!
//! #[derive(Debug, Deserialize, Clone, Serialize)]
//! pub struct Trade {
//! #[serde(rename = "S")]
//! pub symbol: String,
//! #[serde(rename = "i")]
//! pub trade_id: i64,
//! #[serde(rename = "x")]
//! pub exchange: String,
//! #[serde(rename = "p")]
//! pub price: f64,
//! #[serde(rename = "s")]
//! pub size: i64,
//! }
//!
//! let json_data = r#"{
//! "S": "AAPL",
//! "i": 12345,
//! "x": "NYSE",
//! "p": 150.25,
//! "s": 50
//! }"#;
//!
//! let trade: Trade = serde_json::from_str(json_data).unwrap();
//! println!("{:?}", trade);
//! // Output: Trade { symbol: "AAPL", trade_id: 12345, exchange: "NYSE", price: 150.25, size: 50 }
//! ```
use ;
use ;
use ;
use ;
use ;
use Utf8Bytes;
use TypedBuilder;
use crate;
/// The `Subscribe` struct is used to define a subscription payload for various data streams,
/// such as trades, quotes, bars, daily bars, updated bars, statuses, luld events, and imbalances.
///
/// # Fields
///
/// - `trades` (`Vec<String>`):
/// A vector of strings specifying the symbols for which trade updates are subscribed to.
/// This field is serialized only if it is non-empty.
///
/// - `quotes` (`Vec<String>`):
/// A vector of strings specifying the symbols for which quote updates are subscribed to.
/// This field is serialized only if it is non-empty.
///
/// - `bars` (`Vec<String>`):
/// A vector of strings specifying the symbols for which bar (aggregated price/volume data) updates are subscribed to.
/// This field is serialized only if it is non-empty.
///
/// - `daily_bars` (`Vec<String>`):
/// A vector of strings specifying the symbols for which daily bar updates are subscribed to.
/// This field is serialized only if it is non-empty and is serialized with the key `dailyBars`.
///
/// - `updated_bars` (`Vec<String>`):
/// A vector of strings specifying the symbols for which updated bar data is subscribed to.
/// This field is serialized only if it is non-empty and is serialized with the key `updatedBars`.
///
/// - `statuses` (`Vec<String>`):
/// A vector of strings specifying the symbols for which status updates are subscribed to.
/// This field is serialized only if it is non-empty.
///
/// - `lulds` (`Vec<String>`):
/// A vector of strings specifying the symbols for which LULD (Limit Up / Limit Down) updates are subscribed to.
/// This field is serialized only if it is non-empty.
///
/// - `imbalances` (`Vec<String>`):
/// A vector of strings specifying the symbols for which imbalance updates are subscribed to.
/// This field is serialized only if it is non-empty.
///
/// # Attributes
///
/// - The struct implements:
/// - `Debug`: Enables debugging and printing of the struct.
/// - `Default`: Provides a default implementation for the struct.
/// - `Clone`: Allows cloning of the struct.
/// - `Serialize`: Allows serialization of the struct, with conditional serialization for empty fields.
///
/// - Serialization-specific options:
/// - Fields are skipped during serialization if their corresponding vectors are empty (`skip_serializing_if = "Vec::is_empty"`).
/// - Some fields (`daily_bars` and `updated_bars`) use custom field names (`dailyBars` and `updatedBars`) during serialization.
///
/// # Example
///
/// ```rust
/// use serde_json;
/// use rpaca::market_data::v2::stock_websocket::Subscribe;
///
/// let subscription = Subscribe {
/// trades: vec!["AAPL".to_string(), "GOOG".to_string()],
/// quotes: vec![],
/// bars: vec!["TSLA".to_string()],
/// daily_bars: vec![],
/// updated_bars: vec![],
/// statuses: vec![],
/// lulds: vec!["AMD".to_string()],
/// imbalances: vec![],
/// };
///
/// let serialized = serde_json::to_string(&subscription).unwrap();
/// println!("{}", serialized);
/// ```
/// A struct representing an acknowledgment for a subscription, which includes details
/// about the subscribed data streams.
///
/// The struct is deserialized from an external source, such as JSON, and uses optional
/// fields for each type of stream. Any unspecified stream data will default to an empty
/// vector.
///
/// Fields:
/// - `trades` (`Vec<String>`): A collection of subscribed trade channels (e.g., stock symbols)
/// that the user has successfully acknowledged. Defaults to an empty vector.
/// - `quotes` (`Vec<String>`): A collection of subscribed quote channels (e.g., stock symbols)
/// that are acknowledged. Defaults to an empty vector.
/// - `bars` (`Vec<String>`): A list of subscribed bar channels (e.g., stock symbols for candlestick
/// data). Defaults to an empty vector.
/// - `daily_bars` (`Vec<String>`): A list of subscribed daily bar channels, deserialized from
/// `"dailyBars"`. Represents daily candlestick data symbols. Defaults to an empty vector.
/// - `updated_bars` (`Vec<String>`): A list of subscribed updated bar channels, deserialized
/// from `"updatedBars"`. Represents continuously updated candlestick data. Defaults to an empty vector.
/// - `statuses` (`Vec<String>`): A collection of subscribed status channels (e.g., market or stock statuses).
/// Defaults to an empty vector.
/// - `lulds` (`Vec<String>`): A collection of subscribed limit up/limit down (LULD) channels. Defaults
/// to an empty vector.
/// - `imbalances` (`Vec<String>`): A collection of subscribed imbalance data channels, typically used
/// for tracking market imbalances. Defaults to an empty vector.
/// - `corrections` (`Vec<String>`): A collection of subscribed correction data channels, which include
/// adjustments to previously reported trade or quote information. Defaults to an empty vector.
/// - `cancel_errors` (`Vec<String>`): A collection of subscribed cancel error channels, deserialized
/// from `"cancelErrors"`. Represents cancellations or errors related to orders. Defaults to an empty vector.
/// A data structure representing a success message with an optional message and an optional code.
///
/// This structure is used to encapsulate information about a successful operation,
/// including an optional descriptive message (`msg`) and an optional numerical code (`code`).
/// It derives the `Debug`, `Deserialize`, and `Clone` traits to enable debugging, deserialization,
/// and cloning functionality.
///
/// # Fields
/// - `msg` (`Option<String>`): An optional string containing a success message. If `None`, no message is provided.
/// - `code` (`Option<i64>`): An optional integer representing a success code. If `None`, no code is provided.
///
/// # Examples
/// ```
/// use rpaca::market_data::v2::stock_websocket::SuccessMsg;
///
/// let success = SuccessMsg {
/// msg: Some("Operation completed successfully".to_string()),
/// code: Some(200),
/// };
///
/// println!("{:?}", success); // Output: SuccessMsg { msg: Some("Operation completed successfully"), code: Some(200) }
/// ```
///
/// This struct can be useful in scenarios where you need to return structured success information from a function or API.
/// Represents an error message with an optional message string and an optional error code.
///
/// # Fields
/// - `msg` (`Option<String>`): An optional string containing an error message. It can be `None` if no message is provided.
/// - `code` (`Option<i64>`): An optional 64-bit integer representing an error code. It can be `None` if no code is provided.
///
/// # Derives
/// - `Debug`: Allows instances of `ErrorMsg` to be formatted using the `fmt::Debug` trait for debugging purposes.
/// - `Deserialize`: Enables deserialization of `ErrorMsg` from various formats (e.g., JSON).
/// - `Clone`: Allows cloning of `ErrorMsg` instances to create deep copies.
///
/// # Example
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, Clone, Serialize)]
/// pub struct ErrorMsg {
/// pub msg: Option<String>,
/// pub code: Option<i64>,
/// }
///
/// let error = ErrorMsg {
/// msg: Some(String::from("An error occurred")),
/// code: Some(404),
/// };
///
/// println!("{:?}", error);
/// ```
/// Represents a trade record with various details about the trade.
///
/// This struct is used for deserialization of trade data, typically from JSON,
/// using Serde. Each field is mapped to a specific key in the source data
/// which is specified using the `#[serde(rename = "...")]` attribute.
///
/// Fields:
/// - `symbol`: The symbol or ticker of the asset being traded (e.g., "AAPL").
/// Represents a market quote for a specific financial instrument, including bid and ask details.
///
/// This struct is used to deserialize JSON data about market quotes and provides information such as
/// the symbol, bid/ask prices and sizes, exchange identifiers, and additional metadata.
///
/// Fields:
/// - `symbol` (`String`):
/// The ticker symbol of the financial instrument.
///
/// - `ask_exchange` (`String`):
/// Identifier for the exchange that provided the ask price.
///
/// - `ask_price` (`f64`):
/// The current asking price for the financial instrument.
///
/// - `ask_size` (`i64`):
/// The size (quantity) available at the ask price.
///
/// - `bid_exchange` (`String`):
/// Identifier for the exchange that provided the bid price.
///
/// - `bid_price` (`f64`):
/// The current bidding price for the financial instrument.
///
/// - `bid_size` (`i64`):
/// The size (quantity) available at the bid price.
///
/// - `conditions` (`Vec<String>`):
/// A list of conditions or qualifiers tied to the quote (if any).
///
/// - `timestamp` (`String`):
/// The time when the quote was recorded, formatted as an ISO 8601 string.
///
/// - `tape` (`String`):
/// The identifier for the tape (or market data stream) on which the quote is published.
///
/// This struct derives traits for `Debug`, `Clone`, and implements deserialization using `serde`.
///
/// A struct representing a financial trading bar (candlestick),
/// commonly used in financial data to depict price movements over a specific time period.
///
/// Each bar provides details about the symbol, open price, high price,
/// low price, close price, volume, volume-weighted average price, number of trades,
/// and the timestamp for the bar.
///
/// Fields:
///
/// * `symbol` (String): The trading symbol the data is associated with.
/// This is renamed in serialized data as "S".
///
/// * `open` (f64): The opening price of the symbol for the time period.
/// This is renamed in serialized data as "o".
///
/// * `high` (f64): The highest price of the symbol for the time period.
/// This is renamed in serialized data as "h".
///
/// * `low` (f64): The lowest price of the symbol for the time period.
/// This is renamed in serialized data as "l".
///
/// * `close` (f64): The closing price of the symbol for the time period.
/// This is renamed in serialized data as "c".
///
/// * `volume` (i64): The total trading volume during the time period.
/// This is renamed in serialized data as "v".
///
/// * `volume_weighted_avg_price` (f64): The volume-weighted average price for the symbol
/// during the time period. This is renamed in serialized data as "vw".
///
/// * `number_of_trades` (i64): The total number of trades that occurred during the time period.
/// This is renamed in serialized data as "n".
///
/// * `timestamp` (String): The timestamp indicating the end of the bar's time period
/// in ISO 8601 format. This is renamed in serialized data as "t".
///
/// Notes:
/// - This struct implements the `Debug`, `Deserialize`, and `Clone` traits.
/// - Compatible with Serde for convenient serialization and deserialization of the data format.
///
/// Represents a trade correction, which includes details of both the original and corrected trades.
///
/// This struct is used to deserialize information about trade corrections from an external source,
/// providing fields for the symbol, exchange code, trade prices, trade sizes, associated conditions,
/// timestamps, and tape identifiers.
///
/// # Fields
///
/// * `symbol` (`String`):
/// The symbol or ticker of the security related to the trade correction.
///
/// * `exchange_code` (`String`):
/// The exchange code identifying where the trade was executed.
///
/// * `original_trade_id` (`String`):
/// The unique identifier of the original trade before the correction.
///
/// * `original_trade_price` (`f64`):
/// The price associated with the original trade.
///
/// * `original_trade_size` (`i64`):
/// The size or quantity of the original trade.
///
/// * `original_trade_conditions` (`Vec<String>`):
/// A vector of conditions or attributes associated with the original trade (e.g., trade type tags).
///
/// * `corrected_trade_id` (`String`):
/// The unique identifier of the corrected trade after the modification.
///
/// * `corrected_trade_price` (`f64`):
/// The updated price associated with the corrected trade.
///
/// * `corrected_trade_size` (`i64`):
/// The updated size or quantity of the corrected trade.
///
/// * `corrected_trade_conditions` (`Vec<String>`):
/// A vector of conditions or attributes associated with the corrected trade.
///
/// * `timestamp` (`String`):
/// The timestamp (in string format) when the correction was applied.
///
/// * `tape` (`String`):
/// The tape identifier (e.g., A, B, or C) indicating where the information originated.
/// A data structure representing trade cancels and error information.
///
/// This structure captures details such as the trading symbol, trade ID, exchange, price, size,
/// action, timestamp, and tape associated with the event.
///
/// The struct is both `Debug` and `Clone` enabled for debugging purposes and easy duplication.
/// It also derives `Deserialize` to allow the struct to be deserialized from formats like JSON
/// using Serde. Field names are deserialized based on custom mappings provided with the `#[serde(rename = ...)]` attribute.
///
/// Fields:
/// - `symbol` (`String`): Represents the trading symbol associated with the trade.
/// Serialized/Deserialized as "S".
/// - `trade_id` (`i64`): The unique ID of the trade.
/// Serialized/Deserialized as "i".
/// - `trade_exchange` (`String`): Indicates the exchange where the trade was executed.
/// Serialized/Deserialized as "x".
/// - `trade_price` (`f64`): The price at which the trade occurred.
/// Serialized/Deserialized as "p".
/// - `trade_size` (`i64`): The size or volume of the trade.
/// Serialized/Deserialized as "s".
/// - `action` (`String`): The action associated with the trade (e.g., canceled, error, etc.).
/// Serialized/Deserialized as "a".
/// - `timestamp` (`String`): The timestamp of when the trade occurred or the event happened.
/// Serialized/Deserialized as "t".
/// - `tape` (`String`): The tape indicator, providing additional information about the trade.
/// Serialized/Deserialized as "z".
/// Represents the Limit Up-Limit Down (LULD) details for a specific financial instrument.
///
/// The `LimitUpLimitDown` structure is used to capture data related to the LULD mechanism,
/// which is designed to prevent excessive volatility in financial markets by setting
/// upper and lower price limits for a given symbol.
///
/// # Fields
///
/// * `symbol` (*String*): The ticker symbol of the financial instrument.
/// - Serialized as "S" in the data payload.
///
/// * `limit_up_price` (*f64*): The upper price limit for the symbol.
/// - Serialized as "u" in the data payload.
///
/// * `limit_down_price` (*f64*): The lower price limit for the symbol.
/// - Serialized as "d" in the data payload.
///
/// * `indicator` (*String*): An indicator providing additional information about the limits,
/// such as the type of restriction in force.
/// - Serialized as "i" in the data payload.
///
/// * `timestamp` (*String*): The timestamp indicating when the LULD information was generated.
/// - Serialized as "t" in the data payload.
///
/// * `tape` (*String*): An identifier for the market tape or data source for this information.
/// - Serialized as "z" in the data payload.
///
/// # Derives
///
/// This struct supports the following derived traits:
///
/// * `Debug`: Facilitates formatting for debugging purposes.
/// * `Deserialize`: Enables JSON deserialization into this struct.
/// * `Clone`: Allows creating deep copies of `LimitUpLimitDown` instances.
/// Struct representing the trading status of a financial instrument.
///
/// This struct captures details about the trading status of a given instrument
/// along with associated metadata such as the timestamp of the status and
/// other descriptive codes and messages.
///
/// # Fields
///
/// * `symbol` (`String`): The financial instrument or stock symbol.
/// This field is mapped from the `S` key in the serialized data.
///
/// * `status_code` (`String`): A code representing the trading status.
/// This field is mapped from the `sc` key in the serialized data.
///
/// * `status_message` (`String`): A descriptive message associated with the trading status.
/// This field is mapped from the `sm` key in the serialized data.
///
/// * `reason_code` (`String`): A code that indicates the reason for the current trading status.
/// This field is mapped from the `rc` key in the serialized data.
///
/// * `reason_message` (`String`): A descriptive message explaining the reason for the trading status.
/// This field is mapped from the `rm` key in the serialized data.
///
/// * `timestamp` (`String`): A timestamp indicating when the trading status was recorded.
/// This field is mapped from the `t` key in the serialized data.
///
/// * `tape` (`String`): An identifier for the data source or market tape where the status was recorded.
/// This field is mapped from the `z` key in the serialized data.
///
/// # Traits
///
/// This struct derives the following traits:
/// * `Debug`: Allows the struct to be formatted using the `{:?}` formatter.
/// * `Deserialize`: Enables deserialization of the struct from formats supported by `serde`.
/// * `Clone`: Enables cloning of the struct to create duplicate instances.
/// * `Serialize`: Enables serialization of the struct to formats supported by `serde`.
///
/// # Examples
///
/// ```rust
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Deserialize, Clone, Serialize)]
/// pub struct TradingStatus {
/// #[serde(rename = "S")] pub symbol: String,
/// #[serde(rename = "sc")] pub status_code: String,
/// #[serde(rename = "sm")] pub status_message: String,
/// #[serde(rename = "rc")] pub reason_code: String,
/// #[serde(rename = "rm")] pub reason_message: String,
/// #[serde(rename = "t")] pub timestamp: String,
/// #[serde(rename = "z")] pub tape: String,
/// }
/// ```
/// Represents an `OrderImbalances` structure that contains information about market order imbalances.
///
/// This structure is deserialized from external data (e.g., JSON) using Serde's `Deserialize` trait
/// and includes the following fields:
///
/// # Fields
/// - `symbol` (`String`): The market symbol or ticker associated with the order imbalance.
/// This field is deserialized from the `S` key.
/// - `price` (`f64`): The price value associated with the order imbalance.
/// This field is deserialized from the `p` key.
/// - `timestamp` (`String`): The timestamp indicating when the data was collected/recorded.
/// This field is deserialized from the `t` key.
/// - `tape` (`String`): The exchange or data tape identifier where the imbalance data is sourced from.
/// This field is deserialized from the `z` key.
///
/// The structure derives the following traits:
/// - `Debug`: For easy debugging and formatting.
/// - `Clone`: To allow cloning of `OrderImbalances` instances.
/// - `Deserialize`: To facilitate deserialization from structured data formats, such as JSON.
/// Represents a message related to stock market data or administrative events.
///
/// The `StockMsg` enum is deserialized from a JSON object containing a `T` field,
/// which determines the type of message. Each variant corresponds to a specific
/// message type.
///
/// # Variants
///
/// ## Market Data
///
/// - `Trade(Trade)`:
/// Represents a trade message. Serialized with `"T": "t"`.
///
/// - `Quote(Quote)`:
/// Represents a quote message. Serialized with `"T": "q"`.
///
/// - `Bar(Bar)`:
/// Represents an aggregated time period (bar) message. Serialized with `"T": "b"`.
///
/// - `DailyBar(Bar)`:
/// Represents a daily bar message. Serialized with `"T": "d"`.
///
/// - `UpdatedBar(Bar)`:
/// Represents an updated bar message. Serialized with `"T": "u"`.
///
/// - `TradeCorrections(TradeCorrections)`:
/// Represents corrections to previously reported trades. Serialized with `"T": "c"`.
///
/// - `TradeCancelsAndErrors(TradeCancelsAndErrors)`:
/// Represents canceled or erroneous trades. Serialized with `"T": "x"`.
///
/// - `LimitUpLimitDown(LimitUpLimitDown)`:
/// Represents messages pertaining to Limit-Up/Limit-Down (LULD) events.
/// Serialized with `"T": "l"`.
///
/// - `TradingStatus(TradingStatus)`:
/// Represents trading status updates for securities. Serialized with `"T": "s"`.
///
/// - `OrderImbalances(OrderImbalances)`:
/// Represents messages about order imbalances. Serialized with `"T": "i"`.
///
/// ## Administrative
///
/// - `Subscription(SubscriptionAck)`:
/// Acknowledges a subscription request for specific data streams.
/// Serialized with `"T": "subscription"`.
///
/// - `Success(SuccessMsg)`:
/// Represents a success message, typically in response to a successful request.
/// Serialized with `"T": "success"`.
///
/// - `Error(ErrorMsg)`:
/// Represents an error message, usually in response to a failed or invalid request.
/// Serialized with `"T": "error"`.
///
/// # Serialization and Deserialization
///
/// Uses the `Serde` crate for deserialization and is tagged with a `T` field.
/// The `#[serde(rename = "...")]` attribute maps the variant to the expected
/// string identifier in the JSON data.
/// Represents parameters required to configure a stock data stream.
///
/// This struct contains the endpoint, feed path, and subscription information
/// necessary to establish a connection to the stock data stream service (e.g., Alpaca).
/// It uses the `TypedBuilder` crate to easily create instances with default values
/// for the `endpoint` and `feed_path` fields.
///
/// # Fields
///
/// * `endpoint` (String):
/// - The WebSocket URL of the stock data stream server.
/// - Defaults to `"wss://stream.data.alpaca.markets/"`.
/// - Example: `"wss://stream.data.sandbox.alpaca.markets"`.
///
/// * `feed_path` (String):
/// - The subpath identifying the specific data feed to be accessed.
/// - Defaults to `"v2/iex"`.
/// - Examples of possible values:
/// - `"v2/iex"`: IEX data feed.
/// - `"v2/sip"`: SIP (Securities Information Processor) data feed.
/// - `"v2/delayed_sip"`: Delayed SIP feed.
/// - `"v1beta1/boats"`: Experimental "boats" data feed.
/// - `"v1beta1/overnight"`: Experimental overnight data feed.
///
/// * `subscription` (Subscribe):
/// - Defines specific subscription details (e.g., ticker symbols or channels)
/// for the stock data stream.
/// - This field is required and does not have a default value.
///
/// # Usage
///
/// ```
/// use rpaca::market_data::v2::stock_websocket::StockStreamParams;
/// use rpaca::market_data::v2::stock_websocket::Subscribe;
///
/// let params = StockStreamParams::builder()
/// .subscription(Subscribe::new(/* subscription details */))
/// .build();
///
/// println!("{:?}", params);
/// ```
/// Streams real-time stock data using WebSocket connectivity to the specified Alpaca endpoint.
///
/// This function establishes a WebSocket connection to the provided stock data feed endpoint,
/// handles authentication, subscribes to the desired streams, and continuously streams
/// messages back to the caller until the connection is closed or interrupted. If the connection
/// fails or is terminated, the function automatically attempts to reconnect using an exponential
/// backoff strategy.
///
/// # Parameters
///
/// - `alpaca`: A reference to an [`Alpaca`] instance containing the API key/secret required for
/// authentication.
/// - `params`: The [`StockStreamParams`] struct specifying the endpoint URL, feed path, and the
/// desired subscription actions.
///
/// # Returns
///
/// Returns a `Result` wrapping an async [`Stream`], where each item is either:
/// - `Ok(StockMsg)`: A successfully received stock message (such as trade, quote, or other events).
/// - `Err(anyhow::Error)`: An error that occurred during the streaming process, such as connection
/// issues or decoding failures.
///
/// # Behavior
///
/// 1. The function opens a WebSocket connection to the specified feed path.
/// 2. Authenticates the connection with the given API key and secret.
/// 3. Subscribes to the requested stock data streams using the subscription actions provided
/// in `params`.
/// 4. Continuously listens for incoming messages and forwards them to the consumer via a
/// channel-backed [`Stream`].
/// 5. Automatically reconnects on failure with an exponentially increasing backoff up to a maximum limit.
///
/// # Errors
///
/// The function returns an error in the following scenarios:
/// - WebSocket connection failures (e.g., unreachable endpoint, network disruptions).
/// - Authentication errors (e.g., invalid API key or secret).
/// - Decoding issues when parsing incoming messages as [`StockMsg`].
///
/// # Reconnection
///
/// If the connection fails (e.g., due to network errors or server-side issues), the function
/// attempts to reconnect with an exponential backoff (up to 6 retries, capping at approximately
/// 16 seconds between attempts). The stream continues to emit data seamlessly if reconnected
/// successfully.
///
/// # Notes
///
/// - The connection remains active and streams data until interrupted or closed by the client/server.
/// - The function uses [`tokio::sync::mpsc`] for channel-based communication and wraps the receiver
/// with a [`tokio_stream::wrappers::ReceiverStream`] for consumption.
///
/// [`Alpaca`]: struct.Alpaca.html
/// [`StockStreamParams`]: struct.StockStreamParams.html
/// [`Stream`]: https://docs.rs/futures-core/latest/futures_core/stream/trait.Stream.html
/// [`StockMsg`]: enum.StockMsg.html
pub async
async