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

//! # Leg Traits Module
//!
//! This module defines common traits for different types of trading legs
//! (positions in various instruments like spot, futures, perpetuals, etc.).
//!
//! The `LegAble` trait provides a unified interface for calculating profit/loss,
//! retrieving position information, and computing Greeks across different
//! instrument types.

use crate::error::GreeksError;
use crate::model::types::Side;
use positive::Positive;
use rust_decimal::Decimal;

/// Common trait for all leg types in a trading strategy.
///
/// This trait provides a unified interface for different position types
/// (spot, futures, perpetuals, options, etc.) enabling polymorphic handling
/// in multi-leg strategies.
///
/// # Implementors
///
/// - `SpotPosition` - Direct ownership of underlying asset
/// - `FuturePosition` - Exchange-traded futures contracts
/// - `PerpetualPosition` - Crypto perpetual swap contracts
/// - `Position` - Option positions (via adapter)
pub trait LegAble {
    /// Returns the symbol/ticker of the underlying instrument.
    fn get_symbol(&self) -> &str;

    /// Returns the position quantity (number of units/contracts).
    fn get_quantity(&self) -> Positive;

    /// Returns the position side (Long or Short).
    fn get_side(&self) -> Side;

    /// Calculates the profit/loss at a given price.
    ///
    /// # Arguments
    ///
    /// * `price` - The price at which to calculate P&L
    ///
    /// # Returns
    ///
    /// The profit (positive) or loss (negative) as a Decimal value.
    fn pnl_at_price(&self, price: Positive) -> Decimal;

    /// Returns the total cost to establish this position.
    ///
    /// For long positions, this includes the purchase price plus fees.
    /// For short positions, this typically includes only fees.
    fn total_cost(&self) -> Positive;

    /// Returns the total fees associated with this position.
    fn fees(&self) -> Positive;

    /// Returns the delta of this position.
    ///
    /// - Spot positions: ±1.0 per unit (Long = +1, Short = -1)
    /// - Futures/Perpetuals: ±1.0 × contract_size × leverage
    /// - Options: Calculated from Black-Scholes or other models
    ///
    /// # Returns
    ///
    /// The position delta as a Decimal, or an error if calculation fails.
    ///
    /// # Errors
    ///
    /// Propagates any [`GreeksError`] returned by the underlying pricing
    /// kernel, typically [`GreeksError::Pricing`] for option legs whose
    /// Black–Scholes evaluation fails, or [`GreeksError::ExpirationDate`]
    /// when the expiration cannot be resolved.
    fn delta(&self) -> Result<Decimal, GreeksError>;

    /// Returns the gamma of this position.
    ///
    /// For linear instruments (spot, futures, perpetuals), gamma is always 0.
    /// Only options have non-zero gamma.
    ///
    /// # Returns
    ///
    /// The position gamma as a Decimal, or an error if calculation fails.
    ///
    /// # Errors
    ///
    /// The default implementation is infallible (returns `0`). Option-leg
    /// implementors propagate [`GreeksError::Pricing`] on Black–Scholes
    /// failure or [`GreeksError::ExpirationDate`] when the expiration is
    /// invalid.
    fn gamma(&self) -> Result<Decimal, GreeksError> {
        Ok(Decimal::ZERO)
    }

    /// Returns the theta of this position.
    ///
    /// - Spot: 0 (no time decay)
    /// - Futures: ~0 (basis converges over time)
    /// - Perpetuals: Funding rate impact
    /// - Options: Calculated time decay
    ///
    /// # Returns
    ///
    /// The position theta as a Decimal, or an error if calculation fails.
    ///
    /// # Errors
    ///
    /// The default implementation is infallible (returns `0`). Option-leg
    /// implementors propagate [`GreeksError::Pricing`] when the closed-form
    /// time-decay evaluation fails or [`GreeksError::ExpirationDate`] when
    /// the expiration cannot be resolved.
    fn theta(&self) -> Result<Decimal, GreeksError> {
        Ok(Decimal::ZERO)
    }

