tastytrade 0.5.0

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
use super::order::{OrderId, PriceEffect, Symbol};
use crate::accounts::AccountNumber;
use crate::api::quote_streaming::DxFeedSymbol;
use crate::types::instrument::InstrumentType;
use chrono::{DateTime, FixedOffset, NaiveDate};
use pretty_simple_display::{DebugPretty, DisplaySimple};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::fmt::Display;

/// Represents the direction of a quantity, such as a trade or position.
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
pub enum QuantityDirection {
    /// Represents a long position or buy trade.
    Long,
    /// Represents a short position or sell trade.
    Short,
    /// Represents a zero quantity or a neutral position.
    Zero,
}

impl Display for QuantityDirection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            QuantityDirection::Long => write!(f, "Long"),
            QuantityDirection::Short => write!(f, "Short"),
            QuantityDirection::Zero => write!(f, "Zero"),
        }
    }
}

/// Represents a full position for an account.
///
/// This struct provides detailed information about a specific position held in an account, including
/// the instrument, quantity, price details, and various flags.  It's designed for deserialization
/// with kebab-case renaming for compatibility with external APIs.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct FullPosition {
    /// The account number associated with the position.
    pub account_number: AccountNumber,
    /// The symbol of the instrument for this position.
    pub symbol: Symbol,
    /// The type of the instrument (e.g., Equity, Option).
    pub instrument_type: InstrumentType,
    /// The underlying symbol of the instrument, if applicable (e.g., for options).
    pub underlying_symbol: Symbol,
    /// The quantity of the instrument held in the position.  Uses arbitrary precision for accuracy.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub quantity: Decimal,
    /// The direction of the quantity (Long, Short, or Zero).
    pub quantity_direction: QuantityDirection,
    /// The closing price of the instrument.  Uses arbitrary precision for accuracy.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub close_price: Decimal,
    /// The average opening price of the instrument. Uses arbitrary precision for accuracy.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub average_open_price: Decimal,
    /// The average yearly market close price of the instrument. Uses arbitrary precision for accuracy.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub average_yearly_market_close_price: Decimal,
    /// The average daily market close price of the instrument. Uses arbitrary precision for accuracy.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub average_daily_market_close_price: Decimal,
    /// The multiplier for the instrument.
    #[serde(with = "crate::types::wire::decimal")]
    pub multiplier: Decimal,
    /// The effect of the price on the account (Debit, Credit, or None).
    pub cost_effect: PriceEffect,
    /// A flag indicating whether the position is suppressed.
    pub is_suppressed: bool,
    /// A flag indicating whether the position is frozen.
    pub is_frozen: bool,
    /// The restricted quantity of the instrument. Uses arbitrary precision for accuracy.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub restricted_quantity: Decimal,
    /// The realized day gain for the position. Uses arbitrary precision for accuracy.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub realized_day_gain: Decimal,
    /// The effect of the realized day gain (e.g., "Debit", "Credit").
    pub realized_day_gain_effect: String,
    /// The date of the realized day gain.
    #[serde(with = "crate::types::wire::date")]
    pub realized_day_gain_date: NaiveDate,
    /// The realized gain for today. Uses arbitrary precision for accuracy.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub realized_today: Decimal,
    /// The effect of the realized gain for today (e.g., "Debit", "Credit").
    pub realized_today_effect: String,
    /// The date of the realized gain for today.
    #[serde(with = "crate::types::wire::date")]
    pub realized_today_date: NaiveDate,
    /// The date and time when the position was created.
    #[serde(with = "crate::types::wire::datetime")]
    pub created_at: DateTime<FixedOffset>,
    /// The date and time when the position was last updated.
    #[serde(with = "crate::types::wire::datetime")]
    pub updated_at: DateTime<FixedOffset>,

    // Ten fields the venue's schema carries and this struct did not. `mark`
    // and `mark_price` are the ones that mattered: `include-marks` is a
    // documented query filter, so a caller could ask for marks and then have
    // nowhere to read them.
    //
    // All `Option`: `mark` only arrives when it was asked for, `expires_at`
    // only exists for an instrument that expires, and certification omits
    // fields production sends.
    /// Current quote mark, when `include-marks` asked for it.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub mark: Option<Decimal>,
    /// Current quote mark price, when `include-marks` asked for it.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub mark_price: Option<Decimal>,
    /// What the position delivers at expiration, for instruments that deliver.
    #[serde(default)]
    pub deliverable_type: Option<String>,
    /// When the instrument expires, offset preserved.
    #[serde(default, with = "crate::types::wire::datetime_option")]
    pub expires_at: Option<DateTime<FixedOffset>>,
    /// Face value, for fixed income.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub face_value: Option<Decimal>,
    /// Fixing price, for instruments that settle against one.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub fixing_price: Option<Decimal>,
    /// Par size, for fixed income.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub par_size: Option<Decimal>,
    /// The order that opened the position, when the venue attributes one.
    #[serde(default)]
    pub order_id: Option<OrderId>,
    /// What to subscribe to on the streamer for this instrument.
    #[serde(default)]
    pub streamer_symbol: Option<String>,
    /// How the position last changed, as the venue classifies it.
    #[serde(default)]
    pub update_type: Option<String>,
}

