optionstratlib 0.17.2

OptionStratLib is a comprehensive Rust library for options trading and strategy development across multiple asset classes.
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
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 22/9/25
******************************************************************************/

use crate::model::types::UnderlyingAssetType;
use num_traits::ToPrimitive;
use positive::Positive;
use pretty_simple_display::{DebugPretty, DisplaySimple};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

/// Represents the balance of a specific option position in an exchange.
///
/// This struct encapsulates all the information needed to track an option position,
/// including quantity, premium information, and profit/loss calculations.
/// This balance is specifically designed for options trading.
#[derive(DebugPretty, DisplaySimple, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct Balance {
    /// Symbol or Epic of the option contract
    pub symbol: String,
    /// Quantity of option contracts held
    pub quantity: Positive,
    /// Average premium at which the option was acquired
    pub average_premium: Positive,
    /// Current market premium of the option (if available)
    pub current_premium: Option<Positive>,
    /// Name of the exchange where the option is held
    pub exchange: String,
    /// Type of underlying asset (e.g., Stock, Forex, Index)
    pub underlying_asset_type: UnderlyingAssetType,
    /// Margin information for accounts that support leverage
    pub margin_info: Option<MarginInfo>,
}

impl Balance {
    /// Creates a new Balance instance for an option position.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The option contract symbol (e.g., "AAPL240315C00150000")
    /// * `quantity` - The quantity of option contracts held
    /// * `average_premium` - The average premium paid for the option
    /// * `current_premium` - The current market premium (optional)
    /// * `exchange` - The name of the exchange
    /// * `underlying_asset_type` - The type of the underlying asset
    /// * `margin_info` - Margin information for accounts that support leverage (optional)
    ///
    /// # Returns
    ///
    /// A new Balance instance for the option position
    #[must_use]
    pub fn new(
        symbol: String,
        quantity: Positive,
        average_premium: Positive,
        current_premium: Option<Positive>,
        exchange: String,
        underlying_asset_type: UnderlyingAssetType,
        margin_info: Option<MarginInfo>,
    ) -> Self {
        Self {
            symbol,
            quantity,
            average_premium,
            current_premium,
            exchange,
            underlying_asset_type,
            margin_info,
        }
    }

    /// Calculates the total value of the option position based on current premium.
    ///
    /// # Returns
    ///
    /// The total value (quantity * current_premium) if current_premium is available,
    /// otherwise returns the cost basis (quantity * average_premium)
    #[must_use]
    pub fn get_total_value(&self) -> Positive {
        match self.current_premium {
            Some(current_price) => {
                // Safe to unwrap as both quantity and current_price are Positive
                Positive::new(
                    (self.quantity.value() * current_price.value())
                        .to_f64()
                        .unwrap_or(0.0),
                )
                .unwrap_or(Positive::ZERO)
            }
            None => {
                // Use average premium if current premium is not available
                Positive::new(
                    (self.quantity.value() * self.average_premium.value())
                        .to_f64()
                        .unwrap_or(0.0),
                )
                .unwrap_or(Positive::ZERO)
            }
        }
    }

    /// Calculates the unrealized profit or loss of the position.
    ///
    /// # Returns
    ///
    /// The unrealized PnL as a Decimal. Positive values indicate profit,
    /// negative values indicate loss. Returns zero if current_price is not available.
    #[must_use]
    pub fn get_unrealized_pnl(&self) -> Decimal {
        match self.current_premium {
            Some(current_price) => {
                let current_value = self.quantity.value() * current_price.value();
                let cost_basis = self.quantity.value() * self.average_premium.value();
                current_value - cost_basis
            }
            None => Decimal::ZERO,
        }
    }

    /// Updates the current market premium of the option.
    ///
    /// # Arguments
    ///
    /// * `new_premium` - The new current market premium
    pub fn update_current_premium(&mut self, new_premium: Positive) {
        self.current_premium = Some(new_premium);
    }

