optionstratlib 0.17.3

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
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
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 24/12/25
******************************************************************************/

//! # Future Position Module
//!
//! This module provides the `FuturePosition` struct for representing standardized
//! exchange-traded futures contracts.
//!
//! ## Characteristics
//!
//! - Fixed expiration date
//! - Margin-based (leveraged)
//! - Mark-to-market daily settlement
//! - Delta ≈ ±1.0 per contract (adjusted for contract size)
//! - Rho sensitivity for interest rate changes
//!
//! ## Example
//!
//! ```rust
//! use optionstratlib::model::leg::FuturePosition;
//! use optionstratlib::model::types::Side;
//! use optionstratlib::model::ExpirationDate;
//! use positive::{pos_or_panic,Positive};
//! use chrono::Utc;
//!
//! let future = FuturePosition::new(
//!     "ES".to_string(),        // E-mini S&P 500
//!     Positive::TWO,               // 2 contracts
//!     pos_or_panic!(4500.0),            // entry price
//!     Side::Long,
//!     ExpirationDate::Days(pos_or_panic!(30.0)),
//!     pos_or_panic!(50.0),              // contract multiplier
//!     pos_or_panic!(15000.0),           // initial margin
//!     pos_or_panic!(12000.0),           // maintenance margin
//!     Utc::now(),
//!     pos_or_panic!(5.0),               // fees
//! );
//! ```

use crate::error::GreeksError;
use crate::model::ExpirationDate;
use crate::model::leg::traits::{Expirable, LegAble, Marginable};
use crate::model::types::Side;
use chrono::{DateTime, Utc};
use positive::Positive;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

/// Represents a futures contract position.
///
/// Futures are standardized contracts traded on exchanges that obligate the buyer
/// to purchase (or seller to sell) an asset at a predetermined price on a specific
/// future date.
///
/// # Fields
///
/// * `symbol` - Contract symbol (e.g., "ES", "CL", "BTC-QUARTERLY")
/// * `quantity` - Number of contracts
/// * `entry_price` - Average entry price
/// * `side` - Long or Short position
/// * `expiration_date` - Contract expiry date
/// * `contract_size` - Multiplier (e.g., 50 for ES, 1000 for CL)
/// * `initial_margin` - Initial margin requirement
/// * `maintenance_margin` - Maintenance margin level
/// * `date` - Position open timestamp
/// * `fees` - Commission and exchange fees
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct FuturePosition {
    /// Contract symbol (e.g., "ES", "CL", "GC").
    pub symbol: String,

    /// Number of contracts held.
    pub quantity: Positive,

    /// Average entry price per contract.
    pub entry_price: Positive,

    /// Position direction (Long or Short).
    pub side: Side,

    /// Contract expiration date.
    pub expiration_date: ExpirationDate,

    /// Contract size multiplier (notional per point).
    pub contract_size: Positive,

    /// Initial margin requirement per contract.
    pub initial_margin_req: Positive,

    /// Maintenance margin requirement per contract.
    pub maintenance_margin_req: Positive,

    /// Timestamp when the position was opened.
    pub date: DateTime<Utc>,

    /// Total trading fees paid.
    pub fees: Positive,
}

