optionstratlib 0.17.1

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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 2/10/24
******************************************************************************/
// Scoped allow: bulk migration of unchecked `[]` indexing to
// `.get().ok_or_else(..)` tracked as follow-ups to #341. The existing
// call sites are internal to this file and audited for invariant-bound
// indices (fixed-length buffers, just-pushed slices, etc.).
#![allow(clippy::indexing_slicing)]

use super::base::{
    BreakEvenable, Optimizable, Positionable, Strategable, StrategyBasics, StrategyType, Validable,
};
use crate::{
    ExpirationDate, Options,
    chains::{OptionData, chain::OptionChain},
    error::{
        GreeksError, OperationErrorKind, PricingError, position::PositionError,
        probability::ProbabilityError, strategies::StrategyError,
    },
    greeks::Greeks,
    model::{
        ProfitLossRange, Trade,
        decimal::d_add,
        position::Position,
        types::{Action, OptionBasicType, OptionStyle, Side},
        utils::mean_and_std,
    },
    pnl::{PnLCalculator, utils::PnL},
    pricing::payoff::Profit,
    strategies::{
        BasicAble, DeltaAdjustment, Strategies, StrategyConstructor,
        delta_neutral::DeltaNeutrality,
        probabilities::{core::ProbabilityAnalysis, utils::VolatilityAdjustment},
        utils::{FindOptimalSide, OptimizationCriteria},
    },
    utils::process_n_times_iter,
};
use num_traits::ToPrimitive;
use positive::Positive;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use tracing::{debug, error};
use utoipa::ToSchema;

/// Build a `Positive` from a compile-time non-negative `Decimal` literal.
///
/// All call sites in this module pass `dec!(X.X)` with a statically
/// non-negative value, so the checked constructor is total; the
/// `Positive::ZERO` branch is unreachable and only exists to keep the
/// call site free of `.unwrap()`/`.expect()` per §Error Handling.
#[inline]
fn pos_lit(value: Decimal) -> Positive {
    Positive::new_decimal(value).unwrap_or(Positive::ZERO)
}

/// Represents a custom options trading strategy with user-defined positions and characteristics.
///
/// The `CustomStrategy` struct allows traders to create and analyze bespoke options strategies
/// that don't fit into standard predefined patterns. It contains information about the strategy's
/// positions, risk-reward profile, break-even points, and provides methods for profit-loss analysis.
///
/// This structure supports both analytical calculations and visualization of custom strategies,
/// enabling traders to evaluate potential outcomes across different price points of the underlying asset.
///
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct CustomStrategy {
    /// The name of the custom strategy.
    pub name: String,

    /// The ticker symbol of the underlying asset.
    pub symbol: String,

    /// The type of strategy, typically set to StrategyType::Custom.
    pub kind: StrategyType,

    /// A detailed description of the strategy, its purpose, and expected outcomes.
    pub description: String,

    /// The price points at which the strategy breaks even (neither profit nor loss).
    pub break_even_points: Vec<Positive>,

    /// The collection of option positions that make up the strategy.
    pub positions: Vec<Position>,

    /// The current price of the underlying asset.
    pub underlying_price: Positive,

    /// Tolerance value used in numerical calculations for finding critical points.
    epsilon: Positive,

    /// Maximum number of iterations allowed in numerical algorithms.
    max_iterations: u32,

    /// Step size used in price interval calculations.
    step_by: Positive,

    /// The price point and value of maximum profit, if calculated.
    max_profit_point: Option<(Positive, f64)>,

    /// The price point and value of maximum loss, if calculated.
    max_loss_point: Option<(Positive, f64)>,
}