    /// Checks if the position is currently profitable.
    ///
    /// # Returns
    ///
    /// `true` if the position has unrealized gains, `false` otherwise.
    /// Returns `false` if current_price is not available.
    #[must_use]
    pub fn is_profitable(&self) -> bool {
        self.get_unrealized_pnl() > Decimal::ZERO
    }

    /// Gets the cost basis of the option position.
    ///
    /// # Returns
    ///
    /// The total cost basis (quantity * average_premium)
    #[must_use]
    pub fn get_cost_basis(&self) -> Positive {
        Positive::new(
            (self.quantity.value() * self.average_premium.value())
                .to_f64()
                .unwrap_or(0.0),
        )
        .unwrap_or(Positive::ZERO)
    }

    /// Gets the percentage return of the position.
    ///
    /// # Returns
    ///
    /// The percentage return as a Decimal. Returns zero if current_price is not available.
    #[must_use]
    pub fn get_percentage_return(&self) -> Decimal {
        match self.current_premium {
            Some(_current_price) => {
                let pnl = self.get_unrealized_pnl();
                let cost_basis = self.get_cost_basis().value();
                if cost_basis > Decimal::ZERO {
                    (pnl / cost_basis) * Decimal::from(100)
                } else {
                    Decimal::ZERO
                }
            }
            None => Decimal::ZERO,
        }
    }
}

/// Represents margin information for accounts that support leverage
#[derive(
    DebugPretty, DisplaySimple, Clone, PartialEq, Serialize, Deserialize, ToSchema, Default,
)]
pub struct MarginInfo {
    /// Available margin for new positions
    pub available_margin: Decimal,
    /// Currently used margin
    pub used_margin: Decimal,
    /// Maintenance margin requirement
    pub maintenance_margin: Decimal,
    /// Initial margin requirement
    pub initial_margin: Option<Decimal>,
    /// Current margin ratio (used/available)
    pub margin_ratio: Option<Decimal>,
}

/// Represents a portfolio containing multiple option balances.
///
/// This struct provides functionality to manage and analyze a collection
/// of option positions across different exchanges.
#[derive(DebugPretty, DisplaySimple, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct Portfolio {
    /// Collection of option balances
    pub balances: Vec<Balance>,
    /// Name or identifier for the portfolio
    pub name: String,
}

impl Portfolio {
    /// Creates a new empty Portfolio.
    ///
    /// # Arguments
    ///
    /// * `name` - The name or identifier for the portfolio
    ///
    /// # Returns
    ///
    /// A new Portfolio instance with an empty balance collection
    #[must_use]
    pub fn new(name: String) -> Self {
        Self {
            balances: Vec::new(),
            name,
        }
    }

    /// Adds a balance to the portfolio.
    ///
    /// # Arguments
    ///
    /// * `balance` - The Balance to add to the portfolio
    pub fn add_balance(&mut self, balance: Balance) {
        self.balances.push(balance);
    }

    /// Removes a balance from the portfolio by symbol and exchange.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The asset symbol to remove
    /// * `exchange` - The exchange name to match
    ///
    /// # Returns
    ///
    /// `true` if a balance was removed, `false` if not found
    pub fn remove_balance(&mut self, symbol: &str, exchange: &str) -> bool {
        if let Some(pos) = self
            .balances
            .iter()
            .position(|b| b.symbol == symbol && b.exchange == exchange)
        {
            self.balances.remove(pos);
            true
        } else {
            false
        }
    }

    /// Gets a reference to a balance by symbol and exchange.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The asset symbol to find
    /// * `exchange` - The exchange name to match
    ///
    /// # Returns
    ///
    /// An optional reference to the Balance if found
    #[must_use]
    pub fn get_balance(&self, symbol: &str, exchange: &str) -> Option<&Balance> {
        self.balances
            .iter()
            .find(|b| b.symbol == symbol && b.exchange == exchange)
    }

