optionstratlib 0.16.5

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
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
// Scoped allow: bulk migration of unchecked `[]` indexing to
// `.get().ok_or_else(..)` tracked as follow-ups to #341.
#![allow(clippy::indexing_slicing)]

use crate::chains::OptionData;
use crate::constants::{STRIKE_PRICE_LOWER_BOUND_MULTIPLIER, STRIKE_PRICE_UPPER_BOUND_MULTIPLIER};
use crate::error::strategies::BreakEvenErrorKind;
use crate::{
    ExpirationDate, Options,
    chains::{StrategyLegs, chain::OptionChain, utils::OptionDataGroup},
    error::{OperationErrorKind, position::PositionError, strategies::StrategyError},
    greeks::Greeks,
    model::{
        Trade,
        position::Position,
        types::{Action, OptionBasicType, OptionStyle, OptionType, Side},
    },
    pnl::PnLCalculator,
    pricing::payoff::Profit,
    strategies::{
        StrategyConstructor,
        delta_neutral::DeltaNeutrality,
        probabilities::core::ProbabilityAnalysis,
        utils::{FindOptimalSide, OptimizationCriteria, calculate_price_range},
    },
    visualization::Graph,
};
use positive::Positive;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::str::FromStr;
use tracing::{error, instrument, warn};
use utoipa::ToSchema;

/// Represents basic information about a trading strategy.
///
/// This struct is used to store the name, type, and description of a strategy.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema)]
pub struct StrategyBasics {
    /// The name of the strategy.
    pub name: String,
    /// The type of the strategy.  See the [`StrategyType`] enum for possible values.
    pub kind: StrategyType,
    /// A description of the strategy.
    pub description: String,
}

/// This trait defines common functionalities for all trading strategies.
/// It combines several other traits, requiring implementations for methods related to strategy
/// information, construction, optimization, profit calculation, graphing, probability analysis,
/// Greeks calculation, delta neutrality, and P&L calculation.
pub trait Strategable:
    Strategies
    + StrategyConstructor
    + Profit
    + Graph
    + ProbabilityAnalysis
    + Greeks
    + DeltaNeutrality
    + PnLCalculator
{
    /// Returns basic information about the strategy, such as its name, type, and description.
    ///
    /// This method returns an error by default, as it is expected to be implemented by specific
    /// strategy types.
    /// The error indicates that the `info` operation is not supported for the given strategy type.
    ///
    /// # Returns
    ///
    /// A `Result` containing the `StrategyBasics` struct if successful, or a `StrategyError`
    /// if the operation is not supported.
    ///
    /// # Errors
    ///
    /// The default implementation returns [`StrategyError::OperationError`]
    /// with [`OperationErrorKind::NotSupported`]; concrete strategies that
    /// override it may surface [`StrategyError::PriceError`] or
    /// [`StrategyError::BreakEvenError`] when the underlying computations
    /// fail.
    fn info(&self) -> Result<StrategyBasics, StrategyError> {
        Err(StrategyError::operation_not_supported(
            "info",
            std::any::type_name::<Self>(),
        ))
    }

    /// Returns the type of the strategy.
    ///
    /// This method attempts to retrieve the strategy type from the `info()` method.
    /// If `info()` returns an error (indicating it's not implemented for the specific strategy),
    /// the default falls back to `StrategyType::Custom` and emits a warning.
    ///
    /// # Returns
    ///
    /// The `StrategyType` of the strategy, or `StrategyType::Custom` on lookup
    /// failure.
    fn type_name(&self) -> StrategyType {
        match self.info() {
            Ok(info) => info.kind,
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "type_name: info() failed; defaulting to StrategyType::Custom"
                );
                StrategyType::Custom
            }
        }
    }

    /// Returns the name of the strategy.
    ///
    /// This method attempts to retrieve the strategy name from the `info()` method.
    /// If `info()` returns an error (indicating it's not implemented for the specific strategy),
    /// the default falls back to `"Unknown"` and emits a warning.
    ///
    /// # Returns
    ///
    /// The name of the strategy as a `String`, or `"Unknown"` on lookup failure.
    fn name(&self) -> String {
        match self.info() {
            Ok(info) => info.name,
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "name: info() failed; defaulting to \"Unknown\""
                );
                String::from("Unknown")
            }
        }
    }
}

/// Represents different option trading strategies.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
pub enum StrategyType {
    /// Bull Call Spread strategy.
    BullCallSpread,
    /// Bear Call Spread strategy.
    BearCallSpread,
    /// Bull Put Spread strategy.
    BullPutSpread,
    /// Bear Put Spread strategy.
    BearPutSpread,
    /// Long Butterfly Spread strategy.
    LongButterflySpread,
    /// Short Butterfly Spread strategy.
    ShortButterflySpread,
    /// Iron Condor strategy.
    IronCondor,
    /// Iron Butterfly strategy.
    IronButterfly,
    /// Long Straddle strategy.
    LongStraddle,
    /// Short Straddle strategy.
    ShortStraddle,
    /// Long Strangle strategy.
    LongStrangle,
    /// Short Strangle strategy.
    ShortStrangle,
    /// Covered Call strategy.
    CoveredCall,
    /// Protective Put strategy.
    ProtectivePut,
    /// Collar strategy.
    Collar,
    /// Long Call strategy.
    LongCall,
    /// Long Put strategy.
    LongPut,
    /// Short Call strategy.
    ShortCall,
    /// Short Put strategy.
    ShortPut,
    /// Poor Man's Covered Call strategy.
    PoorMansCoveredCall,
    /// Call Butterfly strategy.
    CallButterfly,
    /// Custom strategy.
    Custom,
}

impl FromStr for StrategyType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "BullCallSpread" => Ok(StrategyType::BullCallSpread),
            "BearCallSpread" => Ok(StrategyType::BearCallSpread),
            "BullPutSpread" => Ok(StrategyType::BullPutSpread),
            "BearPutSpread" => Ok(StrategyType::BearPutSpread),
            "LongButterflySpread" => Ok(StrategyType::LongButterflySpread),
            "ShortButterflySpread" => Ok(StrategyType::ShortButterflySpread),
            "IronCondor" => Ok(StrategyType::IronCondor),
            "IronButterfly" => Ok(StrategyType::IronButterfly),
            "LongStraddle" => Ok(StrategyType::LongStraddle),
            "ShortStraddle" => Ok(StrategyType::ShortStraddle),
            "LongStrangle" => Ok(StrategyType::LongStrangle),
            "ShortStrangle" => Ok(StrategyType::ShortStrangle),
            "CoveredCall" => Ok(StrategyType::CoveredCall),
            "ProtectivePut" => Ok(StrategyType::ProtectivePut),
            "Collar" => Ok(StrategyType::Collar),
            "LongCall" => Ok(StrategyType::LongCall),
            "LongPut" => Ok(StrategyType::LongPut),
            "ShortCall" => Ok(StrategyType::ShortCall),
            "ShortPut" => Ok(StrategyType::ShortPut),
            "PoorMansCoveredCall" => Ok(StrategyType::PoorMansCoveredCall),
            "CallButterfly" => Ok(StrategyType::CallButterfly),
            "Custom" => Ok(StrategyType::Custom),
            _ => Err(()),
        }
    }
}

impl StrategyType {
    /// Checks if a given string is a valid `StrategyType`.
    ///
    /// # Arguments
    ///
    /// * `strategy` - A string slice representing the strategy type.
    ///
    /// # Returns
    ///
    /// `true` if the string is a valid `StrategyType`, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use optionstratlib::strategies::base::StrategyType;
    /// assert!(StrategyType::is_valid("BullCallSpread"));
    /// assert!(!StrategyType::is_valid("InvalidStrategy"));
    /// ```
    #[inline]
    #[must_use]
    pub fn is_valid(strategy: &str) -> bool {
        StrategyType::from_str(strategy).is_ok()
    }
}

impl fmt::Display for StrategyType {
    /// Formats the `StrategyType` for display.
    ///
    /// # Arguments
    ///
    /// * `f` - A mutable formatter.
    ///
    /// # Returns
    ///
    /// A `fmt::Result` indicating whether the formatting was successful.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

/// Represents a complete options trading strategy with risk-reward parameters.
///
/// A strategy encapsulates all the information needed to describe, analyze, and
/// trade a specific options strategy. It includes identifying information, the positions
/// that make up the strategy, and critical risk metrics such as maximum profit/loss
/// and break-even points.
///
/// This structure serves as the foundation for strategy analysis, visualization,
/// and trading execution within the options trading framework.
///
pub struct Strategy {
    /// The name of the strategy, which identifies it among other strategies.
    pub name: String,

    /// The type of the strategy, categorizing it according to standard options strategies.
    pub kind: StrategyType,

    /// A textual description explaining the strategy's purpose, construction, and typical market scenarios.
    pub description: String,

    /// A collection of positions (or legs) that together form the complete strategy.
    /// Each position represents an option contract or underlying asset position.
    pub legs: Vec<Position>,

    /// The maximum potential profit of the strategy, if limited and known.
    /// Expressed as an absolute value, not percentage.
    pub max_profit: Option<f64>,

    /// The maximum potential loss of the strategy, if limited and known.
    /// Expressed as an absolute value, not percentage.
    pub max_loss: Option<f64>,