impl CustomStrategy {
    /// Creates a new custom options trading strategy with the specified parameters.
    ///
    /// This constructor initializes a `CustomStrategy` instance and performs several
    /// validation and calculation steps to ensure the strategy is valid and properly
    /// analyzed before being returned to the caller.
    ///
    /// # Parameters
    /// * `name` - The name of the custom strategy
    /// * `symbol` - The ticker symbol of the underlying asset
    /// * `description` - A detailed description of the strategy's purpose and characteristics
    /// * `underlying_price` - The current price of the underlying asset
    /// * `positions` - A collection of option positions that compose the strategy
    /// * `epsilon` - Tolerance value used in numerical calculations for finding critical points
    /// * `max_iterations` - Maximum number of iterations allowed in numerical algorithms
    /// * `step_by` - Step size used in price interval calculations
    ///
    /// # Returns
    /// A fully initialized `CustomStrategy` instance with calculated break-even points,
    /// maximum profit, and maximum loss information.
    ///
    /// # Errors
    ///
    /// Returns `StrategyError::OperationError` when `positions` is empty, and
    /// propagates any error from `update_break_even_points`.
    #[allow(clippy::too_many_arguments)]
    #[inline(never)]
    pub fn new(
        name: String,
        symbol: String,
        description: String,
        underlying_price: Positive,
        positions: Vec<Position>,
        epsilon: Positive,
        max_iterations: u32,
        step_by: Positive,
    ) -> Result<Self, StrategyError> {
        let mut strategy = CustomStrategy {
            name,
            symbol,
            kind: StrategyType::Custom,
            description,
            break_even_points: Vec::new(),
            positions,
            underlying_price,
            epsilon,
            max_iterations,
            step_by,
            max_profit_point: None,
            max_loss_point: None,
        };
        // Basic validation - check positions are not empty
        if strategy.positions.is_empty() {
            return Err(StrategyError::invalid_parameters(
                "CustomStrategy::new",
                "positions cannot be empty",
            ));
        }
        strategy.update_break_even_points()?;
        Ok(strategy)
    }

    fn update_positions(&mut self, new_positions: Vec<Position>) {
        self.positions = new_positions;
        if self.positions.is_empty() {
            tracing::warn!(
                "CustomStrategy::update_positions received empty vector; leaving break-even points unchanged"
            );
            return;
        }
        if let Err(err) = self.update_break_even_points() {
            tracing::error!(
                error = ?err,
                "CustomStrategy::update_positions failed to recompute break-even points"
            );
        }
    }

    /// Calculate the best range to show for price analysis
    fn range_to_show(&self) -> Result<(Positive, Positive), StrategyError> {
        if self.positions.is_empty() {
            return Err(StrategyError::OperationError(
                OperationErrorKind::InvalidParameters {
                    operation: "range_to_show".to_string(),
                    reason: "No positions found".to_string(),
                },
            ));
        }

        let strikes: Vec<Positive> = self
            .positions
            .iter()
            .map(|position| position.option.strike_price)
            .collect();

        let min_strike = strikes.iter().min().unwrap_or(&self.underlying_price);
        let max_strike = strikes.iter().max().unwrap_or(&self.underlying_price);

        // Use a much more focused range calculation for better visualization
        let strike_range = *max_strike - *min_strike;

        // For strategies with small strike ranges, use a very focused approach
        let base_extension = if strike_range < self.underlying_price * pos_lit(dec!(0.05)) {
            // Very tight strikes (< 5% of underlying) - use minimal extension
            strike_range * pos_lit(dec!(1.5)) // 150% of strike range
        } else {
            // Wider strikes - use moderate extension
            strike_range * Positive::ONE // 100% of strike range
        };

        // Center around the underlying price for better focus
        let center_price = self.underlying_price;
        let min_price = center_price - base_extension;
        let max_price = center_price + base_extension;

        Ok((min_price, max_price))
    }

    /// Get the best range to show for visualization
    #[allow(dead_code)]
    fn best_range_to_show(&self, step: Positive) -> Result<Vec<Positive>, StrategyError> {
        let mut prices = Vec::new();
        let mut current_price = self.underlying_price * pos_lit(dec!(0.5));
        let max_price = self.underlying_price * pos_lit(dec!(1.5));

        while current_price <= max_price {
            prices.push(current_price);
            current_price += step;
        }

        Ok(prices)
    }

    /// Refine a break-even point guess using Newton-Raphson method.
    ///
    /// Returns `None` instead of panicking if any per-iteration profit
    /// evaluation or `Decimal -> f64` conversion fails.
    #[allow(dead_code)]
    fn refine_break_even_point(&self, initial_guess: Positive) -> Option<Positive> {
        let mut x = initial_guess;
        let mut iterations = 0;

        while iterations < self.max_iterations {
            let f_x = self.calculate_profit_at(&x).ok()?.to_f64()?;

            // Check if we're close enough to zero
            if f_x.abs() < self.epsilon {
                return Some(x);
            }

            // Calculate derivative numerically with smaller step
            let h = self.epsilon.sqrt();
            let f_x_h = self.calculate_profit_at(&(x + h)).ok()?.to_f64()?;
            let derivative = (f_x_h - f_x) / h;

            // Avoid division by very small numbers
            if derivative.abs() < self.epsilon {
                break;
            }

            // Newton-Raphson step
            let next_x = x - f_x / derivative;

            // Check for convergence with absolute difference
            if (next_x.to_f64() - x.to_f64()).abs() < self.epsilon {
                return Some(next_x);
            }

            x = next_x;
            iterations += 1;
        }

        None
    }