impl FuturePosition {
    /// Creates a new futures position.
    ///
    /// # Arguments
    ///
    /// * `symbol` - Contract symbol
    /// * `quantity` - Number of contracts
    /// * `entry_price` - Average entry price
    /// * `side` - Long or Short
    /// * `expiration_date` - Contract expiry
    /// * `contract_size` - Contract multiplier
    /// * `initial_margin_req` - Initial margin per contract
    /// * `maintenance_margin_req` - Maintenance margin per contract
    /// * `date` - Position open timestamp
    /// * `fees` - Trading fees
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        symbol: String,
        quantity: Positive,
        entry_price: Positive,
        side: Side,
        expiration_date: ExpirationDate,
        contract_size: Positive,
        initial_margin_req: Positive,
        maintenance_margin_req: Positive,
        date: DateTime<Utc>,
        fees: Positive,
    ) -> Self {
        Self {
            symbol,
            quantity,
            entry_price,
            side,
            expiration_date,
            contract_size,
            initial_margin_req,
            maintenance_margin_req,
            date,
            fees,
        }
    }

    /// Creates a long futures position with default settings.
    ///
    /// # Arguments
    ///
    /// * `symbol` - Contract symbol
    /// * `quantity` - Number of contracts
    /// * `entry_price` - Entry price
    /// * `expiration_date` - Contract expiry
    /// * `contract_size` - Contract multiplier
    /// * `margin` - Margin requirement
    #[must_use]
    pub fn long(
        symbol: String,
        quantity: Positive,
        entry_price: Positive,
        expiration_date: ExpirationDate,
        contract_size: Positive,
        margin: Positive,
    ) -> Self {
        Self::new(
            symbol,
            quantity,
            entry_price,
            Side::Long,
            expiration_date,
            contract_size,
            margin,
            margin * Decimal::new(8, 1), // 80% of initial margin
            Utc::now(),
            Positive::ZERO,
        )
    }

    /// Creates a short futures position with default settings.
    ///
    /// # Arguments
    ///
    /// * `symbol` - Contract symbol
    /// * `quantity` - Number of contracts
    /// * `entry_price` - Entry price
    /// * `expiration_date` - Contract expiry
    /// * `contract_size` - Contract multiplier
    /// * `margin` - Margin requirement
    #[must_use]
    pub fn short(
        symbol: String,
        quantity: Positive,
        entry_price: Positive,
        expiration_date: ExpirationDate,
        contract_size: Positive,
        margin: Positive,
    ) -> Self {
        Self::new(
            symbol,
            quantity,
            entry_price,
            Side::Short,
            expiration_date,
            contract_size,
            margin,
            margin * Decimal::new(8, 1),
            Utc::now(),
            Positive::ZERO,
        )
    }

    /// Returns the notional value of the position at entry.
    ///
    /// Notional = quantity × entry_price × contract_size
    #[must_use]
    pub fn notional_value_at_entry(&self) -> Positive {
        self.quantity * self.entry_price * self.contract_size
    }

    /// Returns the notional value at a given price.
    ///
    /// # Arguments
    ///
    /// * `current_price` - Current market price
    #[must_use]
    pub fn notional_value_at_price(&self, current_price: Positive) -> Positive {
        self.quantity * current_price * self.contract_size
    }

    /// Calculates the unrealized P&L at a given price.
    ///
    /// # Arguments
    ///
    /// * `current_price` - Current market price
    #[must_use]
    pub fn unrealized_pnl(&self, current_price: Positive) -> Decimal {
        let price_change = current_price.to_dec() - self.entry_price.to_dec();
        let pnl = price_change * self.quantity.to_dec() * self.contract_size.to_dec();

        match self.side {
            Side::Long => pnl,
            Side::Short => -pnl,
        }
    }

    /// Calculates the tick value (value of one minimum price movement).
    ///
    /// # Arguments
    ///
    /// * `tick_size` - Minimum price increment
    #[must_use]
    pub fn tick_value(&self, tick_size: Positive) -> Positive {
        tick_size * self.contract_size
    }

    /// Returns the total margin required for this position.
    #[must_use]
    pub fn total_margin_required(&self) -> Positive {
        self.initial_margin_req * self.quantity
    }

    /// Calculates the basis (futures price - spot price).
    ///
    /// # Arguments
    ///
    /// * `spot_price` - Current spot price of the underlying
    #[must_use]
    pub fn basis(&self, spot_price: Positive) -> Decimal {
        self.entry_price.to_dec() - spot_price.to_dec()
    }

    /// Calculates the implied leverage of the position.
    ///
    /// Leverage = Notional Value / Margin Required
    #[must_use]
    pub fn implied_leverage(&self) -> Decimal {
        let margin = self.total_margin_required();
        if margin == Positive::ZERO {
            return Decimal::ZERO;
        }

        self.notional_value_at_entry().to_dec() / margin.to_dec()
    }
}

impl LegAble for FuturePosition {
    fn get_symbol(&self) -> &str {
        &self.symbol
    }

