dxlink 0.1.5

Library for trading through tastytrade's API
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
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 7/3/25
******************************************************************************/

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Represents a basic message structure.
///
/// This struct is used for communication, defining a channel and the type of message.
/// The `serde` attributes enable serialization and deserialization in camelCase format.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BaseMessage {
    /// The channel number.
    pub channel: u32,
    /// The type of the message.
    #[serde(rename = "type")]
    pub message_type: String,
}

/// Represents a setup message for establishing a connection.
///
/// This message is used to initiate a connection and exchange
/// initial setup parameters between client and server.  It includes
/// information such as the channel number, message type, keepalive
/// timeout values, and the version of the protocol being used.
///
/// # Examples
///
/// Serializing a `SetupMessage`:
///
/// ```rust
/// use serde_json::json;
/// use dxlink::messages::SetupMessage;
///
/// let setup_message = SetupMessage {
///     channel: 1,
///     message_type: "setup".to_string(),
///     keepalive_timeout: 30000,
///     accept_keepalive_timeout: 35000,
///     version: "1.0".to_string(),
/// };
///
/// let json_representation = serde_json::to_string(&setup_message).unwrap();
/// assert_eq!(json_representation, r#"{"channel":1,"type":"setup","keepaliveTimeout":30000,"acceptKeepaliveTimeout":35000,"version":"1.0"}"#);
///
/// // You can also create it from a JSON string.
/// let setup_message: SetupMessage = serde_json::from_value(json!({
///     "channel": 1,
///     "type": "setup",
///     "keepaliveTimeout": 30000,
///     "acceptKeepaliveTimeout": 35000,
///     "version": "1.0"
/// })).unwrap();
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetupMessage {
    /// The channel number.
    pub channel: u32,
    /// The type of the message.  Should be "setup".
    #[serde(rename = "type")]
    pub message_type: String,
    /// The keepalive timeout value in milliseconds.
    pub keepalive_timeout: u32,
    /// The timeout value for accepting a keepalive message.
    pub accept_keepalive_timeout: u32,
    /// The version of the protocol.
    pub version: String,
}

/// Represents a keepalive message.  This message is used to maintain an active connection
/// and prevent timeouts.  It is sent periodically by the client or server.
///
/// # Example:
///
/// ```json
/// {
///   "channel": 1234,
///   "type": "KEEPALIVE"
/// }
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeepaliveMessage {
    /// The channel ID.
    pub channel: u32,
    /// The message type.  Should always be "KEEPALIVE".
    #[serde(rename = "type")]
    pub message_type: String,
}

/// Represents an authentication message.
///
/// This structure is used for authentication purposes, containing information such as the channel, message type, and token.
/// The `rename_all = "camelCase"` attribute ensures that the fields are serialized and deserialized in camel case format.
///
/// ...
/// # Examples
///
/// Serializing an `AuthMessage` instance to JSON:
///
/// ```rust
/// use serde::{Deserialize, Serialize};
/// use serde_json::to_string;
/// use dxlink::messages::AuthMessage;
///
/// let auth_message = AuthMessage {
///     channel: 1234,
///     message_type: "auth".to_string(),
///     token: "YOUR_TOKEN".to_string(),
/// };
///
/// let json_string = to_string(&auth_message).unwrap();
/// println!("{}", json_string);
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthMessage {
    /// The channel number.
    pub channel: u32,
    /// The type of the message. This is typically "auth".
    #[serde(rename = "type")]
    pub message_type: String,
    /// The authentication token.
    pub token: String,
}

