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
//! Represents an error message structure typically used for structured error handling or reporting.
//!
//! This struct is used to encapsulate a generic error message and
//! an associated optional error code. Both fields are optional to provide flexibility in error representation.
//!
//! # Fields
//! - `msg`:
//! An optional string containing a human-readable error message. For example,
//! this could describe the specific error encountered, such as "Invalid API Key".
//!
//! - `code`:
//! An optional integer representing an error status code. This can be useful
//! for programmatically identifying the type of error in applications.
//!
//! # Derives
//! - `Debug`: Enables the struct to be formatted and displayed using the `{:?}` formatter,
//! ideal for debugging purposes.
//! - `Deserialize`: Facilitates the deserialization of this struct from serialized formats, such as JSON.
//! - `Clone`: Allows this struct to be cloned, providing the ability to easily create duplicate instances of the error.
use ;
use ;
use ;
use ;
use ;
use Utf8Bytes;
use TypedBuilder;
use crate;
/// An enumeration `NumF64` that represents a number which can be one of three types:
/// - `i64`: A signed 64-bit integer.
/// - `f64`: A 64-bit floating-point number.
/// - `String`: A textual representation.
///
/// This enum is:
/// - Derived with `Deserialize` from Serde, allowing it to be deserialized from different formats (e.g., JSON).
/// - Clone-able to easily create duplicates of the value.
/// - Debuggable to enable debugging using the `Debug` formatter.
///
/// Additionally, `#[serde(untagged)]` indicates that Serde will infer the variant to deserialize
/// based on the input type, rather than requiring a tag to distinguish between variants.
///
/// ## Example
///
/// ```rust
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Debug)]
/// #[serde(untagged)]
/// pub enum NumF64 {
/// I(i64),
/// F(f64),
/// S(String),
/// }
///
/// let json_integer = "42";
/// let parsed: NumF64 = serde_json::from_str(json_integer).unwrap();
/// assert!(matches!(parsed, NumF64::I(42)));
///
/// let json_float = "42.42";
/// let parsed: NumF64 = serde_json::from_str(json_float).unwrap();
/// assert!(matches!(parsed, NumF64::F(42.42)));
///
/// let json_string = "\"42\"";
/// let parsed: NumF64 = serde_json::from_str(json_string).unwrap();
/// assert!(matches!(parsed, NumF64::S(ref s) if s == "42"));
/// ```
/// The `Subscribe` struct is used to manage subscription requests for different types of market data.
/// Each field represents a subscription group, allowing customization of which data streams to subscribe to.
///
/// # Fields
///
/// * `trades` - A vector of strings representing the trade symbols to subscribe to.
/// If empty, this field will be skipped during serialization.
///
/// * `quotes` - A vector of strings representing the quote symbols to subscribe to.
/// If empty, this field will be skipped during serialization.
///
/// * `bars` - A vector of strings representing the bar (candlestick) symbols to subscribe to.
/// If empty, this field will be skipped during serialization.
///
/// * `daily_bars` (serialized as `dailyBars`) - A vector of strings representing
/// the symbols for daily bar data (e.g., daily candlesticks) to subscribe to.
/// If empty, this field will be skipped during serialization.
///
/// * `updated_bars` (serialized as `updatedBars`) - A vector of strings representing
/// the symbols for updated bar data to subscribe to.
/// If empty, this field will be skipped during serialization.
///
/// * `orderbooks` - A vector of strings representing the symbols for order book data to subscribe to.
/// If empty, this field will be skipped during serialization.
///
/// # Traits
///
/// * `Debug` - Enables formatting of the `Subscribe` struct for debugging purposes.
/// * `Default` - Provides a default implementation where all subscription vectors are empty.
/// * `Clone` - Enables cloning of the `Subscribe` struct.
/// * `Serialize` - Allows serialization of the struct into formats like JSON, with custom rules applied
/// (e.g., skipping empty fields and renaming some fields).
/// `SubscriptionAck` is a structure representing the acknowledgment of a subscription to various types of market data streams.
/// It contains information about the data streams successfully acknowledged by the server.
///
/// # Fields
///
/// * `trades` - A vector of strings representing the symbols for which trade-related data is acknowledged as subscribed.
/// Defaults to an empty vector if not specified.
///
/// * `quotes` - A vector of strings representing the symbols for which quote-related data is acknowledged as subscribed.
/// Defaults to an empty vector if not specified.
///
/// * `bars` - A vector of strings representing the symbols for which bar-related (e.g., candlestick) data is acknowledged as subscribed.
/// Defaults to an empty vector if not specified.
///
/// * `daily_bars` (`dailyBars`) - A vector of strings representing the symbols for which daily bar-related data
/// is acknowledged as subscribed. This field is deserialized from the key `dailyBars` in a serialized structure.
/// Defaults to an empty vector if not specified.
///
/// * `updated_bars` (`updatedBars`) - A vector of strings representing the symbols for which updated bar-related data
/// is acknowledged as subscribed. This field is deserialized from the key `updatedBars` in a serialized structure.
/// Defaults to an empty vector if not specified.
///
/// * `orderbooks` - A vector of strings representing the symbols for which order book data is acknowledged as subscribed.
/// Defaults to an empty vector if not specified.
///
/// # Derived Traits
///
/// * `Debug` - Enables formatting of the structure for debugging purposes.
/// * `Deserialize` - Provides deserialization capabilities to convert structured data (e.g., from JSON) into a `SubscriptionAck` instance.
/// * `Clone` - Allows creating a deep copy of the structure.
///
/// # Usage Example
///
/// ```rust
/// use serde::Deserialize;
/// use rpaca::market_data::v2::crypto_websocket::{SubscriptionAck, NumF64};
///
/// let json_data = r#"
/// {
/// "trades": ["AAPL", "GOOG"],
/// "quotes": ["TSLA"],
/// "dailyBars": ["MSFT"]
/// }
/// "#;
///
/// let subscription_ack: SubscriptionAck = serde_json::from_str(json_data).unwrap();
///
/// assert_eq!(subscription_ack.trades, vec!["AAPL", "GOOG"]);
/// assert_eq!(subscription_ack.quotes, vec!["TSLA"]);
/// assert_eq!(subscription_ack.daily_bars, vec!["MSFT"]);
/// assert!(subscription_ack.bars.is_empty());
/// assert!(subscription_ack.updated_bars.is_empty());
/// assert!(subscription_ack.orderbooks.is_empty());
/// ```
/// Represents a success message structure typically used for responses.
///
/// This struct is used to encapsulate a generic success message and
/// an associated optional status code. Both fields are optional to allow
/// for flexibility in different use cases.
///
/// # Fields
/// - `msg`:
/// An optional string containing a human-readable success message. For example,
/// it could be a message like "Operation successful".
///
/// - `code`:
/// An optional integer representing a success status code. This is typically
/// used for applications where success codes (non-error codes) need to be passed back.
///
/// # Derives
/// - `Debug`: Allows the struct to be formatted using the `{:?}` formatter,
/// useful for debugging purposes.
/// - `Deserialize`: Enables deserialization from formats like JSON.
/// - `Clone`: Allows the struct to be cloned, useful in scenarios where
/// multiple copies of the structure need to exist.
///
/// A struct that represents an error message with an optional message and optional error code.
///
/// This struct is commonly used to encapsulate error-related information in a structured format.
/// It derives the `Debug`, `Deserialize`, and `Clone` traits, which allow for debugging output,
/// deserialization from formats like JSON, and cloning of the struct, respectively.
///
/// Fields:
///
/// * `msg` - An optional String field that represents the error message.
/// If present, this contains a human-readable description of the error.
///
/// * `code` - An optional i64 field that represents the error code.
/// If present, this typically contains a machine-readable code corresponding to the error.
///
/// Example:
///
/// ```
/// 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 unknown error occurred")),
/// code: Some(500),
/// };
///
/// println!("{:?}", error); // Output: ErrorMsg { msg: Some("An unknown error occurred"), code: Some(500) }
/// ```
/// A data structure representing a trade event in the system.
///
/// This struct is deserialized from a JSON payload and contains the key details
/// of a trade, such as the traded symbol, price, size, timestamp, trade ID, and
/// the side of the trade (taker or maker).
///
/// # Fields
/// - `symbol` (`String`): The trading symbol (e.g., "BTCUSD") representing the currency pair.
/// This field is deserialized from the `S` field in the JSON payload.
/// - `price` (`f64`): The price at which the trade was executed.
/// This field is deserialized from the `p` field in the JSON payload.
/// - `size` (`f64`): The size or quantity of the asset involved in the trade.
/// This field is deserialized from the `s` field in the JSON payload.
/// - `timestamp` (`String`): A timestamp indicating when the trade occurred. It is generally
/// provided in ISO 8601 or Unix epoch timestamp format.
/// This field is deserialized from the `t` field in the JSON payload.
/// - `trade_id` (`NumF64`): The unique identifier for the trade. This is deserialized
/// from the `i` field in the JSON payload.
/// - `taker_side` (`String`): Indicates whether the trade was initiated by a taker
/// on the buy side (`"BUY"`) or the sell side (`"SELL"`). This field is deserialized
/// from the `tks` field in the JSON payload.
///
/// # Derives
/// - `Debug`: Allows the `Trade` struct to be formatted using the `{:?}` formatter, useful for debugging purposes.
/// - `Deserialize`: Enables the deserialization of the `Trade` struct from JSON using Serde.
/// - `Clone`: Allows the `Trade` struct to be duplicated (cloned) with the same field values.
///
/// # Example
/// ```rust
/// use serde_json::from_str;
/// use rpaca::market_data::v2::crypto_websocket::{Trade, NumF64};
///
/// let json_trade = r#"{
/// "S": "BTCUSD",
/// "p": 34000.00,
/// "s": 1.25,
/// "t": "2023-10-15T12:34:56Z",
/// "i": 1029384756,
/// "tks": "BUY"
/// }"#;
///
/// let trade: Trade = from_str(json_trade).unwrap();
///
/// println!("{:?}", trade);
/// ```
///
/// This will produce:
/// ```text
/// Trade {
/// symbol: "BTCUSD",
/// price: 34000.0,
/// size: 1.25,
/// timestamp: "2023-10-15T12:34:56Z",
/// trade_id: 1029384756.0,
/// taker_side: "BUY"
/// }
/// ```
/// Represents financial market data for a specific trading instrument,
/// encapsulating bid and ask prices, their respective sizes, and a timestamp.
///
/// This struct is primarily used for deserializing data from an external API or data source,
/// and leverages the `serde` library for mapping incoming JSON structures to Rust types.
///
/// # Fields
///
/// * `symbol` (`String`):
/// Represents the symbol (ticker) of the trading instrument, e.g., "AAPL" for Apple Inc.
/// Deserialized from the JSON key `"S"`.
///
/// * `bid_price` (`f64`):
/// The best bid (highest price a buyer is willing to pay) for the instrument.
/// Deserialized from the JSON key `"bp"`.
///
/// * `bid_size` (`f64`):
/// The size (quantity) associated with the best bid.
/// Deserialized from the JSON key `"bs"`.
///
/// * `ask_price` (`f64`):
/// The best ask (lowest price a seller is willing to accept) for the instrument.
/// Deserialized from the JSON key `"ap"`.
///
/// * `ask_size` (`f64`):
/// The size (quantity) associated with the best ask.
/// Deserialized from the JSON key `"as"`.
///
/// * `timestamp` (`String`):
/// The timestamp indicating when the quote data was recorded or received.
/// Deserialized from the JSON key `"t"`.
///
/// # Trait Implementations
///
/// * `Debug`: Enables the struct to be formatted using the `{:?}` formatter for debugging purposes.
/// * `Deserialize`: Allows the struct to be deserialized from formats like JSON or other supported data sources.
/// * `Clone`: Enables the creation of a copy of the struct.
///
/// # Example
///
/// ```rust
/// use serde::Deserialize;
/// use rpaca::market_data::v2::crypto_websocket::Quote;
///
/// let json_data = r#"{
/// "S": "AAPL",
/// "bp": 145.32,
/// "bs": 100.0,
/// "ap": 145.35,
/// "as": 120.0,
/// "t": "2023-10-16T12:00:00Z"
/// }"#;
///
/// let quote: Quote = serde_json::from_str(json_data).unwrap();
///
/// println!("{:?}", quote);
/// ```
///
/// In this example, the JSON data is successfully deserialized into a `Quote` instance,
/// which then prints the associated fields for easy inspection.
/// The `Bar` struct represents a trading data entity, commonly used in financial markets
/// to encapsulate data for a single period of time in a candlestick format.
///
/// Each field in the struct is deserialized from an external data source, where
/// the field names are mapped to the corresponding keys in the source via the `#[serde(rename = "...")]` attribute.
///
/// # Fields
///
/// * `symbol` (`String`) - The trading symbol of the asset, deserialized from the `"S"` key.
/// * `open` (`f64`) - The opening price for the trading period, deserialized from the `"o"` key.
/// * `high` (`f64`) - The highest price during the trading period, deserialized from the `"h"` key.
/// * `low` (`f64`) - The lowest price during the trading period, deserialized from the `"l"` key.
/// * `close` (`f64`) - The closing price for the trading period, deserialized from the `"c"` key.
/// * `volume` (`NumF64`) - The trading volume during the period, which is represented as a `NumF64` type, deserialized from the `"v"` key.
/// * `timestamp` (`String`) - The timestamp for the trading data, typically in ISO 8601 format, deserialized from the `"t"` key.
///
/// # Traits
///
/// * `Debug` - Enables the struct to be formatted using the `{:?}` formatter, useful for debugging and logging.
/// * `Deserialize` - Allows the struct to be deserialized from an external data source (e.g., JSON).
/// * `Clone` - Allows for creating a duplicate of the `Bar` instance.
/// This struct is commonly used for processing market data, such as candlestick data in financial applications.
/// A struct representing a level with two parameters.
///
/// The `Level` struct is used to define a level with numerical values for parameters `p` and `s`.
/// This struct derives the `Debug`, `Deserialize`, and `Clone` traits, making it useful for debugging,
/// deserialization (e.g., from a file or API), and cloning.
///
/// Fields:
/// - `p` (`f64`): A floating-point value representing the primary parameter of the level.
/// - `s` (`f64`): A floating-point value representing the secondary parameter of the level.
///
/// Example:
/// ```
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, Clone, Serialize)]
/// pub struct Level {
/// pub p: f64,
/// pub s: f64,
/// }
///
/// let level = Level { p: 1.23, s: 4.56 };
/// println!("{:?}", level); // Outputs: Level { p: 1.23, s: 4.56 }
/// ```
/// Represents an orderbook structure, which contains information about bids and asks
/// for a specific trading symbol at a given timestamp.
///
/// The `Orderbook` struct is used to deserialize data typically obtained from market
/// data feeds. It supports additional metadata such as a reset flag to indicate the
/// need to refresh the orderbook state.
///
/// # Fields
///
/// * `symbol` (`String`):
/// The trading symbol or market identifier, such as "BTCUSD" or "ETHUSDT".
/// This field is deserialized from the "S" key in the source data.
///
/// * `timestamp` (`String`):
/// A string representing the timestamp at which the orderbook data was created
/// or updated. This is deserialized from the "t" key in the source data.
///
/// * `bids` (`Vec<Level>`):
/// A vector of bid levels representing buy orders in the orderbook.
/// Each item in this vector corresponds to a price level and its associated quantity.
/// This is deserialized from the "b" key in the source data.
///
/// * `asks` (`Vec<Level>`):
/// A vector of ask levels representing sell orders in the orderbook.
/// Like `bids`, each item corresponds to a price level and its associated quantity.
/// This is deserialized from the "a" key in the source data.
///
/// * `reset` (`Option<bool>`
/// Represents various types of stock market messages that can be deserialized and processed.
/// This enum leverages `serde` for deserialization and is tagged using the `T` field to determine the variant type.
///
/// Variants:
/// - `Trade`: Represents a trade message, tagged as `"t"`.
/// - `Quote`: Represents a quote message, tagged as `"q"`.
/// - `Bar`: Represents a bar message containing aggregated market data for a specific interval, tagged as `"b"`.
/// - `DailyBar`: Represents a daily bar message, tagged as `"d"`.
/// - `UpdatedBar`: Represents an updated bar message, tagged as `"u"`.
/// - `Orderbook`: Represents an order book message, tagged as `"o"`.
/// - `Subscription`: Acknowledges a successful subscription to specific data streams, tagged as `"subscription"`.
/// - `Success`: Represents a success message, indicating an operation was successful, tagged as `"success"`.
/// - `Error`: Represents an error message, indicating an issue or problem, tagged as `"error"`.
///
/// Each variant corresponds to a specific message type and is deserialized according to the provided tag.
///
/// This enum is derivable as `Debug` and `Clone` and requires deserialization through the `serde` library.
/// Represents the parameters required to set up a crypto data WebSocket stream.
///
/// # Fields
///
/// * `endpoint`
/// - The WebSocket endpoint URL used to establish the crypto data stream connection.
/// - Defaults to `"wss://stream.data.alpaca.markets/v1beta3/crypto/us"`.
/// - Example: `"wss://stream.data.sandbox.alpaca.markets"`.
///
/// * `subscription`
/// - The subscription details specifying the crypto data streams/topics to subscribe to.
///
/// Streams cryptocurrency data using the Alpaca WebSocket API.
///
/// This asynchronous function establishes a WebSocket connection to Alpaca's
/// cryptocurrency streaming API, handles authentication, subscribes to the
/// provided crypto stream channels, and continuously streams data. It handles
/// automatic reconnection with an exponential backoff strategy in case of
/// errors such as dropped connections or authentication issues.
///
/// # Parameters
///
/// - `alpaca`: A reference to an [`Alpaca`] client that contains the API key
/// and secret used for authentication.
/// - `params`: A [`CryptoStreamParams`] struct that contains the WebSocket
/// endpoint and the subscription details (e.g., channels to subscribe to).
///
/// # Returns
///
/// An asynchronous operation that resolves to a [`Result`] containing a stream.
/// The stream yields [`StockMsg`] objects wrapped in a [`Result`]:
/// - On success, data payloads from the WebSocket are returned as `Ok(StockMsg)`.
/// - On failure, an error description is returned as `Err`.
///
/// The return type uses `impl futures_core::Stream` for flexibility, enabling
/// it to work with various stream combinator libraries or patterns.
///
/// # Behavior
///
/// 1. The function establishes a WebSocket connection to the specified
/// endpoint in `params`.
/// 2. It sends an authentication message using the API key and secret from
/// the `alpaca` client.
/// 3. Upon successful authentication, it sends a subscription message
/// containing the stream channel configuration.
/// 4. It listens for incoming messages on the WebSocket connection:
/// - It parses incoming JSON text payloads into `StockMsg` objects.
/// - Successfully parsed messages are sent to the output stream.
/// - Any errors (e.g., decoding errors) are sent as `Err` to the output stream.
/// 5. If the connection is closed, interrupted, or an error occurs, it tries
/// to reconnect indefinitely with an exponential backoff strategy (the max
/// backoff time between attempts is capped).
///
/// # Reconnection Logic
///
/// If the connection fails or the server closes the WebSocket:
/// - The function automatically retries connecting to the server.
/// - The initial delay between retry attempts starts at 250ms, doubling on
/// each failure, up to a maximum delay of 16 seconds (capped at 6 retries).
/// - Once reconnected, it re-authenticates and resends the subscription.
///
/// # Errors
///
/// - Authentication failures are sent as `Err` when they occur.
/// - Any issue during message parsing or WebSocket communication will also
/// be sent as an error.
/// - In the case of unrecoverable errors during reconnection, the stream will
/// continue attempting indefinitely, maintaining the backoff strategy.
///
/// # Notes
///
/// - The `StockMsg` type is used for all incoming WebSocket messages, including
/// success or error responses and actual data payloads.
/// - The function uses the `tokio` library for asynchronous tasks and channel management.
/// - The `serde_json` library is used for JSON encoding and decoding.
pub async
async