    /// The price points of the underlying asset at which the strategy neither makes a profit nor a loss.
    /// These points are crucial for strategy planning and risk management.
    pub break_even_points: Vec<Positive>,
}

/// Creates a new `Strategy` instance.
///
/// This function initializes a new trading strategy with the given name, kind, and description.  The `legs`, `max_profit`, `max_loss`, and `break_even_points` are initialized as empty or `None`.
///
/// # Arguments
///
/// * `name` - The name of the strategy.
/// * `kind` - The type of the strategy  (e.g., BullCallSpread, LongStraddle).
/// * `description` - A description of the strategy.
///
/// # Returns
///
/// A new `Strategy` instance.
///
/// # Example
///
/// ```
/// use optionstratlib::strategies::base::{Strategy, StrategyType};
/// let strategy = Strategy::new(
///     "My Strategy".to_string(),
///     StrategyType::LongCall,
///     "A simple long call strategy".to_string(),
/// );
///
/// assert_eq!(strategy.name, "My Strategy");
/// assert_eq!(strategy.kind, StrategyType::LongCall);
/// assert_eq!(strategy.description, "A simple long call strategy");
/// assert!(strategy.legs.is_empty());
/// assert_eq!(strategy.max_profit, None);
/// assert_eq!(strategy.max_loss, None);
/// assert!(strategy.break_even_points.is_empty());
/// ```
impl Strategy {
    /// Creates a new `Strategy` instance.
    ///
    /// This function initializes a new trading strategy with the given name, kind, and description.
    /// The `legs`, `max_profit`, `max_loss`, and `break_even_points` are initialized as empty or `None`.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the strategy.
    /// * `kind` - The type of the strategy (e.g., BullCallSpread, LongStraddle).
    /// * `description` - A description of the strategy.
    ///
    /// # Returns
    ///
    /// A new `Strategy` instance.
    ///
    /// # Example
    ///
    /// ```
    /// use optionstratlib::strategies::base::{Strategy, StrategyType};
    /// let strategy = Strategy::new(
    ///     "My Strategy".to_string(),
    ///     StrategyType::LongCall,
    ///     "A simple long call strategy".to_string(),
    /// );
    ///
    /// assert_eq!(strategy.name, "My Strategy");
    /// assert_eq!(strategy.kind, StrategyType::LongCall);
    /// assert_eq!(strategy.description, "A simple long call strategy");
    /// assert!(strategy.legs.is_empty());
    /// assert_eq!(strategy.max_profit, None);
    /// assert_eq!(strategy.max_loss, None);
    /// assert!(strategy.break_even_points.is_empty());
    /// ```
    #[inline]
    #[must_use]
    pub fn new(name: String, kind: StrategyType, description: String) -> Self {
        Strategy {
            name,
            kind,
            description,
            legs: Vec::new(),
            max_profit: None,
            max_loss: None,
            break_even_points: Vec::new(),
        }
    }
}

/// A trait that defines basic operations and attributes for managing options-related strategies.
///
/// This trait provides methods to retrieve various properties and mappings
/// associated with options, such as title, symbol, strike prices, sides, styles,
/// expiration dates, and implied volatility.
///
/// # Note
/// Most defaults return either an empty value (with a `tracing::warn!` log)
/// or an `Err(...)` describing the unsupported operation. Concrete strategies
/// should override the methods they need.
///
/// # Methods
/// - `get_title`: Returns the title of the strategy.
/// - `get_option_basic_type`: Retrieves a set of basic option types.
/// - `get_symbol`: Returns the symbol associated with the option.
/// - `get_strike`: Maps option basic types to their positive strike values.
/// - `get_strikes`: Returns a vector of strike prices.
/// - `get_side`: Maps option basic types to their respective sides.
/// - `get_type`: Retrieves the type of the option.
/// - `get_style`: Maps option basic types to their corresponding styles.
/// - `get_expiration`: Maps option basic types to their expiration dates.
/// - `get_implied_volatility`: Retrieves implied volatility.
///
/// # Panics
/// Only `one_option` and `one_option_mut` panic on the default implementation,
/// because their reference return types do not allow a graceful fallback.
/// Every strategy that owns `Options` must override both methods.
///
pub trait BasicAble {
    /// Retrieves the title associated with the current instance of the strategy.
    ///
    /// # Returns
    /// A `String` representing the title.
    ///
    /// # Default
    /// The default implementation returns an empty `String` and emits a
    /// `tracing::warn!` log so callers can detect strategies that did not
    /// override this method.
    ///
    fn get_title(&self) -> String {
        warn!(
            "get_title default: {} did not override; returning empty string",
            std::any::type_name::<Self>()
        );
        String::new()
    }
    /// Retrieves a `HashSet` of `OptionBasicType` values associated with the current strategy.
    ///
    /// # Returns
    /// A `HashSet` containing the `OptionBasicType` elements relevant to the strategy.
    ///
    /// # Default
    /// The default implementation returns an empty `HashSet` and emits a
    /// `tracing::warn!` log so callers can detect strategies that did not
    /// override this method.
    ///
    fn get_option_basic_type(&self) -> HashSet<OptionBasicType<'_>> {
        warn!(
            "get_option_basic_type default: {} did not override; returning empty set",
            std::any::type_name::<Self>()
        );
        HashSet::new()
    }
    /// Retrieves the symbol associated with the current instance by delegating the call to the `get_symbol`
    /// method of the `one_option` object.
    ///
    /// # Returns
    /// A string slice (`&str`) that represents the symbol.
    ///
    /// # Notes
    /// - Assumes that `one_option()` is a method that returns an object or reference which implements
    ///   a `get_symbol()` method.
    /// - The returned `&str` is borrowed from the referenced object, and its lifetime is tied to the `self` instance.
    fn get_symbol(&self) -> &str {
        self.one_option().get_symbol()
    }
    /// Retrieves a mapping of option basic types to their associated positive strike values.
    ///
    /// This method delegates the call to the `get_strike` method of the `one_option` object,
    /// returning a `HashMap` where each key is an `OptionBasicType` and each value is a reference
    /// to a `Positive` strike value.
    ///
    /// # Returns
    /// A `HashMap` where:
    /// - `OptionBasicType` represents the type of the option,
    /// - `&Positive` is a reference to the positive strike value associated with the option.
    ///
    /// # Notes
    /// - Ensure that the `one_option` method returns a valid object that implements a `get_strike` method.
    /// - The values in the returned map are references, so their lifetime is tied to the ownership of `self`.
    ///
    fn get_strike(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        self.one_option().get_strike()
    }
    /// Retrieves a vector of strike prices from the option types.
    ///
    /// This function accesses the `OptionBasicType` objects associated with the instance,
    /// extracts their `strike_price` fields, and collects those values into a `Vec<&Positive>`.
    ///
    /// # Returns
    ///
    /// A vector containing references to the strike prices (`&Positive`) of the associated option types.
    ///
    /// # Notes
    ///
    /// - The method assumes that `self.get_option_basic_type()` returns a collection of
    ///   objects that have a `strike_price` field.
    /// - The `strike_price` type is `&Positive`, which implies it references a type with
    ///   positive constraints.
    fn get_strikes(&self) -> Vec<&Positive> {
        self.get_option_basic_type()
            .iter()
            .map(|option_type| option_type.strike_price)
            .collect()
    }
    /// Retrieves a `HashMap` that maps each `OptionBasicType` to its corresponding `Side`.
    ///
    /// This method generates a mapping by iterating over the result of `get_option_basic_type`
    /// and pairing each `OptionBasicType` with its associated `Side`.
    ///
    /// # Returns
    ///
    /// A `HashMap` where:
    /// - The keys are `OptionBasicType` values.
    /// - The values are `Side` references corresponding to each `OptionBasicType`.
    ///
    /// # Panics
    ///
    /// This function assumes that `option_type.side` is valid for all elements
    /// in the iterator returned by `get_option_basic_type`. If this assumption is violated,
    /// the behavior is undefined.
    ///
    /// # Notes
    ///
    /// Ensure that `get_option_basic_type` is properly implemented and returns
    /// an iterable collection of `OptionBasicType` elements that have valid `Side` associations.
    fn get_side(&self) -> HashMap<OptionBasicType<'_>, &Side> {
        self.get_option_basic_type()
            .iter()
            .map(|option_type| (*option_type, option_type.side))
            .collect()
    }
    /// Retrieves the type of the option.
    ///
    /// This method provides access to the `OptionType` of the associated option
    /// by calling the `get_type` method on the result of `self.one_option()`.
    ///
    /// # Returns
    /// A reference to the `OptionType` of the associated option.
    ///
    /// # Notes
    /// - Ensure `self.one_option()` returns a valid object with a callable `get_type`
    ///   method to avoid runtime errors.
    fn get_type(&self) -> &OptionType {
        self.one_option().get_type()
    }
    /// Retrieves a mapping of `OptionBasicType` to their corresponding `OptionStyle`.
    ///
    /// This function generates a `HashMap` where each `OptionBasicType` returned by
    /// the `get_option_basic_type` method is associated with its respective `OptionStyle`.
    ///
    /// # Returns
    /// A `HashMap` where:
    /// - The keys are `OptionBasicType` values (basic option types).
    /// - The values are references to the associated `OptionStyle` for each option type.
    ///
    /// # Note
    /// Ensure that `get_option_basic_type` returns a valid iterator of `OptionBasicType`
    /// items before calling this function, as the result depends on its output.
    ///
    /// # Panics
    /// This function will panic if the `OptionStyle` reference is invalid or not properly
    /// initialized for any `OptionBasicType`.
    fn get_style(&self) -> HashMap<OptionBasicType<'_>, &OptionStyle> {
        self.get_option_basic_type()
            .iter()
            .map(|option_type| (*option_type, option_type.option_style))
            .collect()
    }
    /// Retrieves a map of option basic types to their corresponding expiration dates.
    ///
    /// This method iterates over the collection of option basic types and creates a `HashMap`
    /// where each key is an `OptionBasicType` and the value is a reference to its associated
    /// `ExpirationDate`.
    ///
    /// # Returns
    /// A `HashMap` where:
    /// - The key is of type `OptionBasicType`.
    /// - The value is a reference to the `ExpirationDate` associated with the option basic type.
    ///
    /// # Panics
    /// This method may panic if `expiration_date` is unexpectedly `None` within the option type,
    /// depending on your implementation of `get_option_basic_type`.
    ///
    /// # Notes
    /// - Ensure `self.get_option_basic_type()` returns a valid iterable of `OptionBasicType` instances.
    /// - The lifetime of the returned `ExpirationDate` references is tied to the lifetime of `self`.
    fn get_expiration(&self) -> HashMap<OptionBasicType<'_>, &ExpirationDate> {
        self.get_option_basic_type()
            .iter()
            .map(|option_type| (*option_type, option_type.expiration_date))
            .collect()
    }
    /// Retrieves the implied volatility for the current strategy.
    ///
    /// # Returns
    ///
    /// A `HashMap` where the key is of type `OptionBasicType` and
    /// the value is a reference to a `Positive` value. Each key-value
    /// pair corresponds to the implied volatility associated with a
    /// specific option type.
    ///
    /// # Default
    ///
    /// The default implementation returns an empty `HashMap` and emits a
    /// `tracing::warn!` log so callers can detect strategies that did not
    /// override this method.
    fn get_implied_volatility(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        warn!(
            "get_implied_volatility default: {} did not override; returning empty map",
            std::any::type_name::<Self>()
        );
        HashMap::new()
    }
    /// Retrieves the quantity information associated with the strategy.
    ///
    /// # Returns
    /// A `HashMap` that holds pairs of `OptionBasicType` (the key) and a reference
    /// to a `Positive` value (the value). This map represents the mapping of
    /// option basic types to their respective quantities.
    ///
    /// # Default
    /// The default implementation returns an empty `HashMap` and emits a
    /// `tracing::warn!` log so callers can detect strategies that did not
    /// override this method.
    ///
    /// # Example
    /// The function currently serves as a placeholder and should be implemented
    /// in a specific strategy that defines its behavior.
    fn get_quantity(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        warn!(
            "get_quantity default: {} did not override; returning empty map",
            std::any::type_name::<Self>()
        );
        HashMap::new()
    }
    /// Retrieves the underlying price of the financial instrument (e.g., option).
    ///
    /// This method fetches the underlying price from the associated `one_option`
    /// instance, ensuring that the value is positive.
    ///
    /// # Returns
    ///
    /// A reference to a `Positive` value representing the underlying price.
    ///
    /// # Notes
    ///
    /// This method assumes that the underlying price is always available and valid.
    fn get_underlying_price(&self) -> &Positive {
        self.one_option().get_underlying_price()
    }
    /// Retrieves the risk-free interest rate associated with a given set of options.
    ///
    /// This function retrieves the risk-free rate from a single option
    /// and returns it as a `HashMap`, where the keys correspond to the `OptionBasicType`
    /// and the values are references to the respective `Decimal` values.
    ///
    /// # Returns
    ///
    /// A `HashMap` where:
    /// - The key is of type `OptionBasicType`, representing the unique identifier or type of option.
    /// - The value is a reference (`&Decimal`) to the corresponding risk-free rate.
    ///
    /// # Notes
    ///
    /// - The method relies on the `one_option()` function to retrieve the required data.
    /// - Ensure that the `one_option()` method is implemented correctly to fetch the necessary risk-free rates.
    ///
    /// # Errors
    ///
    /// This function assumes that `one_option` and its underlying functionality
    /// are error-free. Errors, if any, must be handled within `one_option`.
    fn get_risk_free_rate(&self) -> HashMap<OptionBasicType<'_>, &Decimal> {
        self.one_option().get_risk_free_rate()
    }
    /// Retrieves the dividend yield of a financial option.
    ///
    /// This method calls the `get_dividend_yield` function of the associated `one_option()`
    /// method and returns a `HashMap` containing the dividend yield information. The keys
    /// of the map are of type `OptionBasicType`, and the values are references to instances
    /// of `Positive`.
    ///
    /// # Returns
    /// * `HashMap<OptionBasicType<'_>, &Positive>`: A mapping of option basic types to their
    ///   respective positive dividend yield values.
    ///
    /// # Note
    /// Ensure that the associated `one_option()` method is correctly implemented
    /// and provides the desired dividend yield information.
    fn get_dividend_yield(&self) -> HashMap<OptionBasicType<'_>, &Positive> {
        self.one_option().get_dividend_yield()
    }
    /// Retrieves a shared reference to the strategy's primary `Options` value.
    ///
    /// # Returns
    /// * `&Options` - A reference to an `Options` object owned by the strategy.
    ///
    /// # Panics
    /// The default implementation panics because there is no graceful fallback
    /// for a borrowed `&Options` return. Every strategy that owns options
    /// must override this method.
    ///
    /// # Note
    /// This is a placeholder implementation and must be overridden in any
    /// concrete strategy that holds option positions.
    fn one_option(&self) -> &Options {
        // INVARIANT: a `&Options` return type admits no default — we cannot
        // materialise a safe reference out of thin air. Every strategy that
        // owns positions overrides this; the panic fires only when a caller
        // dispatches through the trait default on a type with no options,
        // which is a programmer error.
        panic!(
            "one_option not implemented for this strategy — every strategy with options must override"
        )
    }
    /// Provides a mutable reference to the strategy's primary `Options` value.
    ///
    /// # Panics
    ///
    /// The default implementation panics because there is no graceful fallback
    /// for a borrowed `&mut Options` return. Every strategy that owns options
    /// must override this method.
    ///
    /// # Returns
    ///
    /// A mutable reference to an `Options` instance.
    ///
    fn one_option_mut(&mut self) -> &mut Options {
        // INVARIANT: same rationale as `one_option` — `&mut Options` has no
        // safe default value, so every strategy with positions must override
        // this method. Reaching the panic is a programmer error.
        panic!(
            "one_option_mut not implemented for this strategy — every strategy with options must override"
        )
    }

    /// Sets the expiration date for the strategy.
    ///
    /// # Parameters
    ///
    /// - `_expiration_date`: The expiration date to set for the strategy,
    ///   represented as an `ExpirationDate` object.
    ///
    /// # Returns
    ///
    /// - `Ok(())` if the operation is successful.
    /// - `Err(StrategyError)` if the strategy does not support setting
    ///   expiration dates.
    ///
    /// # Errors
    ///
    /// The default implementation returns
    /// `StrategyError::OperationError(NotSupported { .. })`. Strategies that
    /// support mutating expiration should override this method.
    fn set_expiration_date(
        &mut self,
        _expiration_date: ExpirationDate,
    ) -> Result<(), StrategyError> {
        Err(StrategyError::operation_not_supported(
            "set_expiration_date",
            std::any::type_name::<Self>(),
        ))
    }
    /// Sets the underlying price for this strategy.
    ///
    /// # Parameters
    /// - `_price`: A reference to a `Positive` value representing the new underlying price
    ///   to be set.
    ///
    /// # Returns
    /// - `Ok(())` if the operation is successful.
    /// - `Err(StrategyError)` if the strategy does not support setting the
    ///   underlying price.
    ///
    /// # Errors
    /// The default implementation returns
    /// `StrategyError::OperationError(NotSupported { .. })`. Strategies that
    /// support mutating the underlying price should override this method.
    ///
    fn set_underlying_price(&mut self, _price: &Positive) -> Result<(), StrategyError> {
        Err(StrategyError::operation_not_supported(
            "set_underlying_price",
            std::any::type_name::<Self>(),
        ))
    }
    /// Updates the volatility for the strategy.
    ///
    /// # Parameters
    /// - `_volatility`: A reference to a `Positive` value representing the new volatility to set.
    ///
    /// # Returns
    /// - `Ok(())`: If the update operation succeeds.
    /// - `Err(StrategyError)`: If the strategy does not support setting the
    ///   implied volatility.
    ///
    /// # Errors
    /// The default implementation returns
    /// `StrategyError::OperationError(NotSupported { .. })`. Strategies that
    /// support mutating implied volatility should override this method.
    ///
    fn set_implied_volatility(&mut self, _volatility: &Positive) -> Result<(), StrategyError> {
        Err(StrategyError::operation_not_supported(
            "set_implied_volatility",
            std::any::type_name::<Self>(),
        ))
    }
}