/// Represents an authentication state message.  This structure is used for serializing
/// and deserializing authentication state messages, typically used in a
/// communication channel like a WebSocket. The `camelCase` serialization
/// attribute ensures compatibility with JavaScript conventions.
///
/// # Examples
///
/// Serialization:
///
/// ```rust
/// use serde_json;
/// use dxlink::messages::AuthStateMessage;
///
/// let message = AuthStateMessage {
///     channel: 1234,
///     message_type: "authState".to_string(),
///     state: "authenticated".to_string(),
///     user_id: Some("user123".to_string()),
/// };
///
/// let json_string = serde_json::to_string(&message).unwrap();
/// println!("{}", json_string); // Output: {"channel":1234,"type":"authState","state":"authenticated","userId":"user123"}
/// ```
///
/// Deserialization:
///
/// ```rust
/// use serde_json;
/// use dxlink::messages::AuthStateMessage;
///
/// let json_string = r#"{"channel":1234,"type":"authState","state":"authenticated","userId":"user123"}"#;
/// let message: AuthStateMessage = serde_json::from_str(json_string).unwrap();
///
/// assert_eq!(message.channel, 1234);
/// assert_eq!(message.message_type, "authState");
/// assert_eq!(message.state, "authenticated");
/// assert_eq!(message.user_id, Some("user123".to_string()));
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthStateMessage {
    /// The channel number.
    pub channel: u32,
    /// The type of the message.  Typically "authState".
    #[serde(rename = "type")]
    pub message_type: String,
    /// The authentication state (e.g., "authenticated", "unauthenticated").
    pub state: String,
    /// The ID of the user.  Optional.
    pub user_id: Option<String>,
}

/// Represents a channel request message.
///
/// This structure is used to send requests to a specific channel.  It includes the channel number,
/// the type of message, the service being requested, and any associated parameters.  Serialization and
/// deserialization are handled using `serde` with `camelCase` naming convention.
///
/// # Examples
///
/// ```rust
/// use std::collections::HashMap;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Debug, Serialize, Deserialize)]
/// #[serde(rename_all = "camelCase")]
/// pub struct ChannelRequestMessage {
///     pub channel: u32,
///     #[serde(rename = "type")]
///     pub message_type: String,
///     pub service: String,
///     pub parameters: HashMap<String, String>,
/// }
///
/// let mut parameters = HashMap::new();
/// parameters.insert("param1".to_string(), "value1".to_string());
/// parameters.insert("param2".to_string(), "value2".to_string());
///
/// let message = ChannelRequestMessage {
///     channel: 123,
///     message_type: "request".to_string(),
///     service: "my_service".to_string(),
///     parameters: parameters,
/// };
///
/// let serialized = serde_json::to_string(&message).unwrap();
/// println!("{}", serialized);
///
/// let deserialized: ChannelRequestMessage = serde_json::from_str(&serialized).unwrap();
/// println!("{:?}", deserialized);
///
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelRequestMessage {
    /// The channel number.
    pub channel: u32,
    /// The type of the message.
    #[serde(rename = "type")]
    pub message_type: String,
    /// The service being requested.
    pub service: String,
    /// The parameters associated with the request.
    pub parameters: HashMap<String, String>,
}

/// Represents a CHANNEL_OPENED message.  This message is sent when a new channel
/// is opened.
///
/// # Example
///
/// ```json
/// {
///   "channel": 123,
///   "type": "CHANNEL_OPENED",
///   "service": "some_service",
///   "parameters": {
///     "param1": "value1",
///     "param2": "value2"
///   }
/// }
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelOpenedMessage {
    /// The channel number.
    pub channel: u32,
    /// The message type.  This should always be "CHANNEL_OPENED".
    #[serde(rename = "type")]
    pub message_type: String,
    /// The service associated with the channel.  This is optional.
    #[serde(default)]
    pub service: Option<String>,
    /// Additional parameters associated with the channel opening.  This is optional.
    #[serde(default)]
    pub parameters: HashMap<String, String>,
}

/// Represents a message indicating a channel has been closed.
///
/// This message is typically used in scenarios where a communication channel,
/// identified by a numerical ID, is closed.  The `message_type` field
/// clarifies the type of message, explicitly set to "CHANNEL_CLOSED".
///
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelClosedMessage {
    /// The ID of the channel that has been closed.
    pub channel: u32,
    /// The type of the message.  This field will always be "CHANNEL_CLOSED".
    #[serde(rename = "type")]
    pub message_type: String,
}