    /// Add a break-even point if it's not already in the list
    #[allow(dead_code)]
    fn add_unique_break_even(&mut self, point: Positive) {
        if !self
            .break_even_points
            .iter()
            .any(|p| (p.to_f64() - point.to_f64()).abs() < self.epsilon)
        {
            self.break_even_points.push(point);
        }
    }

    pub(crate) fn get_profit_loss_zones(
        &self,
        break_even_points: &[Positive],
    ) -> Result<(Vec<ProfitLossRange>, Vec<ProfitLossRange>), ProbabilityError> {
        if break_even_points.is_empty() {
            return Ok((vec![], vec![]));
        }

        let mut profit_zones = Vec::new();
        let mut loss_zones = Vec::new();

        if break_even_points.len() == 1 {
            let break_even = break_even_points[0];
            let test_point = break_even - pos_lit(dec!(0.01));
            let is_profit_below = self.calculate_profit_at(&test_point)? > Decimal::ZERO;

            if is_profit_below {
                profit_zones.push(ProfitLossRange::new(
                    None,
                    Some(break_even),
                    Positive::ZERO,
                )?);
                loss_zones.push(ProfitLossRange::new(
                    Some(break_even),
                    None,
                    Positive::ZERO,
                )?);
            } else {
                loss_zones.push(ProfitLossRange::new(
                    None,
                    Some(break_even),
                    Positive::ZERO,
                )?);
                profit_zones.push(ProfitLossRange::new(
                    Some(break_even),
                    None,
                    Positive::ZERO,
                )?);
            }
        } else {
            // Multiple break-even points
            let test_point = break_even_points[0] - pos_lit(dec!(0.01));
            let is_profit_below = self.calculate_profit_at(&test_point)? > Decimal::ZERO;
            let is_first_zone_profit = is_profit_below;

            // Create ranges between break-even points
            let ranges = (0..=break_even_points.len())
                .map(|i| match i {
                    0 => ProfitLossRange::new(None, Some(break_even_points[0]), Positive::ZERO),
                    i if i == break_even_points.len() => {
                        ProfitLossRange::new(Some(break_even_points[i - 1]), None, Positive::ZERO)
                    }
                    i => ProfitLossRange::new(
                        Some(break_even_points[i - 1]),
                        Some(break_even_points[i]),
                        Positive::ZERO,
                    ),
                })
                .collect::<Result<Vec<_>, _>>()?;

            // Classify ranges as profit or loss zones
            for (i, range) in ranges.into_iter().enumerate() {
                if (is_first_zone_profit && i % 2 == 0) || (!is_first_zone_profit && i % 2 != 0) {
                    profit_zones.push(range);
                } else {
                    loss_zones.push(range);
                }
            }
        }

        Ok((profit_zones, loss_zones))
    }
}

impl StrategyConstructor for CustomStrategy {
    fn get_strategy(vec_options: &[Position]) -> Result<Self, StrategyError> {
        Self::new(
            "CustomStrategy".to_string(),
            "".to_string(),
            format!("CustomStrategy: {:?}", vec_options),
            Default::default(),
            Vec::from(vec_options),
            Default::default(),
            100,
            Default::default(),
        )
    }
}

impl BreakEvenable for CustomStrategy {
    fn get_break_even_points(&self) -> Result<&Vec<Positive>, StrategyError> {
        Ok(&self.break_even_points)
    }

    fn update_break_even_points(&mut self) -> Result<(), StrategyError> {
        // Simple implementation - calculate break-even points by finding where profit = 0
        self.break_even_points.clear();

        // Get a reasonable price range
        let min_price = self.underlying_price * pos_lit(dec!(0.5));
        let max_price = self.underlying_price * pos_lit(dec!(1.5));
        let step = pos_lit(dec!(0.01));

        let mut current_price = min_price;
        while current_price <= max_price {
            if let Ok(profit) = self.calculate_profit_at(&current_price)
                && profit.abs() < rust_decimal::Decimal::new(1, 2)
            {
                // Close to zero
                self.break_even_points.push(current_price);
            }
            current_price += step;
        }

        Ok(())
    }
}