/// Defines a set of strategies for options trading.  Provides methods for calculating key metrics
/// such as profit/loss, cost, break-even points, and price ranges.  Implementations of this trait
/// must also implement the `Validable`, `Positionable`, and `BreakEvenable` traits.
pub trait Strategies: Validable + Positionable + BreakEvenable + BasicAble {
    /// Retrieves the current volume of the strategy as sum of quantities in their positions
    ///
    /// This function returns the volume as a `Positive` value, ensuring that the result
    /// is always greater than zero. If the method fails to retrieve the volume, an error
    /// of type `StrategyError` is returned.
    ///
    /// # Returns
    ///
    /// - `Ok(Positive)` - The current volume as a positive numeric value.
    /// - `Err(StrategyError)` - An error indicating why the volume could not be retrieved.
    ///
    /// # Errors
    ///
    /// This function may return a `StrategyError` in cases such as:
    /// - Internal issues within the strategy's calculation or storage.
    /// - Other implementation-specific failures.
    ///
    fn get_volume(&mut self) -> Result<Positive, StrategyError> {
        let quantities = self.get_quantity();
        let mut volume = Positive::ZERO;
        for (_, quantity) in quantities {
            volume += *quantity;
        }
        Ok(volume)
    }

    /// Calculates the maximum possible profit for the strategy.
    /// The default implementation returns an error indicating that the operation is not supported.
    ///
    /// # Returns
    /// * `Ok(Positive)` - The maximum possible profit.
    /// * `Err(StrategyError)` - If the operation is not supported for this strategy.
    ///
    /// # Errors
    ///
    /// The default implementation returns [`StrategyError::OperationError`]
    /// with [`OperationErrorKind::NotSupported`]. Concrete strategies may
    /// surface [`StrategyError::PriceError`] or
    /// [`StrategyError::ProfitLossError`] when the payoff evaluation fails.
    fn get_max_profit(&self) -> Result<Positive, StrategyError> {
        Err(StrategyError::operation_not_supported(
            "max_profit",
            std::any::type_name::<Self>(),
        ))
    }

    /// Calculates the maximum possible profit for the strategy, potentially using an iterative approach.
    /// Defaults to calling `max_profit`.
    ///
    /// # Returns
    /// * `Ok(Positive)` - The maximum possible profit.
    /// * `Err(StrategyError)` - If the operation is not supported for this strategy.
    ///
    /// # Errors
    ///
    /// Propagates any [`StrategyError`] returned by
    /// `Strategable::get_max_profit` on `&self`.
    fn get_max_profit_mut(&mut self) -> Result<Positive, StrategyError> {
        self.get_max_profit()
    }

    /// Calculates the maximum possible loss for the strategy.
    /// The default implementation returns an error indicating that the operation is not supported.
    ///
    /// # Returns
    /// * `Ok(Positive)` - The maximum possible loss.
    /// * `Err(StrategyError)` - If the operation is not supported for this strategy.
    ///
    /// # Errors
    ///
    /// The default implementation returns [`StrategyError::OperationError`]
    /// with [`OperationErrorKind::NotSupported`]. Concrete strategies may
    /// surface [`StrategyError::PriceError`] or
    /// [`StrategyError::ProfitLossError`] when the payoff evaluation fails.
    fn get_max_loss(&self) -> Result<Positive, StrategyError> {
        Err(StrategyError::operation_not_supported(
            "max_loss",
            std::any::type_name::<Self>(),
        ))
    }

    /// Calculates the maximum possible loss for the strategy, potentially using an iterative approach.
    /// Defaults to calling `max_loss`.
    ///
    /// # Returns
    /// * `Ok(Positive)` - The maximum possible loss.
    /// * `Err(StrategyError)` - If the operation is not supported for this strategy.
    ///
    /// # Errors
    ///
    /// Propagates any [`StrategyError`] returned by
    /// `Strategable::get_max_loss` on `&self`.
    fn get_max_loss_mut(&mut self) -> Result<Positive, StrategyError> {
        self.get_max_loss()
    }