    fn get_quantity(&self) -> Positive {
        self.quantity
    }

    fn get_side(&self) -> Side {
        self.side
    }

    fn pnl_at_price(&self, price: Positive) -> Decimal {
        self.unrealized_pnl(price) - self.fees.to_dec()
    }

    fn total_cost(&self) -> Positive {
        self.total_margin_required() + self.fees
    }

    fn fees(&self) -> Positive {
        self.fees
    }

    fn delta(&self) -> Result<Decimal, GreeksError> {
        let delta_per_contract = match self.side {
            Side::Long => self.contract_size.to_dec(),
            Side::Short => -self.contract_size.to_dec(),
        };
        Ok(delta_per_contract * self.quantity.to_dec())
    }

    fn rho(&self) -> Result<Decimal, GreeksError> {
        let time_to_exp = self.time_to_expiration_years();
        let notional = self.notional_value_at_entry().to_dec();

        let rho_value = match self.side {
            Side::Long => notional * time_to_exp,
            Side::Short => -notional * time_to_exp,
        };

        Ok(rho_value / Decimal::ONE_HUNDRED)
    }
}

impl Marginable for FuturePosition {
    fn initial_margin(&self) -> Positive {
        self.initial_margin_req * self.quantity
    }

    fn maintenance_margin(&self) -> Positive {
        self.maintenance_margin_req * self.quantity
    }

    fn leverage(&self) -> Positive {
        let lev = self.implied_leverage();
        Positive::new_decimal(lev).unwrap_or(positive::Positive::ONE)
    }

    fn liquidation_price(&self, _current_price: Positive) -> Positive {
        let margin_buffer = self.initial_margin().to_dec() - self.maintenance_margin().to_dec();
        let price_buffer = margin_buffer / (self.quantity.to_dec() * self.contract_size.to_dec());

        match self.side {
            Side::Long => {
                let liq = self.entry_price.to_dec() - price_buffer;
                Positive::new_decimal(liq).unwrap_or(Positive::ZERO)
            }
            Side::Short => {
                let liq = self.entry_price.to_dec() + price_buffer;
                Positive::new_decimal(liq).unwrap_or(Positive::ZERO)
            }
        }
    }

    fn is_liquidation_risk(&self, current_price: Positive, _margin_ratio: Decimal) -> bool {
        let liq_price = self.liquidation_price(current_price);

        match self.side {
            Side::Long => current_price <= liq_price,
            Side::Short => current_price >= liq_price,
        }
    }
}

impl Expirable for FuturePosition {
    fn expiration_timestamp(&self) -> i64 {
        self.expiration_date
            .get_date()
            .map(|d| d.timestamp())
            .unwrap_or(0)
    }

    fn days_to_expiration(&self) -> Positive {
        self.expiration_date.get_years().unwrap_or(Positive::ZERO) * Decimal::from(365)
    }

    fn is_expired(&self) -> bool {
        self.expiration_date
            .get_date()
            .map(|d| d < Utc::now())
            .unwrap_or(false)
    }
}

impl std::fmt::Display for FuturePosition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} {} {} @ {} (size: {}, exp: {})",
            self.side,
            self.quantity,
            self.symbol,
            self.entry_price,
            self.contract_size,
            self.expiration_date
        )
    }
}