impl Positionable for CustomStrategy {
    fn add_position(&mut self, position: &Position) -> Result<(), PositionError> {
        self.positions.push(position.clone());
        if !self.validate() {
            return Err(PositionError::invalid_position(
                "Strategy is not valid after adding new position",
            ));
        }
        let _ = self.update_break_even_points();
        Ok(())
    }

    fn get_positions(&self) -> Result<Vec<&Position>, PositionError> {
        Ok(self.positions.iter().collect())
    }

    fn get_position(
        &mut self,
        option_style: &OptionStyle,
        side: &Side,
        strike: &Positive,
    ) -> Result<Vec<&mut Position>, PositionError> {
        let matching_positions: Vec<&mut Position> = self
            .positions
            .iter_mut()
            .filter(|position| {
                position.option.option_style == *option_style
                    && position.option.side == *side
                    && position.option.strike_price == *strike
            })
            .collect();

        if matching_positions.is_empty() {
            Err(PositionError::invalid_position(&format!(
                "Position not found: {:?} {:?} strike {}",
                option_style, side, strike
            )))
        } else {
            Ok(matching_positions)
        }
    }

    fn get_position_unique(
        &mut self,
        option_style: &OptionStyle,
        side: &Side,
    ) -> Result<&mut Position, PositionError> {
        let matching_positions: Vec<&mut Position> = self
            .positions
            .iter_mut()
            .filter(|position| {
                position.option.option_style == *option_style && position.option.side == *side
            })
            .collect();

        match matching_positions.len() {
            0 => Err(PositionError::invalid_position(&format!(
                "Position not found: {:?} {:?}",
                option_style, side
            ))),
            1 => matching_positions.into_iter().next().ok_or_else(|| {
                PositionError::invalid_position(
                    "matching_positions length is 1 but iterator yielded none",
                )
            }),
            _ => Err(PositionError::invalid_position(&format!(
                "Multiple positions found: {:?} {:?}",
                option_style, side
            ))),
        }
    }

    fn get_option_unique(
        &mut self,
        option_style: &OptionStyle,
        side: &Side,
    ) -> Result<&mut Options, PositionError> {
        let position = self.get_position_unique(option_style, side)?;
        Ok(&mut position.option)
    }

    fn modify_position(&mut self, position: &Position) -> Result<(), PositionError> {
        let existing_position =
            self.get_position_unique(&position.option.option_style, &position.option.side)?;

        *existing_position = position.clone();

        if !self.validate() {
            return Err(PositionError::invalid_position(
                "Strategy is not valid after modifying position",
            ));
        }

        let _ = self.update_break_even_points();
        Ok(())
    }

    fn replace_position(&mut self, position: &Position) -> Result<(), PositionError> {
        // Find and replace the position with matching criteria
        let index = self
            .positions
            .iter()
            .position(|p| {
                p.option.option_style == position.option.option_style
                    && p.option.side == position.option.side
                    && p.option.strike_price == position.option.strike_price
            })
            .ok_or_else(|| {
                PositionError::invalid_position(&format!(
                    "Position not found: {:?} {:?} strike {}",
                    position.option.option_style,
                    position.option.side,
                    position.option.strike_price
                ))
            })?;

        self.positions[index] = position.clone();

        if !self.validate() {
            return Err(PositionError::invalid_position(
                "Strategy is not valid after replacing position",
            ));
        }

        let _ = self.update_break_even_points();
        Ok(())
    }
}

impl Strategable for CustomStrategy {
    fn info(&self) -> Result<StrategyBasics, StrategyError> {
        Ok(StrategyBasics {
            name: self.name.clone(),
            kind: self.kind.clone(),
            description: self.description.clone(),
        })
    }
}

impl BasicAble for CustomStrategy {
    fn get_title(&self) -> String {
        format!("{} - {} Strategy", self.symbol, self.name)
    }