    /// Calculates the total cost of the strategy, which is the sum of the absolute cost of all positions.
    ///
    /// # Returns
    /// * `Ok(Positive)` - The total cost of the strategy.
    /// * `Err(PositionError)` - If there is an error retrieving the positions.
    ///
    /// # Errors
    ///
    /// Propagates any [`PositionError`] returned by
    /// `Strategable::get_positions` or by
    /// [`Position::total_cost`] when the component legs surface invalid
    /// state.
    fn get_total_cost(&self) -> Result<Positive, PositionError> {
        let positions = self.get_positions()?;
        let mut total = Positive::ZERO;
        for p in positions {
            total += p.total_cost()?;
        }
        Ok(total)
    }

    /// Calculates the net cost of the strategy, which is the sum of the costs of all positions,
    /// considering premiums paid and received.
    ///
    /// # Returns
    /// * `Ok(Decimal)` - The net cost of the strategy.
    /// * `Err(PositionError)` - If there is an error retrieving the positions.
    ///
    /// # Errors
    ///
    /// Propagates any [`PositionError`] returned by
    /// `Strategable::get_positions` or by
    /// [`Position::net_cost`] when the component legs surface invalid
    /// state.
    fn get_net_cost(&self) -> Result<Decimal, PositionError> {
        let positions = self.get_positions()?;
        let mut total = Decimal::ZERO;
        for p in positions {
            total += p.net_cost()?;
        }
        Ok(total)
    }

    /// Calculates the net premium received for the strategy. This is the total premium received from short positions
    /// minus the total premium paid for long positions. If the result is negative, it returns zero.
    ///
    /// # Returns
    /// * `Ok(Positive)` - The net premium received.
    /// * `Err(StrategyError)` - If there is an error retrieving the positions.
    ///
    /// # Errors
    ///
    /// Returns `StrategyError::from(PositionError)` when
    /// `Strategable::get_positions` or
    /// [`Position::net_premium_received`] fail on any leg.
    fn get_net_premium_received(&self) -> Result<Positive, StrategyError> {
        let positions = self.get_positions()?;
        let mut costs = Decimal::ZERO;
        let mut premiums = Positive::ZERO;
        for p in positions {
            if p.option.side == Side::Long {
                costs += p.net_cost()?;
            } else if p.option.side == Side::Short {
                premiums += p.net_premium_received()?;
            }
        }
        match premiums > costs {
            true => Ok(premiums - costs),
            false => Ok(Positive::ZERO),
        }
    }

    /// Calculates the total fees for the strategy by summing the fees of all positions.
    ///
    /// # Returns
    /// * `Ok(Positive)` - The total fees.
    /// * `Err(StrategyError)` - If there is an error retrieving positions or calculating fees.
    ///
    /// # Errors
    ///
    /// Returns `StrategyError::from(PositionError)` when
    /// `Strategable::get_positions` or [`Position::fees`] fail on any
    /// leg.
    fn get_fees(&self) -> Result<Positive, StrategyError> {
        let mut fee = Positive::ZERO;
        let positions = match self.get_positions() {
            Ok(positions) => positions,
            Err(err) => {
                return Err(StrategyError::OperationError(
                    OperationErrorKind::InvalidParameters {
                        operation: "get_positions".to_string(),
                        reason: err.to_string(),
                    },
                ));
            }
        };
        for position in positions {
            fee += position.fees()?;
        }
        Ok(fee)
    }

    /// Calculates the profit area for the strategy. The default implementation returns an error
    /// indicating that the operation is not supported.
    ///
    /// # Returns
    /// * `Ok(Decimal)` - The profit area.
    /// * `Err(StrategyError)` - If the operation is not supported.
    ///
    /// # Errors
    ///
    /// The default implementation returns [`StrategyError::OperationError`]
    /// with [`OperationErrorKind::NotSupported`]. Overriding strategies may
    /// surface [`StrategyError::BreakEvenError`] or
    /// [`StrategyError::PriceError`] when the payoff integral fails.
    fn get_profit_area(&self) -> Result<Decimal, StrategyError> {
        Err(StrategyError::operation_not_supported(
            "profit_area",
            std::any::type_name::<Self>(),
        ))
    }

    /// Calculates the profit ratio for the strategy. The default implementation returns an error
    /// indicating that the operation is not supported.
    ///
    /// # Returns
    /// * `Ok(Decimal)` - The profit ratio.
    /// * `Err(StrategyError)` - If the operation is not supported.
    ///
    /// # Errors
    ///
    /// The default implementation returns [`StrategyError::OperationError`]
    /// with [`OperationErrorKind::NotSupported`]. Overriding strategies may
    /// surface [`StrategyError::ProfitLossError`] when either
    /// `get_max_profit` or `get_max_loss` fails.
    fn get_profit_ratio(&self) -> Result<Decimal, StrategyError> {
        Err(StrategyError::operation_not_supported(
            "profit_ratio",
            std::any::type_name::<Self>(),
        ))
    }

    /// Determines the price range to display for the strategy's profit/loss graph.  This range is
    /// calculated based on the break-even points, the underlying price, and the maximum and minimum
    /// strike prices.  The range is expanded by applying `STRIKE_PRICE_LOWER_BOUND_MULTIPLIER` and
    /// `STRIKE_PRICE_UPPER_BOUND_MULTIPLIER` to the minimum and maximum prices respectively.
    ///
    /// # Returns
    /// * `Ok((Positive, Positive))` - A tuple containing the start and end prices of the range.
    /// * `Err(StrategyError)` - If there is an error retrieving necessary data for the calculation.
    ///
    /// # Errors
    ///
    /// Propagates any [`StrategyError`] returned by
    /// `Strategable::get_break_even_points` or
    /// `Strategable::get_max_min_strikes`.
    fn get_range_to_show(&self) -> Result<(Positive, Positive), StrategyError> {
        let mut all_points = self.get_break_even_points()?.clone();
        let (first_strike, last_strike) = self.get_max_min_strikes()?;
        let underlying_price = self.get_underlying_price();

        // Calculate the largest difference from the underlying price to furthest strike
        let max_diff = (last_strike.value() - underlying_price.value())
            .abs()
            .max((first_strike.value() - underlying_price.value()).abs());

        // Expand range by max_diff
        all_points.push(
            (*underlying_price - max_diff)
                .max(Positive::ZERO)
                .min(first_strike),
        );
        all_points.push((*underlying_price + max_diff).max(last_strike));

        // Sort to find min and max
        // SAFETY: total order on Positive; f64 fallback to Equal is safe for stable sort
        all_points.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let first = all_points.first().ok_or_else(|| {
            StrategyError::empty_collection("get_range_to_show: all_points is empty")
        })?;
        let last = all_points.last().ok_or_else(|| {
            StrategyError::empty_collection("get_range_to_show: all_points is empty")
        })?;
        let start_price = *first * STRIKE_PRICE_LOWER_BOUND_MULTIPLIER;
        let end_price = *last * STRIKE_PRICE_UPPER_BOUND_MULTIPLIER;
        Ok((start_price, end_price))
    }

    /// Generates a vector of prices within the display range, using a specified step.
    ///
    /// # Returns
    /// * `Ok(Vec<Positive>)` - A vector of prices.
    /// * `Err(StrategyError)` - If there is an error calculating the display range.
    ///
    /// # Errors
    ///
    /// Propagates any [`StrategyError`] returned by
    /// `Strategable::get_range_to_show`.
    fn get_best_range_to_show(&self, step: Positive) -> Result<Vec<Positive>, StrategyError> {
        let (start_price, end_price) = self.get_range_to_show()?;
        Ok(calculate_price_range(start_price, end_price, step))
    }

    /// Returns the minimum and maximum strike prices from the positions in the strategy.
    /// Considers underlying price when applicable, ensuring the returned range includes it.
    ///
    /// # Returns
    /// * `Ok((Positive, Positive))` - A tuple containing the minimum and maximum strike prices.
    /// * `Err(StrategyError)` - If no strikes are found or if an error occurs retrieving positions.
    ///
    /// # Errors
    ///
    /// Returns [`StrategyError::PriceError`] when the strategy has no
    /// strikes to compare against; propagates [`StrategyError`] variants
    /// from `Strategable::get_positions` when position enumeration fails.
    fn get_max_min_strikes(&self) -> Result<(Positive, Positive), StrategyError> {
        let strikes: Vec<&Positive> = self.get_strikes();
        if strikes.is_empty() {
            return Err(StrategyError::OperationError(
                OperationErrorKind::InvalidParameters {
                    operation: "max_min_strikes".to_string(),
                    reason: "No strikes found".to_string(),
                },
            ));
        }

        let min = strikes.iter().fold(Positive::INFINITY, |acc, &strike| {
            Positive::min(acc, *strike)
        });
        let max = strikes
            .iter()
            .fold(Positive::ZERO, |acc, &strike| Positive::max(acc, *strike));

        let underlying_price = self.get_underlying_price();
        let mut min_value = min;
        let mut max_value = max;

        if underlying_price != &Positive::ZERO {
            if min_value > *underlying_price {
                min_value = *underlying_price;
            }
            if *underlying_price > max_value {
                max_value = *underlying_price;
            }
        }

        Ok((min_value, max_value))
    }

    /// Calculates the range of prices where the strategy is profitable, based on the break-even points.
    ///
    /// # Returns:
    /// * `Ok(Positive)` - The difference between the highest and lowest break-even points.  Returns
    ///   `Positive::INFINITY` if there is only one break-even point.
    /// * `Err(StrategyError)` - if there are no break-even points.
    ///
    /// # Errors
    ///
    /// Returns [`StrategyError::BreakEvenError`] when the strategy has
    /// no break-even points, and propagates any other [`StrategyError`]
    /// surfaced by `Strategable::get_break_even_points`.
    fn get_range_of_profit(&self) -> Result<Positive, StrategyError> {
        let mut break_even_points = self.get_break_even_points()?.clone();
        match break_even_points.len() {
            0 => Err(StrategyError::BreakEvenError(
                BreakEvenErrorKind::NoBreakEvenPoints,
            )),
            1 => Ok(Positive::INFINITY),
            2 => Ok(break_even_points[1] - break_even_points[0]),
            _ => {
                // sort break even points and then get last minus first
                // SAFETY: total order on Positive; f64 fallback to Equal is safe for stable sort
                break_even_points
                    .sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
                let last = break_even_points.last().ok_or_else(|| {
                    StrategyError::empty_collection(
                        "get_range_of_profit: break_even_points is empty",
                    )
                })?;
                let first = break_even_points.first().ok_or_else(|| {
                    StrategyError::empty_collection(
                        "get_range_of_profit: break_even_points is empty",
                    )
                })?;
                Ok(*last - *first)
            }
        }
    }

