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
use crate::{
    common::{optional_string_serialize, string_serialize, Date, Decimal, OptionType},
    csv,
    symbol::OptionSymbol,
};

use chrono::{DateTime, FixedOffset};
use num_rational::Rational64;
use num_traits::{Signed, Zero};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Response<Data> {
    pub data: Data,
    pub pagination: Option<Pagination>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Pagination {
    pub page_offset: i32,
    pub total_pages: i32,
}

pub mod accounts {
    use super::*;

    #[derive(Debug, Serialize, Deserialize)]
    pub struct Response {
        pub items: Vec<Item>,
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub struct Item {
        pub account: Account,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Account {
        pub account_number: String,
    }
}

pub mod watchlists {
    use super::*;

    #[derive(Debug, Serialize, Deserialize)]
    pub struct Response {
        pub items: Vec<Item>,
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub struct Item {
        pub name: String,
        #[serde(rename = "watchlist-entries")]
        pub entries: Vec<Entry>,
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub struct Entry {
        pub symbol: String,
        #[serde(alias = "instrument-type")]
        pub instrument_type: InstrumentType,
    }

    #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
    pub enum InstrumentType {
        Future,
        Equity,
        Index,
        Unknown,
    }
}

pub mod market_metrics {
    use super::*;

    #[derive(Debug, Serialize, Deserialize)]
    pub struct Response {
        pub items: Vec<Item>,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Item {
        pub symbol: String,
        implied_volatility_index: Option<String>,
        implied_volatility_index_5_day_change: Option<String>,
        implied_volatility_index_rank: Option<String>,
        tos_implied_volatility_index_rank: Option<String>,
        tw_implied_volatility_index_rank: Option<String>,
        tos_implied_volatility_index_rank_updated_at: Option<String>,
        implied_volatility_index_rank_source: Option<String>,
        implied_volatility_percentile: Option<String>,
        implied_volatility_updated_at: Option<String>,
        liquidity_value: Option<String>,
        liquidity_rank: Option<String>,
        liquidity_rating: Option<i32>,
        updated_at: String,
        pub option_expiration_implied_volatilities: Option<Vec<ExpirationImpliedVolatility>>,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct ExpirationImpliedVolatility {
        #[serde(with = "string_serialize")]
        pub expiration_date: Date,
        #[serde(default, with = "optional_string_serialize")]
        pub implied_volatility: Option<f64>,
    }
}

pub mod positions {
    use super::*;

    #[derive(Debug, Serialize, Deserialize)]
    pub struct Response {
        pub items: Vec<Item>,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Item {
        pub symbol: String,
        pub quantity: i32,
        pub quantity_direction: QuantityDirection,
        pub instrument_type: String,
    }

    #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
    pub enum QuantityDirection {
        Short,
        Long,
    }

    impl QuantityDirection {
        fn from_signed_quantity(quantity: i32) -> Self {
            if quantity > 0 {
                Self::Long
            } else {
                Self::Short
            }
        }
    }

    impl Item {
        pub fn quote_symbol(&self) -> String {
            OptionSymbol::from(&self.symbol).quote_symbol()
        }

        pub fn expiration_date(&self) -> Date {
            OptionSymbol::from(&self.symbol).expiration_date()
        }

        pub fn underlying_symbol(&self) -> &str {
            OptionSymbol::from(&self.symbol).underlying_symbol()
        }

        pub fn option_type(&self) -> OptionType {
            OptionSymbol::from(&self.symbol).option_type()
        }

        pub fn strike_price(&self) -> Rational64 {
            OptionSymbol::from(&self.symbol).strike_price()
        }
    }

    impl From<csv::Position> for Item {
        fn from(csv: csv::Position) -> Self {
            Self {
                symbol: csv.symbol,
                quantity: csv.quantity.abs(),
                quantity_direction: QuantityDirection::from_signed_quantity(csv.quantity),
                instrument_type: match csv.instrument_type.as_ref() {
                    // TODO: handle futures and futures options
                    "OPTION" => "Equity Option".to_string(),
                    "STOCK" => "Equity".to_string(),
                    _ => unreachable!("Unhandled instrument type: {}", csv.instrument_type),
                },
            }
        }
    }
}

pub mod transactions {
    use super::*;

    #[derive(Debug, Serialize, Deserialize)]
    pub struct Response {
        pub items: Vec<Item>,
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(untagged)]
    pub enum Item {
        Trade(TradeItem),
        ReceiveDeliver(ReceiveDeliverItem),
        Other(OtherItem),
    }

    impl Item {
        pub fn id_mut(&mut self) -> &mut u32 {
            match self {
                Self::Trade(item) => &mut item.id,
                Self::ReceiveDeliver(item) => &mut item.id,
                Self::Other(item) => &mut item.id,
            }
        }

        pub fn executed_at(&mut self) -> DateTime<FixedOffset> {
            match self {
                Self::Trade(item) => item.executed_at,
                Self::ReceiveDeliver(item) => item.executed_at,
                Self::Other(item) => item.executed_at,
            }
        }
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct TradeItem {
        pub id: u32,
        pub symbol: String,
        pub instrument_type: String,
        pub transaction_type: String,
        #[serde(with = "string_serialize")]
        pub executed_at: DateTime<FixedOffset>,
        pub action: TradeAction,
        pub underlying_symbol: String,
        #[serde(with = "string_serialize")]
        value: Decimal,
        value_effect: ValueEffect,
        #[serde(with = "string_serialize")]
        pub quantity: Decimal,
        #[serde(with = "string_serialize")]
        commission: Decimal,
        commission_effect: ValueEffect,
        #[serde(with = "string_serialize")]
        clearing_fees: Decimal,
        clearing_fees_effect: ValueEffect,
        #[serde(with = "string_serialize")]
        regulatory_fees: Decimal,
        regulatory_fees_effect: ValueEffect,
        #[serde(with = "string_serialize")]
        proprietary_index_option_fees: Decimal,
        proprietary_index_option_fees_effect: ValueEffect,
        pub ext_global_order_number: u32,
    }

    impl PartialEq for TradeItem {
        fn eq(&self, other: &Self) -> bool {
            self.id == other.id
        }
    }
    impl Eq for TradeItem {}

    impl TradeItem {
        pub fn value(&self) -> Rational64 {
            self.value_effect.apply(self.value.0)
        }

        pub fn commission(&self) -> Rational64 {
            self.commission_effect.apply(self.commission.0)
        }

        pub fn fees(&self) -> Rational64 {
            self.clearing_fees_effect.apply(self.clearing_fees.0)
                + self.regulatory_fees_effect.apply(self.regulatory_fees.0)
                + self
                    .proprietary_index_option_fees_effect
                    .apply(self.proprietary_index_option_fees.0)
        }

        pub fn expiration_date(&self) -> Date {
            OptionSymbol::from(&self.symbol).expiration_date()
        }

        pub fn underlying_symbol(&self) -> &str {
            OptionSymbol::from(&self.symbol).underlying_symbol()
        }

        pub fn option_type(&self) -> OptionType {
            OptionSymbol::from(&self.symbol).option_type()
        }

        pub fn strike_price(&self) -> Rational64 {
            OptionSymbol::from(&self.symbol).strike_price()
        }
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct ReceiveDeliverItem {
        pub id: u32,
        pub symbol: String,
        pub instrument_type: String,
        pub transaction_type: String,
        pub transaction_sub_type: String,
        #[serde(with = "string_serialize")]
        pub executed_at: DateTime<FixedOffset>,
        #[serde(default)]
        pub action: Option<TradeAction>, // defined for stock splits, missing for exercise
        pub underlying_symbol: String,
        #[serde(with = "string_serialize")]
        value: Decimal,
        pub value_effect: ValueEffect,
        #[serde(with = "string_serialize")]
        pub quantity: Decimal,
    }

    impl PartialEq for ReceiveDeliverItem {
        fn eq(&self, other: &Self) -> bool {
            self.id == other.id
        }
    }
    impl Eq for ReceiveDeliverItem {}

    impl ReceiveDeliverItem {
        pub fn value(&self) -> Rational64 {
            self.value_effect.apply(self.value.0)
        }

        pub fn expiration_date(&self) -> Date {
            OptionSymbol::from(&self.symbol).expiration_date()
        }

        pub fn underlying_symbol(&self) -> &str {
            OptionSymbol::from(&self.symbol).underlying_symbol()
        }

        pub fn option_type(&self) -> OptionType {
            OptionSymbol::from(&self.symbol).option_type()
        }

        pub fn strike_price(&self) -> Rational64 {
            OptionSymbol::from(&self.symbol).strike_price()
        }
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct OtherItem {
        pub id: u32,
        pub transaction_type: String,
        #[serde(with = "string_serialize")]
        pub executed_at: DateTime<FixedOffset>,
    }

    #[derive(Copy, Clone, Debug, Serialize, Deserialize, Eq, Hash, PartialEq)]
    pub enum TradeAction {
        Sell,
        Buy,
        #[serde(rename = "Sell to Open")]
        SellToOpen, // open credit
        #[serde(rename = "Buy to Open")]
        BuyToOpen, // open debit
        #[serde(rename = "Sell to Close")]
        SellToClose, // close credit
        #[serde(rename = "Buy to Close")]
        BuyToClose, // close debit
    }

    impl TradeAction {
        pub fn opposing_action(&self) -> Self {
            match self {
                TradeAction::Sell => TradeAction::Buy,
                TradeAction::Buy => TradeAction::Sell,
                TradeAction::SellToOpen => TradeAction::BuyToClose,
                TradeAction::BuyToOpen => TradeAction::SellToClose,
                TradeAction::SellToClose => TradeAction::BuyToOpen,
                TradeAction::BuyToClose => TradeAction::SellToOpen,
            }
        }

        pub fn opens(&self) -> bool {
            match self {
                TradeAction::Sell => true,
                TradeAction::Buy => true,
                TradeAction::SellToOpen => true,
                TradeAction::BuyToOpen => true,
                TradeAction::SellToClose => false,
                TradeAction::BuyToClose => false,
            }
        }

        pub fn closes(&self) -> bool {
            !self.opens()
        }
    }

    #[derive(Copy, Clone, Debug, Serialize, Deserialize, Eq, Hash, PartialEq)]
    pub enum ValueEffect {
        None,
        Debit,
        Credit,
    }

    impl ValueEffect {
        fn from_value(value: Rational64) -> Self {
            if value.is_positive() {
                Self::Credit
            } else if value.is_negative() {
                Self::Debit
            } else {
                Self::None
            }
        }

        fn apply(&self, v: Rational64) -> Rational64 {
            match self {
                Self::None => Rational64::zero(),
                Self::Debit => -v,
                Self::Credit => v,
            }
        }
    }

    impl From<csv::Transaction> for Item {
        fn from(csv: csv::Transaction) -> Self {
            let symbol = csv.symbol.clone().unwrap_or_default();
            let instrument_type = csv.instrument_type.clone().unwrap_or_default();
            let underlying_symbol = csv.underlying_symbol().unwrap_or_default().to_string();

            let split_fees = Decimal(csv.fees.abs().0 / 3);
            let fees_effect = ValueEffect::from_value(csv.fees.0);

            if csv.trade_type == "Trade" {
                let commission = csv.commissions.expect("Missing commissions").abs();
                Item::Trade(TradeItem {
                    id: 0,
                    symbol,
                    instrument_type,
                    transaction_type: csv.trade_type,
                    executed_at: csv.date,
                    action: csv.action.expect("Missing trade action").into(),
                    underlying_symbol,
                    value: csv.value.abs(),
                    value_effect: ValueEffect::from_value(csv.value.0),
                    quantity: csv.quantity,
                    commission,
                    commission_effect: ValueEffect::from_value(commission.0),
                    clearing_fees: split_fees,
                    clearing_fees_effect: fees_effect,
                    regulatory_fees: split_fees,
                    regulatory_fees_effect: fees_effect,
                    proprietary_index_option_fees: split_fees,
                    proprietary_index_option_fees_effect: fees_effect,
                    ext_global_order_number: 0,
                })
            } else if csv.trade_type == "Receive Deliver" {
                let description = csv.description.to_ascii_lowercase();
                let transaction_sub_type = if description.contains("exercise") {
                    "Exercise".to_string()
                } else if description.contains("expiration") {
                    "Expiration".to_string()
                } else if description.contains("assignment") {
                    "Assignment".to_string()
                } else if description.contains("forward split") {
                    "Forward Split".to_string()
                } else if description.contains("backwards split") {
                    "Backwards Split".to_string()
                } else {
                    description
                };

                Item::ReceiveDeliver(ReceiveDeliverItem {
                    id: 0,
                    symbol,
                    instrument_type,
                    transaction_type: csv.trade_type,
                    transaction_sub_type,
                    executed_at: csv.date,
                    action: csv.action.map(|action| action.into()),
                    underlying_symbol,
                    value: csv.value.abs(),
                    value_effect: ValueEffect::from_value(csv.value.0),
                    quantity: csv.quantity,
                })
            } else {
                Item::Other(OtherItem {
                    id: 0,
                    transaction_type: csv.trade_type,
                    executed_at: csv.date,
                })
            }
        }
    }

    impl From<csv::TradeAction> for TradeAction {
        fn from(csv: csv::TradeAction) -> Self {
            match csv {
                csv::TradeAction::SellToOpen => Self::SellToOpen,
                csv::TradeAction::BuyToOpen => Self::BuyToOpen,
                csv::TradeAction::SellToClose => Self::SellToClose,
                csv::TradeAction::BuyToClose => Self::BuyToClose,
            }
        }
    }
}