    fn get_option_basic_type(&self) -> HashSet<OptionBasicType<'_>> {
        let mut types = HashSet::new();
        for position in &self.positions {
            types.insert(OptionBasicType {
                option_style: &position.option.option_style,
                side: &position.option.side,
                strike_price: &position.option.strike_price,
                expiration_date: &position.option.expiration_date,
            });
        }
        types
    }

    fn get_implied_volatility(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        let mut volatilities = HashMap::new();
        for position in &self.positions {
            let basic_type = OptionBasicType {
                option_style: &position.option.option_style,
                side: &position.option.side,
                strike_price: &position.option.strike_price,
                expiration_date: &position.option.expiration_date,
            };
            volatilities.insert(basic_type, &position.option.implied_volatility);
        }
        volatilities
    }

    fn get_quantity(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        let mut quantities = HashMap::new();
        for position in &self.positions {
            let basic_type = OptionBasicType {
                option_style: &position.option.option_style,
                side: &position.option.side,
                strike_price: &position.option.strike_price,
                expiration_date: &position.option.expiration_date,
            };
            quantities.insert(basic_type, &position.option.quantity);
        }
        quantities
    }

    fn one_option(&self) -> &Options {
        &self.positions[0].option
    }

    fn one_option_mut(&mut self) -> &mut Options {
        &mut self.positions[0].option
    }

    fn set_expiration_date(
        &mut self,
        expiration_date: ExpirationDate,
    ) -> Result<(), StrategyError> {
        for position in &mut self.positions {
            position.option.expiration_date = expiration_date;
        }
        Ok(())
    }

    fn set_underlying_price(&mut self, price: &Positive) -> Result<(), StrategyError> {
        self.underlying_price = *price;
        for position in &mut self.positions {
            position.option.underlying_price = *price;
        }
        Ok(())
    }

    fn set_implied_volatility(&mut self, volatility: &Positive) -> Result<(), StrategyError> {
        for position in &mut self.positions {
            position.option.implied_volatility = *volatility;
        }
        Ok(())
    }
}

impl Strategies for CustomStrategy {
    fn get_volume(&mut self) -> Result<Positive, StrategyError> {
        let mut total_volume = Positive::ZERO;
        for position in &self.positions {
            total_volume += position.option.quantity;
        }
        Ok(total_volume)
    }

    fn get_max_profit(&self) -> Result<Positive, StrategyError> {
        if self.positions.is_empty() {
            return Ok(Positive::ZERO);
        }

        let (min_price, max_price) = self.range_to_show()?;
        let step = (max_price - min_price) / pos_lit(dec!(50.0)); // Use 50 steps max
        let mut max_profit = Decimal::ZERO;
        let mut current_price = min_price;

        // Limit iterations to prevent infinite loops
        let max_iterations = 100;
        let mut iterations = 0;

        while current_price <= max_price && iterations < max_iterations {
            if let Ok(current_profit) = self.calculate_profit_at(&current_price)
                && current_profit > max_profit
            {
                max_profit = current_profit;
            }
            current_price += step;
            iterations += 1;
        }

        // If max_profit is still zero or negative, return zero
        if max_profit <= Decimal::ZERO {
            Ok(Positive::ZERO)
        } else {
            Ok(Positive::new_decimal(max_profit)?)
        }
    }

    fn get_max_loss(&self) -> Result<Positive, StrategyError> {
        if self.positions.is_empty() {
            return Ok(Positive::ZERO);
        }

        let (min_price, max_price) = self.range_to_show()?;
        let step = (max_price - min_price) / pos_lit(dec!(50.0)); // Use 50 steps max
        let mut max_loss = Decimal::ZERO;
        let mut current_price = min_price;

        // Limit iterations to prevent infinite loops
        let max_iterations = 100;
        let mut iterations = 0;

        while current_price <= max_price && iterations < max_iterations {
            if let Ok(current_profit) = self.calculate_profit_at(&current_price)
                && current_profit < max_loss
            {
                max_loss = current_profit;
            }
            current_price += step;
            iterations += 1;
        }

        // Return absolute value of max loss
        if max_loss >= Decimal::ZERO {
            Ok(Positive::ZERO)
        } else {
            Ok(Positive::new_decimal(-max_loss)?)
        }
    }