    /// Attempts to execute the roll-in functionality for the strategy.
    ///
    /// # Parameters
    /// - `&mut self`: A mutable reference to the current instance of the strategy.
    /// - `_position: &Position`: A reference to the `Position` object, representing the current position
    ///   in the market. This parameter is currently unused by the default implementation.
    ///
    /// # Returns
    /// - `Result<HashMap<Action, Trade>, StrategyError>`:
    ///   - `Ok(HashMap<Action, Trade>)`: On success, a map of actions to trades, representing the changes
    ///     made during the roll-in process.
    ///   - `Err(StrategyError)`: If the strategy does not support rolling in.
    ///
    /// # Errors
    /// The default implementation returns
    /// `StrategyError::OperationError(NotSupported { .. })`. Strategies that
    /// support roll-in should override this method.
    fn roll_in(&mut self, _position: &Position) -> Result<HashMap<Action, Trade>, StrategyError> {
        Err(StrategyError::operation_not_supported(
            "roll_in",
            std::any::type_name::<Self>(),
        ))
    }

    /// Executes the roll-out strategy for the provided position.
    ///
    /// # Arguments
    ///
    /// * `_position` - A reference to a `Position` object which represents the
    ///   current state of a trading position.
    ///
    /// # Returns
    ///
    /// * `Result<HashMap<Action, Trade>, StrategyError>` - A `Result` object
    ///   containing:
    ///   - `Ok(HashMap<Action, Trade>)` with the mapping of actions to trades.
    ///   - `Err(StrategyError)` if the strategy does not support rolling out.
    ///
    /// # Errors
    ///
    /// The default implementation returns
    /// `StrategyError::OperationError(NotSupported { .. })`. Strategies that
    /// support roll-out should override this method.
    fn roll_out(&mut self, _position: &Position) -> Result<HashMap<Action, Trade>, StrategyError> {
        Err(StrategyError::operation_not_supported(
            "roll_out",
            std::any::type_name::<Self>(),
        ))
    }
}

/// Trait for strategies that can calculate and update break-even points.
///
/// This trait provides methods for retrieving and updating break-even points, which are
/// crucial for determining profitability in various trading scenarios.
pub trait BreakEvenable {
    /// Retrieves the break-even points for the strategy.
    ///
    /// Returns a `Result` containing a reference to a vector of `Positive` values representing
    /// the break-even points, or a `StrategyError` if the operation is not supported for the specific strategy.
    ///
    /// The default implementation returns a `StrategyError::OperationError` with `OperationErrorKind::NotSupported`.
    /// Strategies implementing this trait should override this method if they support break-even point calculations.
    ///
    /// # Errors
    ///
    /// The default implementation returns [`StrategyError::OperationError`]
    /// with [`OperationErrorKind::NotSupported`]. Concrete strategies may
    /// surface [`StrategyError::BreakEvenError`] when no crossing is
    /// found in the payoff profile.
    fn get_break_even_points(&self) -> Result<&Vec<Positive>, StrategyError> {
        Err(StrategyError::operation_not_supported(
            "get_break_even_points",
            std::any::type_name::<Self>(),
        ))
    }

    /// Updates the break-even points for the strategy.
    ///
    /// This method is responsible for recalculating and updating the break-even points based on
    /// the current state of the strategy.
    ///
    /// # Errors
    /// The default implementation returns
    /// `StrategyError::OperationError(NotSupported { .. })`. Strategies
    /// implementing this trait should override this method to provide
    /// specific update logic.
    fn update_break_even_points(&mut self) -> Result<(), StrategyError> {
        Err(StrategyError::operation_not_supported(
            "update_break_even_points",
            std::any::type_name::<Self>(),
        ))
    }
}

/// This trait defines a way to validate a strategy.
///
/// The default implementation panics with a message indicating that validation
/// is not applicable for the specific strategy.  Implementors of this trait
/// should override the `validate` method to provide specific validation logic.
pub trait Validable {
    /// Validates the strategy.
    ///
    /// The default implementation is a safe no-op: it emits a warning and
    /// returns `false` so callers treat an unoverridden strategy as invalid.
    /// Implementors should override this method to provide appropriate
    /// validation logic.
    ///
    /// Returns `true` if the strategy is valid, and `false` otherwise.
    fn validate(&self) -> bool {
        tracing::warn!(
            ty = std::any::type_name::<Self>(),
            "Validable::validate default implementation invoked; treating strategy as invalid"
        );
        false
    }
}

/// This trait defines methods for optimizing and validating option strategies.
/// It combines the `Validable` and `Strategies` traits, requiring implementors
/// to provide functionality for both validation and strategy generation.
pub trait Optimizable: Validable + Strategies {
    /// The type of strategy associated with this optimization.
    type Strategy: Strategies;

    /// Finds the best ratio-based strategy within the given `OptionChain`.
    ///
    /// # Arguments
    /// * `option_chain` - A reference to the `OptionChain` containing option data.
    /// * `side` - A `FindOptimalSide` value specifying the filtering strategy.
    #[instrument(skip(self, option_chain), fields(side = ?side, criteria = "Ratio"))]
    fn get_best_ratio(&mut self, option_chain: &OptionChain, side: FindOptimalSide) {
        self.find_optimal(option_chain, side, OptimizationCriteria::Ratio);
    }

    /// Finds the best area-based strategy within the given `OptionChain`.
    ///
    /// # Arguments
    /// * `option_chain` - A reference to the `OptionChain` containing option data.
    /// * `side` - A `FindOptimalSide` value specifying the filtering strategy.
    #[instrument(skip(self, option_chain), fields(side = ?side, criteria = "Area"))]
    fn get_best_area(&mut self, option_chain: &OptionChain, side: FindOptimalSide) {
        self.find_optimal(option_chain, side, OptimizationCriteria::Area);
    }

    /// Filters and generates combinations of options data from the given `OptionChain`.
    ///
    /// # Parameters
    /// - `&self`: A reference to the current object/context that holds the filtering logic or required data.
    /// - `_option_chain`: A reference to an `OptionChain` object that contains relevant financial information
    ///   such as options data, underlying price, and expiration date.
    /// - `_side`: A `FindOptimalSide` value that specifies the filtering strategy for finding combinations of
    ///   options. It can specify:
    ///     - `Upper`: Consider options higher than a certain threshold.
    ///     - `Lower`: Consider options lower than a certain threshold.
    ///     - `All`: Include all options.
    ///     - `Range(start, end)`: Consider options within a specified range.
    ///
    /// # Returns
    /// - An iterator that yields `OptionDataGroup` items. These items represent combinations of options data filtered
    ///   based on the given criteria. The `OptionDataGroup` can represent combinations of 2, 3, 4, or any number
    ///   of options depending on the grouping logic.
    ///
    /// **Note**:
    /// - The current implementation returns an empty iterator (`std::iter::empty()`) as a placeholder.
    /// - You may modify this method to implement the actual filtering and combination logic based on the
    ///   provided `OptionChain` and `FindOptimalSide` criteria.
    ///
    /// # See Also
    /// - `FindOptimalSide` for the strategy enumeration.
    /// - `OptionDataGroup` for the structure of grouped combinations.
    /// - `OptionChain` for the full structure being processed.
    fn filter_combinations<'a>(
        &'a self,
        _option_chain: &'a OptionChain,
        _side: FindOptimalSide,
    ) -> impl Iterator<Item = OptionDataGroup<'a>> {
        error!("Filter combinations is not applicable for this strategy");
        std::iter::empty()
    }

    /// Finds the optimal strategy based on the given criteria.
    /// The default implementation is a safe no-op: it emits a warning and
    /// leaves `self` unchanged. Specific strategies should override this
    /// method to provide their own optimization logic.
    ///
    /// # Arguments
    /// * `_option_chain` - A reference to the `OptionChain` containing option data.
    /// * `_side` - A `FindOptimalSide` value specifying the filtering strategy.
    /// * `_criteria` - An `OptimizationCriteria` value indicating the optimization goal (e.g., ratio, area).
    fn find_optimal(
        &mut self,
        _option_chain: &OptionChain,
        _side: FindOptimalSide,
        _criteria: OptimizationCriteria,
    ) {
        tracing::warn!(
            ty = std::any::type_name::<Self>(),
            "find_optimal default implementation invoked; strategy left unchanged"
        );
    }

    /// Checks if a long option is valid based on the given criteria.
    ///
    /// # Arguments
    /// * `option` - A reference to the `OptionData` to validate.
    /// * `side` - A reference to the `FindOptimalSide` specifying the filtering strategy.
    fn is_valid_optimal_option(&self, option: &OptionData, side: &FindOptimalSide) -> bool {
        match side {
            FindOptimalSide::Upper => option.strike_price >= *self.get_underlying_price(),
            FindOptimalSide::Lower => option.strike_price <= *self.get_underlying_price(),
            FindOptimalSide::All => true,
            FindOptimalSide::Range(start, end) => {
                option.strike_price >= *start && option.strike_price <= *end
            }
            FindOptimalSide::Deltable(_threshold) => true,
            FindOptimalSide::Center => {
                // `Center` is a sentinel the concrete strategy is expected to
                // intercept (it needs contextual state like the ATM strike to
                // expand into a concrete side). The default trait impl has no
                // such state: log and skip this candidate rather than panic.
                tracing::warn!(
                    "is_valid_optimal_option: FindOptimalSide::Center must be resolved by the concrete strategy; skipping option"
                );
                false
            }
            FindOptimalSide::DeltaRange(min, max) => {
                let (delta_call, delta_put) = option.current_deltas();
                let put_in = delta_put.is_some_and(|d| d >= *min && d <= *max);
                let call_in = delta_call.is_some_and(|d| d >= *min && d <= *max);
                put_in || call_in
            }
        }
    }

    /// Checks if the prices in the given `StrategyLegs` are valid.
    /// Assumes the strategy consists of one long call and one short call by default.
    ///
    /// # Arguments
    /// * `legs` - A reference to the `StrategyLegs` containing the option data.
    fn are_valid_legs(&self, legs: &StrategyLegs) -> bool {
        // by default, we assume Options are one long call and one short call
        let (long, short) = match legs {
            StrategyLegs::TwoLegs { first, second } => (first, second),
            other => {
                tracing::warn!(
                    legs = ?other,
                    "are_valid_legs: default impl expects TwoLegs"
                );
                return false;
            }
        };
        long.call_ask.unwrap_or(Positive::ZERO) > Positive::ZERO
            && short.call_bid.unwrap_or(Positive::ZERO) > Positive::ZERO
    }

    /// Creates a new strategy from the given `OptionChain` and `StrategyLegs`.
    ///
    /// Specific strategies must override this method. The default implementation
    /// returns `StrategyError::OperationError(NotSupported { .. })`.
    ///
    /// # Arguments
    /// * `_chain` - A reference to the `OptionChain` providing option data.
    /// * `_legs` - A reference to the `StrategyLegs` defining the strategy's components.
    ///
    /// # Errors
    ///
    /// Returns `StrategyError::OperationError` if the strategy cannot be built
    /// from the supplied legs (e.g., missing bid/ask quotes, invalid leg
    /// combination, or operation not supported by the concrete strategy).
    fn create_strategy(
        &self,
        _chain: &OptionChain,
        _legs: &StrategyLegs,
    ) -> Result<Self::Strategy, StrategyError> {
        Err(StrategyError::operation_not_supported(
            "create_strategy",
            std::any::type_name::<Self>(),
        ))
    }
}