/// Represents a message to cancel a channel.
///
/// This message is used to signal the cancellation of a specific channel.  It includes the channel number and the message type.
///
/// # Examples
///
/// ```
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Debug, Serialize, Deserialize)]
/// #[serde(rename_all = "camelCase")]
/// pub struct ChannelCancelMessage {
///     pub channel: u32,
///     #[serde(rename = "type")]
///     pub message_type: String,
/// }
///
/// let message = ChannelCancelMessage {
///     channel: 123,
///     message_type: "CHANNEL_CANCEL".to_string(),
/// };
///
/// // Serialize the message to JSON
/// let json = serde_json::to_string(&message).unwrap();
///
/// // Deserialize the message from JSON
/// let deserialized_message: ChannelCancelMessage = serde_json::from_str(&json).unwrap();
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelCancelMessage {
    /// The number of the channel to cancel.
    pub channel: u32,
    /// The type of the message.  This should always be "CHANNEL_CANCEL".
    #[serde(rename = "type")]
    pub message_type: String,
}

/// Represents an error message.
///
/// This struct is used to serialize and deserialize error messages in a structured format.
/// It adheres to the camelCase naming convention for serialization/deserialization thanks to the `#[serde(rename_all = "camelCase")]` attribute.
///
/// # Examples
///
/// ```
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Debug, Serialize, Deserialize)]
/// #[serde(rename_all = "camelCase")]
/// pub struct ErrorMessage {
///     pub channel: u32,
///     #[serde(rename = "type")]
///     pub message_type: String,
///     pub error: String,
///     pub message: String,
/// }
///
/// let error_message = ErrorMessage {
///     channel: 1,
///     message_type: "error".to_string(),
///     error: "ErrorCode".to_string(),
///     message: "Something went wrong".to_string(),
/// };
///
/// let serialized = serde_json::to_string(&error_message).unwrap();
///
/// assert_eq!(serialized, r#"{"channel":1,"type":"error","error":"ErrorCode","message":"Something went wrong"}"#);
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorMessage {
    /// The channel the error occurred on.
    pub channel: u32,
    /// The type of the message, which should be "error".
    #[serde(rename = "type")]
    pub message_type: String,
    /// A short error code.
    pub error: String,
    /// A human-readable error message.
    pub message: String,
}

/// Represents a subscription to a data feed.
///
/// This struct is used to specify the type of data, the symbol,
/// optional filtering by time, and the optional source of the data.
/// It is serialized and deserialized using the `serde` library,
/// with field names converted to camelCase.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FeedSubscription {
    /// The type of event to subscribe to.  For example, "trade", "kline", etc.
    #[serde(rename = "type")]
    pub event_type: String,

    /// The symbol to subscribe to. For example, "BTCUSDT".
    pub symbol: String,

    /// Optional starting time for the subscription, represented as a Unix timestamp in milliseconds.
    /// If not provided, the subscription will start from the current time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_time: Option<i64>,

    /// Optional source of the data.  This can be used to specify a particular
    /// exchange or data provider.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

/// Represents a message for managing feed subscriptions.
///
/// This message is used to add, remove, or reset subscriptions to data feeds.
/// It is serialized and deserialized using the `serde` library,
/// with field names converted to camelCase.  The `channel` field is used
/// to identify the specific connection or channel the message is associated with.
/// The `type` field indicates the type of message, which is always "FEED_SUBSCRIPTION".
/// The `add`, `remove`, and `reset` fields are optional and mutually exclusive.
/// If `add` is present, it contains a vector of `FeedSubscription` objects to be added.
/// If `remove` is present, it contains a vector of `FeedSubscription` objects to be removed.
/// If `reset` is true, all existing subscriptions are removed.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FeedSubscriptionMessage {
    /// The channel ID.
    pub channel: u32,

    /// The message type.  This should always be "FEED_SUBSCRIPTION".
    #[serde(rename = "type")]
    pub message_type: String,

    /// An optional vector of subscriptions to add.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub add: Option<Vec<FeedSubscription>>,

    /// An optional vector of subscriptions to remove.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remove: Option<Vec<FeedSubscription>>,

    /// An optional flag to reset all subscriptions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reset: Option<bool>,
}