impl Default for FuturePosition {
    fn default() -> Self {
        Self {
            symbol: String::new(),
            quantity: Positive::ZERO,
            entry_price: Positive::ZERO,
            side: Side::Long,
            // `dec!(30.0)` is a compile-time positive literal; the checked
            // constructor never fails, so the `Positive::ZERO` fallback is
            // unreachable and only exists to keep the call site free of
            // `.unwrap()`/`.expect()`.
            expiration_date: ExpirationDate::Days(
                Positive::new_decimal(dec!(30.0)).unwrap_or(Positive::ZERO),
            ),
            contract_size: positive::Positive::ONE,
            initial_margin_req: Positive::ZERO,
            maintenance_margin_req: Positive::ZERO,
            date: Utc::now(),
            fees: Positive::ZERO,
        }
    }
}

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

    #[test]
    fn test_future_position_new() {
        let future = FuturePosition::new(
            "ES".to_string(),
            Positive::TWO,
            pos_or_panic!(4500.0),
            Side::Long,
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
            pos_or_panic!(12000.0),
            Utc::now(),
            pos_or_panic!(5.0),
        );

        assert_eq!(future.symbol, "ES");
        assert_eq!(future.quantity, Positive::TWO);
        assert_eq!(future.entry_price, pos_or_panic!(4500.0));
        assert_eq!(future.side, Side::Long);
        assert_eq!(future.contract_size, pos_or_panic!(50.0));
    }

    #[test]
    fn test_future_long_convenience() {
        let future = FuturePosition::long(
            "ES".to_string(),
            Positive::ONE,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        assert_eq!(future.side, Side::Long);
        assert_eq!(future.initial_margin_req, pos_or_panic!(15000.0));
    }

    #[test]
    fn test_future_short_convenience() {
        let future = FuturePosition::short(
            "ES".to_string(),
            Positive::ONE,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        assert_eq!(future.side, Side::Short);
    }

    #[test]
    fn test_notional_value() {
        let future = FuturePosition::long(
            "ES".to_string(),
            Positive::TWO,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        assert_eq!(future.notional_value_at_entry(), pos_or_panic!(450000.0));
    }

    #[test]
    fn test_unrealized_pnl_long() {
        let future = FuturePosition::long(
            "ES".to_string(),
            Positive::ONE,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        let pnl = future.unrealized_pnl(pos_or_panic!(4510.0));
        assert_eq!(pnl, Decimal::from(500));

        let pnl_loss = future.unrealized_pnl(pos_or_panic!(4490.0));
        assert_eq!(pnl_loss, Decimal::from(-500));
    }

    #[test]
    fn test_unrealized_pnl_short() {
        let future = FuturePosition::short(
            "ES".to_string(),
            Positive::ONE,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        let pnl = future.unrealized_pnl(pos_or_panic!(4490.0));
        assert_eq!(pnl, Decimal::from(500));

        let pnl_loss = future.unrealized_pnl(pos_or_panic!(4510.0));
        assert_eq!(pnl_loss, Decimal::from(-500));
    }

    #[test]
    fn test_delta_long() {
        let future = FuturePosition::long(
            "ES".to_string(),
            Positive::TWO,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        assert_eq!(future.delta().unwrap(), Decimal::from(100));
    }

    #[test]
    fn test_delta_short() {
        let future = FuturePosition::short(
            "ES".to_string(),
            Positive::TWO,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        assert_eq!(future.delta().unwrap(), Decimal::from(-100));
    }

    #[test]
    fn test_implied_leverage() {
        let future = FuturePosition::long(
            "ES".to_string(),
            Positive::ONE,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        let leverage = future.implied_leverage();
        assert_eq!(leverage, Decimal::from(15));
    }

    #[test]
    fn test_basis() {
        let future = FuturePosition::long(
            "ES".to_string(),
            Positive::ONE,
            pos_or_panic!(4510.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        let basis = future.basis(pos_or_panic!(4500.0));
        assert_eq!(basis, Decimal::from(10));
    }

    #[test]
    fn test_tick_value() {
        let future = FuturePosition::long(
            "ES".to_string(),
            Positive::ONE,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        let tick_val = future.tick_value(pos_or_panic!(0.25));
        assert_eq!(tick_val, pos_or_panic!(12.5));
    }

    #[test]
    fn test_total_margin_required() {
        let future = FuturePosition::long(
            "ES".to_string(),
            Positive::TWO,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        assert_eq!(future.total_margin_required(), pos_or_panic!(30000.0));
    }

    #[test]
    fn test_display() {
        let future = FuturePosition::long(
            "ES".to_string(),
            Positive::ONE,
            pos_or_panic!(4500.0),
            ExpirationDate::Days(pos_or_panic!(30.0)),
            pos_or_panic!(50.0),
            pos_or_panic!(15000.0),
        );

        let display = format!("{}", future);
        assert!(display.contains("Long"));
        assert!(display.contains("ES"));
        assert!(display.contains("4500"));
    }
}