/// The `Positionable` trait defines methods for managing positions within a trading strategy.
/// These methods allow for adding, retrieving, and modifying positions, providing a common
/// interface for different strategies to interact with position data.
pub trait Positionable {
    /// Adds a position to the strategy.
    ///
    /// # Arguments
    ///
    /// * `_position` - A reference to the `Position` to be added.
    ///
    /// # Returns
    ///
    /// * `Result<(), PositionError>` - Returns `Ok(())` if the position was successfully added,
    ///   or a `PositionError` if the operation is not supported by the strategy.
    ///
    /// # Default Implementation
    ///
    /// The default implementation returns an error indicating that adding a position is not
    /// supported. Strategies that support adding positions should override this method.
    ///
    /// # Errors
    ///
    /// The default implementation returns
    /// [`PositionError::unsupported_operation`]. Overriding strategies may
    /// surface [`PositionError::ValidationError`] when the added position
    /// violates strategy invariants (e.g. mismatched underlying, wrong
    /// side or invalid quantity).
    fn add_position(&mut self, _position: &Position) -> Result<(), PositionError> {
        Err(PositionError::unsupported_operation(
            std::any::type_name::<Self>(),
            "add_position",
        ))
    }

    /// Retrieves all positions held by the strategy.
    ///
    /// # Returns
    ///
    /// * `Result<Vec<&Position>, PositionError>` - A `Result` containing a vector of references to
    ///   the `Position` objects held by the strategy, or a `PositionError` if the operation is
    ///   not supported.
    ///
    /// # Default Implementation
    ///
    /// The default implementation returns an error indicating that getting positions is not
    /// supported. Strategies that manage positions should override this method.
    ///
    /// # Errors
    ///
    /// The default implementation returns
    /// [`PositionError::unsupported_operation`]. Overriding strategies
    /// typically do not fail, but may surface
    /// [`PositionError::ValidationError`] if the internal layout has been
    /// corrupted.
    fn get_positions(&self) -> Result<Vec<&Position>, PositionError> {
        Err(PositionError::unsupported_operation(
            std::any::type_name::<Self>(),
            "get_positions",
        ))
    }

    /// Retrieves a specific position based on option style, side, and strike.
    ///
    /// # Arguments
    ///
    /// * `_option_style` - The style of the option (Call or Put).
    /// * `_side` - The side of the position (Long or Short).
    /// * `_strike` - The strike price of the option.
    ///
    /// # Returns
    ///
    /// * `Result<Vec<&mut Position>, PositionError>` - A `Result` containing a vector of mutable
    ///   references to the matching `Position` objects, or a `PositionError` if the operation is not supported.
    ///
    /// # Errors
    /// The default implementation returns
    /// `PositionError::unsupported_operation(..)`. Strategies that manage
    /// positions should override this method.
    fn get_position(
        &mut self,
        _option_style: &OptionStyle,
        _side: &Side,
        _strike: &Positive,
    ) -> Result<Vec<&mut Position>, PositionError> {
        Err(PositionError::unsupported_operation(
            std::any::type_name::<Self>(),
            "get_position",
        ))
    }

    /// Retrieves a unique position based on the given option style and side.
    ///
    /// # Parameters
    /// - `_option_style`: A reference to an `OptionStyle` which defines the style of the options (e.g., American, European).
    /// - `_side`: A reference to a `Side` which specifies whether the position is on the buy or sell side.
    ///
    /// # Returns
    /// A mutable reference to the `Position` if found. If the position could not be determined or does not exist,
    /// returns a `PositionError`.
    ///
    /// # Errors
    /// The default implementation returns
    /// `PositionError::unsupported_operation(..)`. Strategies that expose a
    /// unique position per (style, side) pair should override this method.
    ///
    fn get_position_unique(
        &mut self,
        _option_style: &OptionStyle,
        _side: &Side,
    ) -> Result<&mut Position, PositionError> {
        Err(PositionError::unsupported_operation(
            std::any::type_name::<Self>(),
            "get_position_unique",
        ))
    }

    /// Retrieves a unique option based on the given style and side.
    ///
    /// # Parameters
    /// - `_option_style`: A reference to an `OptionStyle` that specifies the style
    ///   of the option to retrieve (e.g., American, European).
    /// - `_side`: A reference to a `Side` that indicates the side of the option, such
    ///   as a call or put.
    ///
    /// # Returns
    /// - `Result<&mut Options, PositionError>`:
    ///     - On success, a mutable reference to an `Options` object.
    ///     - On failure, a `PositionError`.
    ///
    /// # Errors
    /// The default implementation returns
    /// `PositionError::unsupported_operation(..)`. Strategies that expose a
    /// unique option per (style, side) pair should override this method.
    ///
    fn get_option_unique(
        &mut self,
        _option_style: &OptionStyle,
        _side: &Side,
    ) -> Result<&mut Options, PositionError> {
        Err(PositionError::unsupported_operation(
            std::any::type_name::<Self>(),
            "get_option_unique",
        ))
    }

    /// Modifies an existing position.
    ///
    /// # Arguments
    ///
    /// * `_position` - A reference to the `Position` to be modified.
    ///
    /// # Returns
    ///
    /// * `Result<(), PositionError>` - A `Result` indicating success or failure of the
    ///   modification, or a `PositionError` if the operation is not supported.
    ///
    /// # Errors
    /// The default implementation returns
    /// `PositionError::unsupported_operation(..)`. Strategies that allow
    /// in-place modification of positions should override this method.
    fn modify_position(&mut self, _position: &Position) -> Result<(), PositionError> {
        Err(PositionError::unsupported_operation(
            std::any::type_name::<Self>(),
            "modify_position",
        ))
    }

    ///
    /// Attempts to replace the current position with a new position.
    ///
    /// # Parameters
    /// - `_position`: A reference to a `Position` object that represents the new position to replace the current one.
    ///
    /// # Returns
    /// - `Ok(())`: If the position replacement is successful.
    /// - `Err(PositionError)`: If an error occurs while replacing the position.
    ///
    /// # Errors
    /// The default implementation returns
    /// `PositionError::unsupported_operation(..)`. Strategies that allow
    /// replacing positions should override this method.
    ///
    fn replace_position(&mut self, _position: &Position) -> Result<(), PositionError> {
        Err(PositionError::unsupported_operation(
            std::any::type_name::<Self>(),
            "replace_position",
        ))
    }