    /// Returns the vega of this position.
    ///
    /// For linear instruments (spot, futures, perpetuals), vega is always 0.
    /// Only options have non-zero vega.
    ///
    /// # Returns
    ///
    /// The position vega as a Decimal, or an error if calculation fails.
    ///
    /// # Errors
    ///
    /// The default implementation is infallible (returns `0`). Option-leg
    /// implementors propagate [`GreeksError::Pricing`] when the Black–Scholes
    /// vega evaluation fails or [`GreeksError::ExpirationDate`] when the
    /// expiration cannot be resolved.
    fn vega(&self) -> Result<Decimal, GreeksError> {
        Ok(Decimal::ZERO)
    }

    /// Returns the rho of this position.
    ///
    /// - Spot: 0
    /// - Futures/Forwards: Interest rate sensitivity
    /// - Options: Calculated interest rate sensitivity
    ///
    /// # Returns
    ///
    /// The position rho as a Decimal, or an error if calculation fails.
    ///
    /// # Errors
    ///
    /// The default implementation is infallible (returns `0`). Option-leg
    /// implementors propagate [`GreeksError::Pricing`] when the rho
    /// evaluation fails or [`GreeksError::ExpirationDate`] when the
    /// expiration cannot be resolved.
    fn rho(&self) -> Result<Decimal, GreeksError> {
        Ok(Decimal::ZERO)
    }

    /// Checks if this is a long position.
    #[must_use]
    fn is_long(&self) -> bool {
        matches!(self.get_side(), Side::Long)
    }

    /// Checks if this is a short position.
    #[must_use]
    fn is_short(&self) -> bool {
        matches!(self.get_side(), Side::Short)
    }

    /// Returns the notional value of the position at a given price.
    ///
    /// Notional = quantity × price
    fn notional_value(&self, price: Positive) -> Positive {
        self.get_quantity() * price
    }
}

/// Trait for positions that have margin requirements.
///
/// This applies to futures, perpetuals, and CFDs where positions
/// are leveraged and require margin collateral.
pub trait Marginable: LegAble {
    /// Returns the initial margin requirement.
    fn initial_margin(&self) -> Positive;

    /// Returns the maintenance margin requirement.
    fn maintenance_margin(&self) -> Positive;

    /// Returns the current leverage applied to the position.
    fn leverage(&self) -> Positive;

    /// Calculates the liquidation price for this position.
    ///
    /// # Arguments
    ///
    /// * `current_price` - The current market price
    ///
    /// # Returns
    ///
    /// The price at which the position would be liquidated.
    fn liquidation_price(&self, current_price: Positive) -> Positive;

    /// Checks if the position is at risk of liquidation.
    ///
    /// # Arguments
    ///
    /// * `current_price` - The current market price
    /// * `margin_ratio` - Current margin ratio (margin / notional)
    fn is_liquidation_risk(&self, current_price: Positive, margin_ratio: Decimal) -> bool;
}

/// Trait for positions that have funding rate payments.
///
/// This applies primarily to perpetual swap contracts in crypto markets.
pub trait Fundable: LegAble {
    /// Returns the current funding rate (as a decimal, e.g., 0.0001 = 0.01%).
    fn funding_rate(&self) -> Decimal;

    /// Returns the funding interval in hours (typically 8 for most exchanges).
    fn funding_interval_hours(&self) -> u32;

    /// Calculates the funding payment for the current period.
    ///
    /// Positive value means the position pays funding.
    /// Negative value means the position receives funding.
    ///
    /// # Arguments
    ///
    /// * `mark_price` - The current mark price for funding calculation
    fn funding_payment(&self, mark_price: Positive) -> Decimal;

    /// Calculates the annualized funding cost/income.
    ///
    /// # Arguments
    ///
    /// * `mark_price` - The current mark price
    fn annualized_funding(&self, mark_price: Positive) -> Decimal {
        let payment = self.funding_payment(mark_price);
        let periods_per_year = Decimal::from(24 * 365 / self.funding_interval_hours());
        payment * periods_per_year
    }
}

/// Trait for positions that have an expiration date.
///
/// This applies to futures, forwards, and options.
pub trait Expirable: LegAble {
    /// Returns the expiration date as a timestamp.
    fn expiration_timestamp(&self) -> i64;

    /// Returns the number of days until expiration.
    fn days_to_expiration(&self) -> Positive;