/// Represents the setup message for a data feed.  This message is used to configure the channel, message type,
/// aggregation period, data format, and accepted event fields for the feed.
///
/// # Example
///
/// ```json
/// {
///   "channel": 1234,
///   "type": "marketData",
///   "acceptAggregationPeriod": 60.0,
///   "acceptDataFormat": "json",
///   "acceptEventFields": {
///     "trade": ["price", "quantity"],
///     "quote": ["bid", "ask"]
///   }
/// }
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FeedSetupMessage {
    /// The channel identifier for the feed.
    pub channel: u32,

    /// The type of message expected on the feed.  For example, "marketData", "orderEvents", etc.
    #[serde(rename = "type")]
    pub message_type: String,

    /// The accepted aggregation period for the feed, in seconds.  This indicates how frequently aggregated
    /// data should be sent.  If not applicable, a value of 0.0 can be used.
    pub accept_aggregation_period: f64,

    /// The accepted data format for the feed.  For example, "json", "csv", "protobuf", etc.
    pub accept_data_format: String,

    /// A map of event types to a list of accepted fields for each type.  This allows for fine-grained control
    /// over the data received on the feed.  For example, for a "trade" event, you might only want to receive
    /// the "price" and "quantity" fields.
    pub accept_event_fields: HashMap<String, Vec<String>>,
}

///
/// Represents the configuration for a feed message.
///
/// This structure defines how data should be aggregated and formatted for a specific channel.
/// It includes details like the channel number, message type, aggregation period, data format, and optional event fields.
///
/// # Examples
///
/// ```json
/// {
///   "channel": 123,
///   "type": "marketData",
///   "aggregationPeriod": 60.0,
///   "dataFormat": "json",
///   "eventFields": {
///     "trade": ["price", "volume"],
///     "quote": ["bid", "ask"]
///   }
/// }
/// ```
///
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FeedConfigMessage {
    /// The channel number for the feed.
    pub channel: u32,

    /// The type of the message.  For example "marketData", or "orderEvents".
    #[serde(rename = "type")]
    pub message_type: String,

    /// The aggregation period in seconds. Data will be aggregated over this time interval.
    pub aggregation_period: f64,

    /// The format of the data. For example "json", "csv", or "protobuf".
    pub data_format: String,

    /// Optional event fields to include in the message. This is a map where the keys are event types
    /// and the values are vectors of field names to include for that event type.
    #[serde(default)]
    pub event_fields: Option<HashMap<String, Vec<String>>>,
}

/// Represents a message containing feed data.
///
/// This struct is used to serialize and deserialize feed data messages,
/// adhering to a camelCase naming convention for JSON serialization.
///
/// `T` represents the type of the data being transmitted in the message.  
///
/// # Examples
///
/// ```rust
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Debug, Serialize, Deserialize)]
/// #[serde(rename_all = "camelCase")]
/// pub struct FeedDataMessage<T> {
///     pub channel: u32,
///     #[serde(rename = "type")]
///     pub message_type: String,
///     pub data: T,
/// }
///
/// #[derive(Debug, Serialize, Deserialize)]
/// pub struct MyData {
///     value: i32,
/// }
///
/// let message = FeedDataMessage {
///     channel: 123,
///     message_type: "data".to_string(),
///     data: MyData { value: 42 },
/// };
///
/// let json = serde_json::to_string(&message).unwrap();
///
/// println!("{}", json); // Output: {"channel":123,"type":"data","data":{"value":42}}
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FeedDataMessage<T> {
    /// The channel number associated with the message.
    pub channel: u32,
    /// The type of the message.  This field is renamed to "type" during serialization.
    #[serde(rename = "type")]
    pub message_type: String,
    /// The actual data being transmitted in the message.  This can be any serializable type.
    pub data: T,
}