    fn get_profit_area(&self) -> Result<Decimal, StrategyError> {
        if self.positions.is_empty() {
            return Ok(Decimal::ZERO);
        }

        let (min_price, max_price) = self.range_to_show()?;
        let step = (max_price - min_price) / pos_lit(dec!(50.0)); // Use 50 steps max
        let mut total_profit = Decimal::ZERO;
        let mut current_price = min_price;

        // Limit iterations to prevent infinite loops
        let max_iterations = 100;
        let mut iterations = 0;

        while current_price <= max_price && iterations < max_iterations {
            if let Ok(current_profit) = self.calculate_profit_at(&current_price)
                && current_profit > Decimal::ZERO
            {
                total_profit += current_profit;
            }
            current_price += step;
            iterations += 1;
        }

        Ok(total_profit / self.underlying_price.to_dec())
    }

    fn get_profit_ratio(&self) -> Result<Decimal, StrategyError> {
        if self.positions.is_empty() {
            return Ok(Decimal::ZERO);
        }

        let max_profit = self.get_max_profit().unwrap_or(Positive::ZERO);
        let max_loss = self.get_max_loss().unwrap_or(Positive::ZERO);

        if max_loss == Positive::ZERO {
            return Ok(Decimal::ZERO);
        }

        let ratio = (max_profit.to_dec() / max_loss.to_dec()) * Decimal::from(100);
        Ok(ratio)
    }

    fn get_best_range_to_show(&self, step: Positive) -> Result<Vec<Positive>, StrategyError> {
        let (start_price, end_price) = self.range_to_show()?;
        let mut prices = Vec::new();
        let mut current_price = start_price;

        while current_price <= end_price {
            prices.push(current_price);
            current_price += step;
        }

        Ok(prices)
    }

    fn roll_in(&mut self, _position: &Position) -> Result<HashMap<Action, Trade>, StrategyError> {
        // Custom strategy doesn't support rolling operations by default
        Ok(HashMap::new())
    }

    fn roll_out(&mut self, _position: &Position) -> Result<HashMap<Action, Trade>, StrategyError> {
        // Custom strategy doesn't support rolling operations by default
        Ok(HashMap::new())
    }
}

impl Validable for CustomStrategy {
    fn validate(&self) -> bool {
        if self.positions.is_empty() {
            error!("No positions found");
            return false;
        }

        // Validate individual positions
        if !self.positions.iter().all(|position| position.validate()) {
            error!("One or more positions are invalid");
            return false;
        }

        // Max loss point validation is optional during construction
        if let Some(loss) = self.max_loss_point
            && loss.1 >= 0.0
        {
            error!("Max loss point is not valid");
            return false;
        }

        true
    }
}

impl Optimizable for CustomStrategy {
    type Strategy = CustomStrategy;

    fn find_optimal(
        &mut self,
        option_chain: &OptionChain,
        side: FindOptimalSide,
        criteria: OptimizationCriteria,
    ) {
        let positions = self.positions.clone();
        let options: Vec<&OptionData> = option_chain.filter_option_data(side);

        let mut best_value = Decimal::MIN;
        let mut best_positions = positions.clone();

        debug!("Starting optimization with {} positions", positions.len());

        let _result = process_n_times_iter(&options, positions.len(), |combination| {
            let mut current_positions = positions.clone();

            // Update each position with the new data
            for (position, option_data) in current_positions.iter_mut().zip(combination.iter()) {
                // TODO now update_from_option_data is returning a Result
                // consider the opportunity to propagate the error by adding a Result return type
                // also to the find_optimal method.
                let _ = position.update_from_option_data(option_data);
            }

            // check if the positions are valid
            for position in current_positions.iter() {
                if !position.validate() {
                    debug!("Invalid position found");
                    return vec![];
                }
            }

            // Evaluate the current combination
            self.update_positions(current_positions.clone());
            let metric = match criteria {
                OptimizationCriteria::Ratio => self.get_profit_ratio(),
                OptimizationCriteria::Area => self.get_profit_area(),
            };
            let current_value = match metric {
                Ok(v) => v,
                Err(e) => {
                    tracing::warn!(error = %e, "skipping candidate with unscorable metric");
                    return best_positions.clone();
                }
            };

            if current_value > best_value {
                debug!("Found better value: {} > {}", current_value, best_value);
                best_value = current_value;
                best_positions = current_positions.clone();
            }

            best_positions.clone()
        });
        if let Err(e) = _result {
            tracing::warn!(error = ?e, "process_n_times_iter failed during find_optimal");
        }

        if best_value == Decimal::MIN {
            error!("No valid combinations found");
        }

        debug!("Optimization completed. Best value: {}", best_value);
        self.update_positions(best_positions);
    }
}