    /// Gets a mutable reference to a balance by symbol and exchange.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The asset symbol to find
    /// * `exchange` - The exchange name to match
    ///
    /// # Returns
    ///
    /// An optional mutable reference to the Balance if found
    pub fn get_balance_mut(&mut self, symbol: &str, exchange: &str) -> Option<&mut Balance> {
        self.balances
            .iter_mut()
            .find(|b| b.symbol == symbol && b.exchange == exchange)
    }

    /// Calculates the total portfolio value.
    ///
    /// # Returns
    ///
    /// The sum of all balance values in the portfolio
    #[must_use]
    pub fn get_total_value(&self) -> Positive {
        let total_value: f64 = self
            .balances
            .iter()
            .map(|balance| balance.get_total_value().value().to_f64().unwrap_or(0.0))
            .sum();

        Positive::new(total_value).unwrap_or(Positive::ZERO)
    }

    /// Calculates the total unrealized PnL for the portfolio.
    ///
    /// # Returns
    ///
    /// The sum of all unrealized PnL across all balances
    #[must_use]
    pub fn get_total_unrealized_pnl(&self) -> Decimal {
        self.balances
            .iter()
            .map(|balance| balance.get_unrealized_pnl())
            .sum()
    }

    /// Gets all balances from a specific exchange.
    ///
    /// # Arguments
    ///
    /// * `exchange` - The exchange name to filter by
    ///
    /// # Returns
    ///
    /// A vector of references to balances from the specified exchange
    #[must_use]
    pub fn get_balances_by_exchange(&self, exchange: &str) -> Vec<&Balance> {
        self.balances
            .iter()
            .filter(|balance| balance.exchange == exchange)
            .collect()
    }

    /// Checks if the portfolio has any profitable positions.
    ///
    /// # Returns
    ///
    /// `true` if any balance in the portfolio is profitable
    #[must_use]
    pub fn has_profitable_positions(&self) -> bool {
        self.balances.iter().any(|balance| balance.is_profitable())
    }

    /// Gets the number of balances in the portfolio.
    ///
    /// # Returns
    ///
    /// The count of balances in the portfolio
    #[must_use]
    pub fn balance_count(&self) -> usize {
        self.balances.len()
    }

    /// Checks if the portfolio is empty.
    ///
    /// # Returns
    ///
    /// `true` if the portfolio has no balances
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.balances.is_empty()
    }
}