    /// Checks if all short positions have a net premium received that meets or exceeds a specified minimum.
    ///
    /// # Parameters
    /// - `min_premium`: A reference to a `Positive` value representing the minimum premium
    ///   required for the short positions to be considered valid.
    ///
    /// # Returns
    /// - `true` if all short positions in the portfolio have a net premium received that is greater
    ///   than or equal to `min_premium`.
    /// - `false` if any of the following conditions occur:
    ///   - Unable to retrieve positions (e.g., `get_positions` fails).
    ///   - At least one short position has a net premium less than `min_premium`.
    ///   - At least one short position's net premium calculation fails with an error.
    ///
    /// # Implementation Details
    /// - Retrieves positions using the `get_positions` method. If this operation fails, the function returns `false`.
    /// - Filters positions to only include shorts (based on `is_short` method).
    /// - For each short position, determines if the net premium received is available (`is_ok`)
    ///   and satisfies the minimum threshold (`>= *min_premium`).
    ///
    fn valid_premium_for_shorts(&self, min_premium: &Positive) -> bool {
        let positions = match self.get_positions() {
            Ok(positions) => positions,
            Err(_) => return false,
        };
        positions
            .iter()
            .filter(|position| position.is_short())
            .all(|p| {
                p.net_premium_received()
                    .is_ok_and(|premium| premium >= *min_premium)
            })
    }
}

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

    use crate::model::position::Position;
    use crate::model::types::{OptionStyle, Side};
    use crate::model::utils::create_sample_option_simplest;

    #[test]
    fn test_strategy_enum() {
        assert_ne!(StrategyType::BullCallSpread, StrategyType::BearCallSpread);
    }

    #[test]
    fn test_strategy_new_with_legs() {
        let mut strategy = Strategy::new(
            "Test Strategy".to_string(),
            StrategyType::BullCallSpread,
            "Test Description".to_string(),
        );
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let position = Position::new(
            option,
            Positive::ONE,
            Default::default(),
            Positive::ZERO,
            Positive::ZERO,
            None,
            None,
        );

        strategy.legs.push(position);

        assert_eq!(strategy.legs.len(), 1);
    }

    #[test]
    fn test_strategies_get_legs_panic() {
        struct PanicStrategy;
        impl Validable for PanicStrategy {}
        impl Positionable for PanicStrategy {}
        impl BreakEvenable for PanicStrategy {}
        impl BasicAble for PanicStrategy {}
        impl Strategies for PanicStrategy {
            fn get_volume(&mut self) -> Result<Positive, StrategyError> {
                unreachable!()
            }
        }

        let strategy = PanicStrategy;
        assert!(strategy.get_positions().is_err());
    }

    #[test]
    fn test_strategies_break_even_panic() {
        struct PanicStrategy;
        impl Validable for PanicStrategy {}
        impl Positionable for PanicStrategy {}
        impl BreakEvenable for PanicStrategy {}
        impl BasicAble for PanicStrategy {}
        impl Strategies for PanicStrategy {
            fn get_volume(&mut self) -> Result<Positive, StrategyError> {
                unreachable!()
            }
        }

        let strategy = PanicStrategy;
        assert!(strategy.get_break_even_points().is_err());
    }

    #[test]
    fn test_strategies_net_premium_received_panic() {
        struct PanicStrategy;
        impl Validable for PanicStrategy {}
        impl Positionable for PanicStrategy {}
        impl BreakEvenable for PanicStrategy {}
        impl BasicAble for PanicStrategy {}
        impl Strategies for PanicStrategy {}

        let strategy = PanicStrategy;
        assert!(strategy.get_net_premium_received().is_err());
    }

    #[test]
    fn test_strategies_fees_panic() {
        struct PanicStrategy;
        impl Validable for PanicStrategy {}
        impl Positionable for PanicStrategy {}
        impl BreakEvenable for PanicStrategy {}
        impl BasicAble for PanicStrategy {}
        impl Strategies for PanicStrategy {}

        let strategy = PanicStrategy;
        assert!(strategy.get_fees().is_err());
    }

    #[test]
    fn test_strategies_max_profit_iter() {
        struct TestStrategy;
        impl Validable for TestStrategy {}
        impl Positionable for TestStrategy {}
        impl BreakEvenable for TestStrategy {}
        impl BasicAble for TestStrategy {}
        impl Strategies for TestStrategy {
            fn get_max_profit(&self) -> Result<Positive, StrategyError> {
                Ok(Positive::HUNDRED)
            }
        }

        let mut strategy = TestStrategy;
        assert_eq!(strategy.get_max_profit_mut().unwrap().to_f64(), 100.0);
    }

    #[test]
    fn test_strategies_max_loss_iter() {
        struct TestStrategy;
        impl Validable for TestStrategy {}
        impl Positionable for TestStrategy {}
        impl BreakEvenable for TestStrategy {}
        impl BasicAble for TestStrategy {}
        impl Strategies for TestStrategy {
            fn get_max_loss(&self) -> Result<Positive, StrategyError> {
                Ok(pos_or_panic!(50.0))
            }
        }

        let mut strategy = TestStrategy;
        assert_eq!(strategy.get_max_loss_mut().unwrap().to_f64(), 50.0);
    }

    #[test]
    fn test_strategies_empty_strikes() {
        struct EmptyStrategy;
        impl Validable for EmptyStrategy {}
        impl Positionable for EmptyStrategy {
            fn get_positions(&self) -> Result<Vec<&Position>, PositionError> {
                Ok(vec![])
            }
        }
        impl BreakEvenable for EmptyStrategy {}
        impl BasicAble for EmptyStrategy {
            fn get_option_basic_type(&self) -> HashSet<OptionBasicType<'_>> {
                HashSet::new()
            }
        }
        impl Strategies for EmptyStrategy {}

        let strategy = EmptyStrategy;
        assert_eq!(strategy.get_strikes(), Vec::<&Positive>::new());
        assert!(strategy.get_max_min_strikes().is_err());
    }
}

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

    #[test]
    fn test_strategy_type_equality() {
        assert_eq!(StrategyType::BullCallSpread, StrategyType::BullCallSpread);
        assert_ne!(StrategyType::BullCallSpread, StrategyType::BearCallSpread);
    }

    #[test]
    fn test_strategy_type_clone() {
        let strategy = StrategyType::IronCondor;
        let cloned = strategy.clone();
        assert_eq!(strategy, cloned);
    }

    #[test]
    fn test_strategy_type_debug() {
        let strategy = StrategyType::ShortStraddle;
        let debug_string = format!("{strategy:?}");
        assert_eq!(debug_string, "ShortStraddle");
    }

    #[test]
    fn test_strategy_type_from_str() {
        assert_eq!(
            StrategyType::from_str("ShortStrangle"),
            Ok(StrategyType::ShortStrangle)
        );
        assert_eq!(
            StrategyType::from_str("LongCall"),
            Ok(StrategyType::LongCall)
        );
        assert_eq!(
            StrategyType::from_str("BullCallSpread"),
            Ok(StrategyType::BullCallSpread)
        );
        assert_eq!(StrategyType::from_str("InvalidStrategy"), Err(()));
    }

    #[test]
    fn test_strategy_type_is_valid() {
        assert!(StrategyType::is_valid("ShortStrangle"));
        assert!(StrategyType::is_valid("LongPut"));
        assert!(StrategyType::is_valid("CoveredCall"));
        assert!(!StrategyType::is_valid("InvalidStrategy"));
        assert!(!StrategyType::is_valid("Random"));
    }

    #[test]
    fn test_strategy_type_serialization() {
        let strategy = StrategyType::IronCondor;
        let serialized = serde_json::to_string(&strategy).unwrap();
        assert_eq!(serialized, "\"IronCondor\"");

        let deserialized: StrategyType = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, StrategyType::IronCondor);
    }

    #[test]
    fn test_strategy_type_deserialization() {
        let json_data = "\"ShortStraddle\"";
        let deserialized: StrategyType = serde_json::from_str(json_data).unwrap();
        assert_eq!(deserialized, StrategyType::ShortStraddle);
    }

    #[test]
    fn test_invalid_strategy_type_deserialization() {
        let json_data = "\"InvalidStrategy\"";
        let deserialized: Result<StrategyType, _> = serde_json::from_str(json_data);
        assert!(deserialized.is_err());
    }
}

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

    struct TestStrategy {
        underlying_price: Positive,
        break_even_points: Vec<Positive>,
    }

    impl TestStrategy {
        fn new(underlying_price: Positive, break_even_points: Vec<Positive>) -> Self {
            Self {
                underlying_price,
                break_even_points,
            }
        }
    }

    impl Validable for TestStrategy {}

    impl Positionable for TestStrategy {}

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

    impl BasicAble for TestStrategy {
        fn get_underlying_price(&self) -> &Positive {
            &self.underlying_price
        }
        fn get_option_basic_type(&self) -> HashSet<OptionBasicType<'_>> {
            HashSet::new()
        }
    }

    impl Strategies for TestStrategy {
        fn get_max_min_strikes(&self) -> Result<(Positive, Positive), StrategyError> {
            Ok((pos_or_panic!(90.0), Positive::HUNDRED))
        }
    }

    #[test]
    fn test_basic_range_with_step() {
        let strategy = TestStrategy::new(
            Positive::HUNDRED,
            vec![pos_or_panic!(90.0), pos_or_panic!(110.0)],
        );
        let range = strategy.get_best_range_to_show(pos_or_panic!(5.0)).unwrap();
        assert!(!range.is_empty());
        assert_eq!(range[1] - range[0], pos_or_panic!(5.0));
    }

    #[test]
    fn test_range_with_small_step() {
        let strategy = TestStrategy::new(
            Positive::HUNDRED,
            vec![pos_or_panic!(95.0), pos_or_panic!(105.0)],
        );
        let range = strategy.get_best_range_to_show(Positive::ONE).unwrap();
        assert!(!range.is_empty());
        assert_eq!(range[1] - range[0], Positive::ONE);
    }

    #[test]
    fn test_range_boundaries() {
        let strategy = TestStrategy::new(
            Positive::HUNDRED,
            vec![pos_or_panic!(90.0), pos_or_panic!(110.0)],
        );
        let range = strategy.get_best_range_to_show(pos_or_panic!(5.0)).unwrap();
        assert!(range.first().unwrap() < &pos_or_panic!(90.0));
        assert!(range.last().unwrap() > &pos_or_panic!(110.0));
    }

    #[test]
    fn test_range_step_size() {
        let strategy = TestStrategy::new(
            Positive::HUNDRED,
            vec![pos_or_panic!(90.0), pos_or_panic!(110.0)],
        );
        let step = pos_or_panic!(5.0);
        let range = strategy.get_best_range_to_show(step).unwrap();

        for i in 1..range.len() {
            assert_eq!(range[i] - range[i - 1], step);
        }
    }

    #[test]
    fn test_range_includes_underlying() {
        let underlying_price = Positive::HUNDRED;
        let strategy = TestStrategy::new(
            underlying_price,
            vec![pos_or_panic!(90.0), pos_or_panic!(110.0)],
        );
        let range = strategy.get_best_range_to_show(pos_or_panic!(5.0)).unwrap();

        assert!(range.iter().any(|&price| price <= underlying_price));
        assert!(range.iter().any(|&price| price >= underlying_price));
    }

    #[test]
    fn test_range_with_extreme_values() {
        let strategy = TestStrategy::new(
            Positive::HUNDRED,
            vec![pos_or_panic!(50.0), pos_or_panic!(150.0)],
        );
        let range = strategy
            .get_best_range_to_show(pos_or_panic!(10.0))
            .unwrap();

        assert!(range.first().unwrap() <= &pos_or_panic!(50.0));
        assert!(range.last().unwrap() >= &pos_or_panic!(150.0));
    }
}

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

    struct TestStrategy {
        underlying_price: Positive,
        break_even_points: Vec<Positive>,
    }

    impl TestStrategy {
        fn new(underlying_price: Positive, break_even_points: Vec<Positive>) -> Self {
            Self {
                underlying_price,
                break_even_points,
            }
        }
    }

    impl Validable for TestStrategy {}

    impl Positionable for TestStrategy {}

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

    impl BasicAble for TestStrategy {
        fn get_option_basic_type(&self) -> HashSet<OptionBasicType<'_>> {
            HashSet::new()
        }
        fn get_underlying_price(&self) -> &Positive {
            &self.underlying_price
        }
    }

    impl Strategies for TestStrategy {
        fn get_max_min_strikes(&self) -> Result<(Positive, Positive), StrategyError> {
            Ok((pos_or_panic!(90.0), pos_or_panic!(110.0)))
        }
    }

    #[test]
    fn test_basic_range() {
        let strategy = TestStrategy::new(
            Positive::HUNDRED,
            vec![pos_or_panic!(90.0), pos_or_panic!(110.0)],
        );
        let (start, end) = strategy.get_range_to_show().unwrap();
        assert!(start < pos_or_panic!(90.0));
        assert!(end > pos_or_panic!(110.0));
    }

    #[test]
    fn test_range_with_far_strikes() {
        let strategy = TestStrategy::new(
            Positive::HUNDRED,
            vec![pos_or_panic!(90.0), pos_or_panic!(110.0)],
        );
        let (start, end) = strategy.get_range_to_show().unwrap();
        assert!(start < pos_or_panic!(90.0));
        assert!(end > pos_or_panic!(110.0));
    }

    #[test]
    fn test_range_with_underlying_outside_strikes() {
        let strategy = TestStrategy::new(
            pos_or_panic!(150.0),
            vec![pos_or_panic!(90.0), pos_or_panic!(110.0)],
        );
        let (_start, end) = strategy.get_range_to_show().unwrap();
        assert!(end > pos_or_panic!(150.0));
    }
}

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

    struct TestStrategy {
        break_even_points: Vec<Positive>,
    }

    impl TestStrategy {
        fn new(break_even_points: Vec<Positive>) -> Self {
            Self { break_even_points }
        }
    }

    impl Validable for TestStrategy {}

    impl Positionable for TestStrategy {}

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

    impl BasicAble for TestStrategy {}

    impl Strategies for TestStrategy {}

    #[test]
    fn test_no_break_even_points() {
        let strategy = TestStrategy::new(vec![]);
        assert!(strategy.get_range_of_profit().is_err());
    }

    #[test]
    fn test_single_break_even_point() {
        let strategy = TestStrategy::new(vec![Positive::HUNDRED]);
        assert_eq!(strategy.get_range_of_profit().unwrap(), Positive::INFINITY);
    }

    #[test]
    fn test_two_break_even_points() {
        let strategy = TestStrategy::new(vec![pos_or_panic!(90.0), pos_or_panic!(110.0)]);
        assert_eq!(strategy.get_range_of_profit().unwrap(), pos_or_panic!(20.0));
    }

    #[test]
    fn test_multiple_break_even_points() {
        let strategy = TestStrategy::new(vec![
            pos_or_panic!(80.0),
            Positive::HUNDRED,
            pos_or_panic!(120.0),
        ]);
        assert_eq!(strategy.get_range_of_profit().unwrap(), pos_or_panic!(40.0));
    }

    #[test]
    fn test_unordered_break_even_points() {
        let strategy = TestStrategy::new(vec![
            pos_or_panic!(120.0),
            pos_or_panic!(80.0),
            Positive::HUNDRED,
        ]);
        assert_eq!(strategy.get_range_of_profit().unwrap(), pos_or_panic!(40.0));
    }
}

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

    #[test]
    fn test_get_underlying_price_panic() {
        struct TestStrategy;
        impl Validable for TestStrategy {}
        impl Positionable for TestStrategy {}
        impl BreakEvenable for TestStrategy {}
        impl BasicAble for TestStrategy {}
        impl Strategies for TestStrategy {}
        let strategy = TestStrategy;
        let result = std::panic::catch_unwind(|| strategy.get_underlying_price());
        assert!(result.is_err());
    }
}