impl Profit for CustomStrategy {
    fn calculate_profit_at(&self, price: &Positive) -> Result<Decimal, PricingError> {
        let price = Some(price);
        self.positions
            .iter()
            .try_fold(Decimal::ZERO, |acc, position| {
                let pnl = position.pnl_at_expiration(&price)?;
                d_add(acc, pnl, "strategies::custom::profit_at").map_err(PricingError::from)
            })
    }
}

// Graph trait implementation is provided by the impl_graph_for_payoff_strategy! macro in graph.rs

impl ProbabilityAnalysis for CustomStrategy {
    fn get_profit_ranges(&self) -> Result<Vec<ProfitLossRange>, ProbabilityError> {
        let break_even_points = self.get_break_even_points()?;

        let implied_volatilities = self
            .positions
            .iter()
            .map(|position| position.option.implied_volatility)
            .collect();
        let (mean_volatility, std_dev) = mean_and_std(implied_volatilities);

        let (mut profit_ranges, _) = self.get_profit_loss_zones(break_even_points)?;

        let expiration = match self.positions.first() {
            Some(position) => position.option.expiration_date,
            None => return Ok(profit_ranges),
        };
        let risk_free_rate = self
            .positions
            .first()
            .map(|position| position.option.risk_free_rate);

        for range in profit_ranges.iter_mut() {
            range.calculate_probability(
                &self.underlying_price,
                Some(VolatilityAdjustment {
                    base_volatility: mean_volatility,
                    std_dev_adjustment: std_dev,
                }),
                None, // PriceTrend
                &expiration,
                risk_free_rate,
            )?;
        }

        Ok(profit_ranges)
    }

    fn get_loss_ranges(&self) -> Result<Vec<ProfitLossRange>, ProbabilityError> {
        let break_even_points = self.get_break_even_points()?;

        let implied_volatilities = self
            .positions
            .iter()
            .map(|position| position.option.implied_volatility)
            .collect();
        let (mean_volatility, std_dev) = mean_and_std(implied_volatilities);

        let (_, mut loss_ranges) = self.get_profit_loss_zones(break_even_points)?;

        let expiration = match self.positions.first() {
            Some(position) => position.option.expiration_date,
            None => return Ok(loss_ranges),
        };
        let risk_free_rate = self
            .positions
            .first()
            .map(|position| position.option.risk_free_rate);

        for range in loss_ranges.iter_mut() {
            range.calculate_probability(
                &self.underlying_price,
                Some(VolatilityAdjustment {
                    base_volatility: mean_volatility,
                    std_dev_adjustment: std_dev,
                }),
                None, // PriceTrend
                &expiration,
                risk_free_rate,
            )?;
        }

        Ok(loss_ranges)
    }
}

impl Greeks for CustomStrategy {
    fn get_options(&self) -> Result<Vec<&Options>, GreeksError> {
        Ok(self
            .positions
            .iter()
            .map(|position| &position.option)
            .collect())
    }
}

impl DeltaNeutrality for CustomStrategy {}

impl PnLCalculator for CustomStrategy {
    fn calculate_pnl(
        &self,
        market_price: &Positive,
        expiration_date: ExpirationDate,
        implied_volatility: &Positive,
    ) -> Result<PnL, PricingError> {
        let mut total = PnL::default();
        for position in &self.positions {
            total = total
                + position.calculate_pnl(market_price, expiration_date, implied_volatility)?;
        }
        Ok(total)
    }

    fn calculate_pnl_at_expiration(
        &self,
        underlying_price: &Positive,
    ) -> Result<PnL, PricingError> {
        let mut total = PnL::default();
        for position in &self.positions {
            total = total + position.calculate_pnl_at_expiration(underlying_price)?;
        }
        Ok(total)
    }

    fn adjustments_pnl(&self, adjustment: &DeltaAdjustment) -> Result<PnL, PricingError> {
        let mut total_pnl = PnL::default();

        for position in &self.positions {
            let position_pnl = position.adjustments_pnl(adjustment)?;
            total_pnl = total_pnl + position_pnl;
        }

        Ok(total_pnl)
    }
}