impl Default for Portfolio {
    fn default() -> Self {
        Self::new("Default Portfolio".to_string())
    }
}

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

    use rust_decimal_macros::dec;

    #[test]
    fn test_balance_creation() {
        let balance = Balance::new(
            "AAPL240315C00150000".to_string(),
            pos_or_panic!(10.0),
            pos_or_panic!(5.50),
            None,
            "CBOE".to_string(),
            UnderlyingAssetType::Stock,
            None,
        );

        assert_eq!(balance.symbol, "AAPL240315C00150000");
        assert_eq!(balance.quantity, pos_or_panic!(10.0));
        assert_eq!(balance.average_premium, pos_or_panic!(5.50));
        assert_eq!(balance.exchange, "CBOE");
        assert_eq!(balance.underlying_asset_type, UnderlyingAssetType::Stock);
        assert!(balance.current_premium.is_none());
        assert!(balance.margin_info.is_none());
    }

    #[test]
    fn test_balance_total_value() {
        let balance = Balance::new(
            "TSLA240315C00200000".to_string(),
            pos_or_panic!(5.0),
            pos_or_panic!(8.00),
            Some(pos_or_panic!(12.50)),
            "CBOE".to_string(),
            UnderlyingAssetType::Stock,
            None,
        );

        let total_value = balance.get_total_value();
        assert_eq!(total_value, pos_or_panic!(62.5)); // 5 * 12.50
    }

    #[test]
    fn test_balance_unrealized_pnl() {
        let balance = Balance::new(
            "AAPL240315C00150000".to_string(),
            pos_or_panic!(10.0),
            pos_or_panic!(5.50),
            Some(pos_or_panic!(7.00)),
            "CBOE".to_string(),
            UnderlyingAssetType::Stock,
            None,
        );

        let pnl = balance.get_unrealized_pnl();
        assert_eq!(pnl, dec!(15.0)); // (7.00 - 5.50) * 10
    }

    #[test]
    fn test_balance_is_profitable() {
        let profitable_balance = Balance::new(
            "GOOGL240315C00200000".to_string(),
            pos_or_panic!(5.0),
            pos_or_panic!(10.00),
            Some(pos_or_panic!(12.00)),
            "CBOE".to_string(),
            UnderlyingAssetType::Stock,
            None,
        );

        let losing_balance = Balance::new(
            "TSLA240315C00080000".to_string(),
            pos_or_panic!(3.0),
            pos_or_panic!(8.00),
            Some(pos_or_panic!(6.50)),
            "CBOE".to_string(),
            UnderlyingAssetType::Stock,
            None,
        );

        assert!(profitable_balance.is_profitable());
        assert!(!losing_balance.is_profitable());
    }

    #[test]
    fn test_portfolio_creation() {
        let portfolio = Portfolio::new("My Portfolio".to_string());
        assert_eq!(portfolio.name, "My Portfolio");
        assert!(portfolio.is_empty());
        assert_eq!(portfolio.balance_count(), 0);
    }

    #[test]
    fn test_portfolio_add_balance() {
        let mut portfolio = Portfolio::new("Test Portfolio".to_string());
        let balance = Balance::new(
            "AAPL240315C00150000".to_string(),
            pos_or_panic!(10.0),
            pos_or_panic!(5.50),
            Some(pos_or_panic!(7.00)),
            "CBOE".to_string(),
            UnderlyingAssetType::Stock,
            None,
        );

        portfolio.add_balance(balance);
        assert_eq!(portfolio.balance_count(), 1);
        assert!(!portfolio.is_empty());
    }

    #[test]
    fn test_portfolio_total_value() {
        let mut portfolio = Portfolio::new("Test Portfolio".to_string());

        let balance1 = Balance::new(
            "AAPL240315C00150000".to_string(),
            pos_or_panic!(10.0),
            pos_or_panic!(5.50),
            Some(pos_or_panic!(7.00)),
            "CBOE".to_string(),
            UnderlyingAssetType::Stock,
            None,
        );

        let balance2 = Balance::new(
            "TSLA240315C00200000".to_string(),
            pos_or_panic!(5.0),
            pos_or_panic!(8.00),
            Some(pos_or_panic!(12.50)),
            "CBOE".to_string(),
            UnderlyingAssetType::Stock,
            None,
        );

        portfolio.add_balance(balance1);
        portfolio.add_balance(balance2);

        let total_value = portfolio.get_total_value();
        assert_eq!(total_value, pos_or_panic!(132.5)); // 70.0 + 62.5
    }

    #[test]
    fn test_portfolio_get_balance() {
        let mut portfolio = Portfolio::new("Test Portfolio".to_string());
        let balance = Balance::new(
            "AAPL240315C00150000".to_string(),
            pos_or_panic!(10.0),
            pos_or_panic!(5.50),
            Some(pos_or_panic!(7.00)),
            "CBOE".to_string(),
            UnderlyingAssetType::Stock,
            None,
        );

        portfolio.add_balance(balance);

        let found_balance = portfolio.get_balance("AAPL240315C00150000", "CBOE");
        assert!(found_balance.is_some());
        assert_eq!(found_balance.unwrap().symbol, "AAPL240315C00150000");

        let not_found = portfolio.get_balance("TSLA240315C00200000", "CBOE");
        assert!(not_found.is_none());
    }
}