/// Represents a brief overview of a position.
///
/// This struct provides a summary of a trading position, including details such as
/// the account number, symbol, quantity, price, and various status flags.  It's
/// designed for deserialization with kebab-case renaming for compatibility with
/// external APIs.
#[derive(DebugPretty, DisplaySimple, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct BriefPosition {
    /// The account number associated with the position.
    pub account_number: AccountNumber,
    /// The trading symbol of the instrument.
    pub symbol: Symbol,
    /// The type of the instrument (e.g., Equity, Option).
    pub instrument_type: InstrumentType,
    /// The underlying symbol of the instrument (if applicable).
    pub underlying_symbol: Symbol,
    /// The quantity of the instrument held in the position.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub quantity: Decimal,
    /// The direction of the quantity (Long, Short, or Zero).
    pub quantity_direction: QuantityDirection,
    /// The closing price of the instrument.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub close_price: Decimal,
    /// The average opening price of the instrument.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub average_open_price: Decimal,
    /// The multiplier for the instrument.
    #[serde(with = "crate::types::wire::decimal")]
    pub multiplier: Decimal,
    /// The effect of the price on the account (Debit, Credit, or None).
    pub cost_effect: PriceEffect,
    /// A flag indicating whether the position is suppressed.
    pub is_suppressed: bool,
    /// A flag indicating whether the position is frozen.
    pub is_frozen: bool,
    /// The restricted quantity of the instrument.
    #[serde(with = "crate::types::wire::decimal")]
    pub restricted_quantity: Decimal,
    /// The realized day gain for the position.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub realized_day_gain: Decimal,
    /// The realized amount for today.
    #[serde(with = "rust_decimal::serde::arbitrary_precision")]
    pub realized_today: Decimal,
    /// The timestamp of when the position was created.
    #[serde(with = "crate::types::wire::datetime")]
    pub created_at: DateTime<FixedOffset>,

    // Everything below is `Option`. The published schema marks no position
    // field required, and which of them the venue sends depends on the
    // instrument: an equity has no `expires-at`, a future has no
    // `deliverable-type`. A required field the venue skips would fail the
    // whole decode, which on the streaming path means a position notification
    // silently becoming an unreadable frame.
    //
    // `default` is not redundant next to `with`: an explicit `with` cancels
    // serde's implicit "absent Option is None".
    /// The instrument's streaming name, when it has one.
    ///
    /// Not always the same string as `symbol`; see
    /// [`crate::TastyTrade::get_streamer_symbol`].
    #[serde(default)]
    pub streamer_symbol: Option<DxFeedSymbol>,

    /// The average closing price over the trailing day window.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub average_daily_market_close_price: Option<Decimal>,

    /// The average closing price over the trailing year window.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub average_yearly_market_close_price: Option<Decimal>,

    /// The mark, as the venue values the position.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub mark: Option<Decimal>,

    /// The price the mark was computed from.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub mark_price: Option<Decimal>,

    /// Face value, for instruments that have one.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub face_value: Option<Decimal>,

    /// The fixing price, for instruments that settle against one.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub fixing_price: Option<Decimal>,

    /// Par size, for instruments quoted against one.
    #[serde(default, with = "crate::types::wire::decimal_option")]
    pub par_size: Option<Decimal>,

    /// What the position delivers at expiration, when it delivers something.
    #[serde(default)]
    pub deliverable_type: Option<String>,

    /// What produced this update, when the venue says.
    #[serde(default)]
    pub update_type: Option<String>,

    /// The order that opened the position, when one did.
    #[serde(default)]
    pub order_id: Option<OrderId>,

    /// When the instrument expires, for those that do.
    #[serde(default, with = "crate::types::wire::datetime_option")]
    pub expires_at: Option<DateTime<FixedOffset>>,

    /// Whether the realized day gain is a debit or a credit.
    #[serde(default)]
    pub realized_day_gain_effect: Option<PriceEffect>,

    /// The calendar day the realized day gain belongs to.
    #[serde(default, with = "crate::types::wire::date_option")]
    pub realized_day_gain_date: Option<NaiveDate>,

    /// Whether today's realized amount is a debit or a credit.
    #[serde(default)]
    pub realized_today_effect: Option<PriceEffect>,

    /// The calendar day today's realized amount belongs to.
    #[serde(default, with = "crate::types::wire::date_option")]
    pub realized_today_date: Option<NaiveDate>,

    /// The timestamp of when the position was last updated.
    #[serde(with = "crate::types::wire::datetime")]
    pub updated_at: DateTime<FixedOffset>,
}

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

    use rust_decimal::Decimal;
    use std::str::FromStr;

    #[test]
    fn test_quantity_direction_display() {
        assert_eq!(format!("{}", QuantityDirection::Long), "Long");
        assert_eq!(format!("{}", QuantityDirection::Short), "Short");
        assert_eq!(format!("{}", QuantityDirection::Zero), "Zero");
    }

    #[test]
    fn test_quantity_direction_serialization() {
        let long = QuantityDirection::Long;
        let serialized = serde_json::to_string(&long).unwrap();
        assert_eq!(serialized, "\"Long\"");

        let short = QuantityDirection::Short;
        let serialized = serde_json::to_string(&short).unwrap();
        assert_eq!(serialized, "\"Short\"");

        let zero = QuantityDirection::Zero;
        let serialized = serde_json::to_string(&zero).unwrap();
        assert_eq!(serialized, "\"Zero\"");
    }

    #[test]
    fn test_quantity_direction_deserialization() {
        let long: QuantityDirection = serde_json::from_str("\"Long\"").unwrap();
        matches!(long, QuantityDirection::Long);

        let short: QuantityDirection = serde_json::from_str("\"Short\"").unwrap();
        matches!(short, QuantityDirection::Short);

        let zero: QuantityDirection = serde_json::from_str("\"Zero\"").unwrap();
        matches!(zero, QuantityDirection::Zero);
    }

    #[test]
    fn test_quantity_direction_clone_and_copy() {
        let original = QuantityDirection::Long;
        let cloned = original;
        let copied = original;

        matches!(cloned, QuantityDirection::Long);
        matches!(copied, QuantityDirection::Long);
    }

    #[test]
    fn test_quantity_direction_debug() {
        let long = QuantityDirection::Long;
        let debug_str = format!("{:?}", long);
        assert_eq!(debug_str, "Long");
    }

    #[test]
    fn test_full_position_debug() {
        // We can't easily create a FullPosition due to all the required fields,
        // but we can test that the struct exists and has the expected fields
        // by checking if we can deserialize a minimal JSON
        let json = r#"{
            "account-number": "TEST123",
            "symbol": "AAPL",
            "instrument-type": "Equity",
            "underlying-symbol": "AAPL",
            "quantity": "100",
            "quantity-direction": "Long",
            "close-price": "150.50",
            "average-open-price": "145.00",
            "average-yearly-market-close-price": "140.00",
            "average-daily-market-close-price": "149.00",
            "multiplier": 1.0,
            "cost-effect": "Debit",
            "is-suppressed": false,
            "is-frozen": false,
            "restricted-quantity": "0",
            "realized-day-gain": "550.00",
            "realized-day-gain-effect": "Credit",
            "realized-day-gain-date": "2024-01-01",
            "realized-today": "550.00",
            "realized-today-effect": "Credit",
            "realized-today-date": "2024-01-01",
            "created-at": "2024-01-01T10:00:00Z",
            "updated-at": "2024-01-01T16:00:00Z"
        }"#;

        let position: Result<FullPosition, _> = serde_json::from_str(json);
        assert!(position.is_ok());

        let position = position.unwrap();
        assert_eq!(position.account_number.0, "TEST123");
        assert_eq!(position.symbol.0, "AAPL");
        assert_eq!(position.quantity, Decimal::from_str("100").unwrap());
        matches!(position.quantity_direction, QuantityDirection::Long);
        matches!(position.instrument_type, InstrumentType::Equity);
    }

    #[test]
    fn test_brief_position_debug() {
        let json = r#"{
            "account-number": "BRIEF123",
            "symbol": "MSFT",
            "instrument-type": "Equity",
            "underlying-symbol": "MSFT",
            "quantity": "50",
            "quantity-direction": "Short",
            "close-price": "300.00",
            "average-open-price": "295.00",
            "multiplier": 1.0,
            "cost-effect": "Credit",
            "is-suppressed": true,
            "is-frozen": false,
            "restricted-quantity": 10.0,
            "realized-day-gain": "-250.00",
            "realized-today": "-250.00",
            "created-at": "2024-01-01T09:00:00Z",
            "updated-at": "2024-01-01T15:30:00Z"
        }"#;

        let position: Result<BriefPosition, _> = serde_json::from_str(json);
        assert!(position.is_ok());

        let position = position.unwrap();
        assert_eq!(position.account_number.0, "BRIEF123");
        assert_eq!(position.symbol.0, "MSFT");
        assert_eq!(position.quantity, Decimal::from_str("50").unwrap());
        matches!(position.quantity_direction, QuantityDirection::Short);
        assert!(position.is_suppressed);
        assert!(!position.is_frozen);
    }

    #[test]
    fn test_position_with_zero_quantity() {
        let json = r#"{
            "account-number": "ZERO123",
            "symbol": "TSLA",
            "instrument-type": "Equity",
            "underlying-symbol": "TSLA",
            "quantity": "0",
            "quantity-direction": "Zero",
            "close-price": "200.00",
            "average-open-price": "200.00",
            "multiplier": 1.0,
            "cost-effect": "None",
            "is-suppressed": false,
            "is-frozen": false,
            "restricted-quantity": 0.0,
            "realized-day-gain": "0.00",
            "realized-today": "0.00",
            "created-at": "2024-01-01T12:00:00Z",
            "updated-at": "2024-01-01T12:00:00Z"
        }"#;

        let position: Result<BriefPosition, _> = serde_json::from_str(json);
        assert!(position.is_ok());

        let position = position.unwrap();
        matches!(position.quantity_direction, QuantityDirection::Zero);
        assert_eq!(position.quantity, Decimal::ZERO);
        matches!(position.cost_effect, PriceEffect::None);
    }
}