    /// Checks if the position has expired.
    fn is_expired(&self) -> bool;

    /// Returns the time to expiration in years (for pricing calculations).
    fn time_to_expiration_years(&self) -> Decimal {
        self.days_to_expiration().to_dec() / Decimal::from(365)
    }
}

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

    /// Mock implementation for testing
    struct MockLeg {
        symbol: String,
        quantity: Positive,
        side: Side,
        cost_basis: Positive,
        fees: Positive,
    }

    impl LegAble for MockLeg {
        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 {
            let value_change = (price.to_dec() - self.cost_basis.to_dec()) * self.quantity.to_dec();
            match self.side {
                Side::Long => value_change,
                Side::Short => -value_change,
            }
        }

        fn total_cost(&self) -> Positive {
            self.cost_basis * self.quantity + self.fees
        }

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

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

    #[test]
    fn test_mock_leg_long_pnl() {
        let leg = MockLeg {
            symbol: "BTC".to_string(),
            quantity: positive::Positive::ONE,
            side: Side::Long,
            cost_basis: positive::pos_or_panic!(50000.0),
            fees: positive::pos_or_panic!(10.0),
        };

        // Price goes up - profit
        let pnl = leg.pnl_at_price(positive::pos_or_panic!(55000.0));
        assert_eq!(pnl, Decimal::from(5000));

        // Price goes down - loss
        let pnl = leg.pnl_at_price(positive::pos_or_panic!(45000.0));
        assert_eq!(pnl, Decimal::from(-5000));
    }

    #[test]
    fn test_mock_leg_short_pnl() {
        let leg = MockLeg {
            symbol: "BTC".to_string(),
            quantity: positive::Positive::ONE,
            side: Side::Short,
            cost_basis: positive::pos_or_panic!(50000.0),
            fees: positive::pos_or_panic!(10.0),
        };

        // Price goes up - loss for short
        let pnl = leg.pnl_at_price(positive::pos_or_panic!(55000.0));
        assert_eq!(pnl, Decimal::from(-5000));

        // Price goes down - profit for short
        let pnl = leg.pnl_at_price(positive::pos_or_panic!(45000.0));
        assert_eq!(pnl, Decimal::from(5000));
    }

    #[test]
    fn test_mock_leg_delta() {
        let long_leg = MockLeg {
            symbol: "BTC".to_string(),
            quantity: positive::Positive::TWO,
            side: Side::Long,
            cost_basis: positive::pos_or_panic!(50000.0),
            fees: positive::pos_or_panic!(10.0),
        };

        let short_leg = MockLeg {
            symbol: "BTC".to_string(),
            quantity: positive::Positive::TWO,
            side: Side::Short,
            cost_basis: positive::pos_or_panic!(50000.0),
            fees: positive::pos_or_panic!(10.0),
        };

        assert_eq!(long_leg.delta().unwrap(), Decimal::from(2));
        assert_eq!(short_leg.delta().unwrap(), Decimal::from(-2));
    }

    #[test]
    fn test_is_long_short() {
        let long_leg = MockLeg {
            symbol: "BTC".to_string(),
            quantity: positive::Positive::ONE,
            side: Side::Long,
            cost_basis: positive::pos_or_panic!(50000.0),
            fees: positive::pos_or_panic!(10.0),
        };

        let short_leg = MockLeg {
            symbol: "BTC".to_string(),
            quantity: Positive::ONE,
            side: Side::Short,
            cost_basis: positive::pos_or_panic!(50000.0),
            fees: positive::pos_or_panic!(10.0),
        };

        assert!(long_leg.is_long());
        assert!(!long_leg.is_short());
        assert!(!short_leg.is_long());
        assert!(short_leg.is_short());
    }

    #[test]
    fn test_notional_value() {
        let leg = MockLeg {
            symbol: "BTC".to_string(),
            quantity: positive::Positive::TWO,
            side: Side::Long,
            cost_basis: positive::pos_or_panic!(50000.0),
            fees: positive::pos_or_panic!(10.0),
        };

        let notional = leg.notional_value(positive::pos_or_panic!(55000.0));
        assert_eq!(notional, positive::pos_or_panic!(110000.0));
    }
}