#[cfg(test)]
mod tests_optimizable {
    use super::*;
    use positive::{pos_or_panic, spos};

    use crate::chains::OptionData;

    use rust_decimal_macros::dec;

    struct TestOptimizableStrategy;

    impl Validable for TestOptimizableStrategy {
        fn validate(&self) -> bool {
            true
        }
    }

    impl Positionable for TestOptimizableStrategy {}

    impl BreakEvenable for TestOptimizableStrategy {}

    impl BasicAble for TestOptimizableStrategy {}

    impl Strategies for TestOptimizableStrategy {}

    impl Optimizable for TestOptimizableStrategy {
        type Strategy = Self;
    }

    #[test]
    fn test_is_valid_long_option() {
        let strategy = TestOptimizableStrategy;
        let option_data = OptionData::new(
            Positive::HUNDRED,  // strike_price
            spos!(5.0),         // call_bid
            spos!(5.5),         // call_ask
            spos!(4.0),         // put_bid
            spos!(4.5),         // put_ask
            pos_or_panic!(0.2), // implied_volatility
            Some(dec!(0.5)),    // delta
            Some(dec!(0.3)),
            Some(dec!(0.3)),
            spos!(1000.0), // volume
            Some(100),     // open_interest
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        assert!(strategy.is_valid_optimal_option(&option_data, &FindOptimalSide::All));
        assert!(strategy.is_valid_optimal_option(
            &option_data,
            &FindOptimalSide::Range(pos_or_panic!(90.0), pos_or_panic!(110.0))
        ));
    }

    #[test]
    #[should_panic]
    fn test_is_valid_long_option_upper_panic() {
        let strategy = TestOptimizableStrategy;
        let option_data = OptionData::new(
            Positive::HUNDRED,  // strike_price
            spos!(5.0),         // call_bid
            spos!(5.5),         // call_ask
            spos!(4.0),         // put_bid
            spos!(4.5),         // put_ask
            pos_or_panic!(0.2), // implied_volatility
            Some(dec!(0.5)),    // delta
            Some(dec!(0.3)),
            Some(dec!(0.3)),
            spos!(1000.0), // volume
            Some(100),     // open_interest
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        assert!(strategy.is_valid_optimal_option(&option_data, &FindOptimalSide::Upper));
    }

    #[test]
    #[should_panic]
    fn test_is_valid_long_option_lower_panic() {
        let strategy = TestOptimizableStrategy;
        let option_data = OptionData::new(
            Positive::HUNDRED,  // strike_price
            spos!(5.0),         // call_bid
            spos!(5.5),         // call_ask
            spos!(4.0),         // put_bid
            spos!(4.5),         // put_ask
            pos_or_panic!(0.2), // implied_volatility
            Some(dec!(0.5)),    // delta
            Some(dec!(0.3)),
            Some(dec!(0.3)),
            spos!(1000.0), // volume
            Some(100),     // open_interest
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        assert!(strategy.is_valid_optimal_option(&option_data, &FindOptimalSide::Lower));
    }

    #[test]
    fn test_is_valid_short_option() {
        let strategy = TestOptimizableStrategy;
        let option_data = OptionData::new(
            Positive::HUNDRED,  // strike_price
            spos!(5.0),         // call_bid
            spos!(5.5),         // call_ask
            spos!(4.0),         // put_bid
            spos!(4.5),         // put_ask
            pos_or_panic!(0.2), // implied_volatility
            Some(dec!(0.5)),    // delta
            Some(dec!(0.3)),
            Some(dec!(0.3)),
            spos!(1000.0), // volume
            Some(100),     // open_interest
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        assert!(strategy.is_valid_optimal_option(&option_data, &FindOptimalSide::All));
        assert!(strategy.is_valid_optimal_option(
            &option_data,
            &FindOptimalSide::Range(pos_or_panic!(90.0), pos_or_panic!(110.0))
        ));
    }

    #[test]
    #[should_panic]
    fn test_is_valid_short_option_upper_panic() {
        let strategy = TestOptimizableStrategy;
        let option_data = OptionData::new(
            Positive::HUNDRED,  // strike_price
            spos!(5.0),         // call_bid
            spos!(5.5),         // call_ask
            spos!(4.0),         // put_bid
            spos!(4.5),         // put_ask
            pos_or_panic!(0.2), // implied_volatility
            Some(dec!(0.5)),    // delta
            Some(dec!(0.3)),
            Some(dec!(0.3)),
            spos!(1000.0), // volume
            Some(100),     // open_interest
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        assert!(strategy.is_valid_optimal_option(&option_data, &FindOptimalSide::Upper));
    }

    #[test]
    #[should_panic]
    fn test_is_valid_short_option_lower_panic() {
        let strategy = TestOptimizableStrategy;
        let option_data = OptionData::new(
            Positive::HUNDRED,  // strike_price
            spos!(5.0),         // call_bid
            spos!(5.5),         // call_ask
            spos!(4.0),         // put_bid
            spos!(4.5),         // put_ask
            pos_or_panic!(0.2), // implied_volatility
            Some(dec!(0.5)),    // delta
            Some(dec!(0.3)),
            Some(dec!(0.3)),
            spos!(1000.0), // volume
            Some(100),     // open_interest
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        assert!(strategy.is_valid_optimal_option(&option_data, &FindOptimalSide::Lower));
    }
}

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

    use crate::model::position::Position;
    use crate::model::types::{OptionStyle, Side};
    use crate::model::utils::create_sample_option_simplest;

    use chrono::{TimeZone, Utc};
    use positive::pos_or_panic;

    struct TestStrategy {
        positions: Vec<Position>,
    }

    impl TestStrategy {
        fn new() -> Self {
            Self {
                positions: Vec::new(),
            }
        }
    }

    impl Validable for TestStrategy {}

    impl Positionable for TestStrategy {
        fn add_position(&mut self, position: &Position) -> Result<(), PositionError> {
            self.positions.push(position.clone());
            Ok(())
        }

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

    impl BreakEvenable for TestStrategy {}

    impl BasicAble for TestStrategy {}

    impl Strategies for TestStrategy {}

    #[test]
    fn test_net_cost_calculation() {
        let mut strategy = TestStrategy::new();
        let option_long = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let option_short = create_sample_option_simplest(OptionStyle::Call, Side::Short);

        let position_long = Position::new(
            option_long,
            Positive::ONE,
            Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
            Positive::ONE,
            pos_or_panic!(0.5),
            None,
            None,
        );
        let position_short = Position::new(
            option_short,
            Positive::ONE,
            Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
            Positive::ONE,
            pos_or_panic!(0.5),
            None,
            None,
        );

        strategy.add_position(&position_long).unwrap();
        strategy.add_position(&position_short).unwrap();

        let result = strategy.get_net_cost().unwrap();
        assert!(result > Decimal::ZERO);
    }

    #[test]
    fn test_net_premium_received_calculation() {
        let mut strategy = TestStrategy::new();
        let option_long = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let option_short = create_sample_option_simplest(OptionStyle::Call, Side::Short);

        let fixed_date = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let position_long = Position::new(
            option_long,
            Positive::ONE,
            fixed_date,
            Positive::ONE,
            pos_or_panic!(0.5),
            None,
            None,
        );
        let position_short = Position::new(
            option_short,
            Positive::ONE,
            fixed_date,
            Positive::ONE,
            pos_or_panic!(0.5),
            None,
            None,
        );

        strategy.add_position(&position_long).unwrap();
        strategy.add_position(&position_short).unwrap();

        let result = strategy.get_net_premium_received().unwrap();
        assert_eq!(result, Positive::ZERO);
    }

    #[test]
    fn test_fees_calculation() {
        let mut strategy = TestStrategy::new();
        let option = create_sample_option_simplest(OptionStyle::Call, Side::Long);
        let fixed_date = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let position = Position::new(
            option,
            Positive::ONE,
            fixed_date,
            Positive::ONE,
            pos_or_panic!(0.5),
            None,
            None,
        );

        strategy.add_position(&position).unwrap();

        let result = strategy.get_fees().unwrap();
        assert!(result > Positive::ZERO);
    }
}