kaccy-core 0.2.0

Core business logic for Kaccy Protocol - batching, fee optimization, and transaction management
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
//! Plugin and extension system for custom indicators and extensibility
use crate::error::CoreError;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// Plugin API version for compatibility checking
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ApiVersion {
    /// Breaking-change version component
    pub major: u32,
    /// Backwards-compatible feature version component
    pub minor: u32,
    /// Bug-fix version component
    pub patch: u32,
}

impl ApiVersion {
    /// Create a new API version
    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    /// Check if this version is compatible with another
    pub fn is_compatible(&self, other: &ApiVersion) -> bool {
        self.major == other.major && self.minor >= other.minor
    }
}

/// Plugin metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginMetadata {
    /// Unique identifier of the plugin
    pub id: Uuid,
    /// Human-readable plugin name
    pub name: String,
    /// Plugin version string (e.g. "1.2.3")
    pub version: String,
    /// Plugin author or organisation
    pub author: String,
    /// Short description of the plugin's functionality
    pub description: String,
    /// Minimum API version required by this plugin
    pub api_version: ApiVersion,
    /// Permissions this plugin requires to operate
    pub permissions: Vec<PluginPermission>,
    /// Names of other plugins this plugin depends on
    pub dependencies: Vec<String>,
    /// When the plugin was first registered
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Whether the plugin has been verified by the marketplace
    pub verified: bool,
}

/// Plugin permissions
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PluginPermission {
    /// Permission to read market data
    ReadMarketData,
    /// Permission to read user profile data
    ReadUserData,
    /// Permission to submit trades
    ExecuteTrades,
    /// Permission to access price feeds
    AccessPriceData,
    /// Permission to register custom indicators
    CreateIndicators,
    /// Permission to make external network requests
    NetworkAccess,
    /// Permission to read or write local files
    FileSystemAccess,
}

impl PluginMetadata {
    /// Create new plugin metadata
    pub fn new(
        name: String,
        version: String,
        author: String,
        description: String,
        api_version: ApiVersion,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            name,
            version,
            author,
            description,
            api_version,
            permissions: Vec::new(),
            dependencies: Vec::new(),
            created_at: chrono::Utc::now(),
            verified: false,
        }
    }

    /// Add a permission
    pub fn add_permission(&mut self, permission: PluginPermission) {
        if !self.permissions.contains(&permission) {
            self.permissions.push(permission);
        }
    }

    /// Check if plugin has permission
    pub fn has_permission(&self, permission: &PluginPermission) -> bool {
        self.permissions.contains(permission)
    }

    /// Verify the plugin
    pub fn verify(&mut self) {
        self.verified = true;
    }
}

/// Plugin execution sandbox
#[derive(Debug, Clone)]
pub struct PluginSandbox {
    /// Plugin running inside this sandbox
    pub plugin_id: Uuid,
    /// Permissions granted to the sandboxed plugin
    pub allowed_permissions: Vec<PluginPermission>,
    /// Resource limits enforced for this plugin
    pub resource_limits: ResourceLimits,
    /// Total number of times the plugin has been executed
    pub execution_count: u64,
    /// Timestamp of the most recent execution
    pub last_execution: Option<chrono::DateTime<chrono::Utc>>,
}

/// Resource limits for plugin execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLimits {
    /// Maximum heap memory the plugin may consume, in megabytes
    pub max_memory_mb: u64,
    /// Maximum CPU wall-clock time allowed per execution, in milliseconds
    pub max_cpu_time_ms: u64,
    /// Maximum outbound network calls per execution
    pub max_network_calls: u32,
    /// Maximum file read/write operations per execution
    pub max_file_operations: u32,
}

impl Default for ResourceLimits {
    fn default() -> Self {
        Self {
            max_memory_mb: 100,
            max_cpu_time_ms: 5000,
            max_network_calls: 10,
            max_file_operations: 0,
        }
    }
}

impl PluginSandbox {
    /// Create a new sandbox
    pub fn new(plugin_id: Uuid, allowed_permissions: Vec<PluginPermission>) -> Self {
        Self {
            plugin_id,
            allowed_permissions,
            resource_limits: ResourceLimits::default(),
            execution_count: 0,
            last_execution: None,
        }
    }

    /// Check if plugin can execute with given permission
    pub fn can_execute(&self, permission: &PluginPermission) -> bool {
        self.allowed_permissions.contains(permission)
    }

    /// Record execution
    pub fn record_execution(&mut self) {
        self.execution_count += 1;
        self.last_execution = Some(chrono::Utc::now());
    }

    /// Set custom resource limits
    pub fn set_limits(&mut self, limits: ResourceLimits) {
        self.resource_limits = limits;
    }
}

/// Plugin registry for discovery and management
#[derive(Debug, Clone)]
pub struct PluginRegistry {
    /// All registered plugins indexed by their UUID
    plugins: HashMap<Uuid, PluginMetadata>,
    /// The API version this registry enforces for compatibility checks
    current_api_version: ApiVersion,
}

impl PluginRegistry {
    /// Create a new plugin registry
    pub fn new(api_version: ApiVersion) -> Self {
        Self {
            plugins: HashMap::new(),
            current_api_version: api_version,
        }
    }

    /// Register a plugin
    pub fn register(&mut self, metadata: PluginMetadata) -> Result<(), CoreError> {
        // Check API compatibility
        if !self
            .current_api_version
            .is_compatible(&metadata.api_version)
        {
            return Err(CoreError::Validation(format!(
                "Plugin API version {:?} is not compatible with current version {:?}",
                metadata.api_version, self.current_api_version
            )));
        }

        // Check dependencies
        for dep in &metadata.dependencies {
            if !self.plugins.values().any(|p| p.name == *dep) {
                return Err(CoreError::Validation(format!(
                    "Missing dependency: {}",
                    dep
                )));
            }
        }

        self.plugins.insert(metadata.id, metadata);
        Ok(())
    }

    /// Unregister a plugin
    pub fn unregister(&mut self, plugin_id: &Uuid) -> Result<(), CoreError> {
        // Check if any other plugins depend on this one
        let plugin_name = self
            .plugins
            .get(plugin_id)
            .map(|p| p.name.clone())
            .ok_or_else(|| CoreError::NotFound("Plugin not found".to_string()))?;

        for plugin in self.plugins.values() {
            if plugin.dependencies.contains(&plugin_name) {
                return Err(CoreError::Validation(format!(
                    "Cannot unregister plugin: {} depends on it",
                    plugin.name
                )));
            }
        }

        self.plugins.remove(plugin_id);
        Ok(())
    }

    /// Get plugin by ID
    pub fn get(&self, plugin_id: &Uuid) -> Option<&PluginMetadata> {
        self.plugins.get(plugin_id)
    }

    /// List all plugins
    pub fn list_all(&self) -> Vec<&PluginMetadata> {
        self.plugins.values().collect()
    }

    /// List verified plugins only
    pub fn list_verified(&self) -> Vec<&PluginMetadata> {
        self.plugins.values().filter(|p| p.verified).collect()
    }
}

/// Plugin marketplace listing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketplaceListing {
    /// Unique identifier of this listing
    pub id: Uuid,
    /// Metadata of the plugin being listed
    pub plugin_metadata: PluginMetadata,
    /// Listed price
    pub price: Decimal,
    /// Currency used for the price (e.g. "BTC")
    pub currency: String,
    /// Total number of downloads
    pub downloads: u64,
    /// Average user rating (0.0 to 5.0)
    pub rating: Decimal,
    /// Total number of user reviews
    pub reviews: u32,
    /// Current lifecycle status of the listing
    pub status: PluginListingStatus,
    /// When this listing was created
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Marketplace listing status for a plugin
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PluginListingStatus {
    /// Listing is live and available for download
    Active,
    /// Listing is awaiting review
    Pending,
    /// Listing has been temporarily suspended
    Suspended,
    /// Listing has been permanently removed
    Removed,
}

impl MarketplaceListing {
    /// Create a new marketplace listing
    pub fn new(plugin_metadata: PluginMetadata, price: Decimal, currency: String) -> Self {
        Self {
            id: Uuid::new_v4(),
            plugin_metadata,
            price,
            currency,
            downloads: 0,
            rating: Decimal::ZERO,
            reviews: 0,
            status: PluginListingStatus::Pending,
            created_at: chrono::Utc::now(),
        }
    }

    /// Increment download count
    pub fn record_download(&mut self) {
        self.downloads += 1;
    }

    /// Add a review
    pub fn add_review(&mut self, rating: Decimal) {
        let total_rating = self.rating * Decimal::from(self.reviews);
        self.reviews += 1;
        self.rating = (total_rating + rating) / Decimal::from(self.reviews);
    }

    /// Approve listing
    pub fn approve(&mut self) {
        self.status = PluginListingStatus::Active;
    }

    /// Suspend listing
    pub fn suspend(&mut self) {
        self.status = PluginListingStatus::Suspended;
    }
}

/// Custom technical indicator
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomIndicator {
    /// Unique identifier of the indicator
    pub id: Uuid,
    /// Human-readable indicator name (e.g. "SMA", "RSI")
    pub name: String,
    /// Short description of what the indicator measures
    pub description: String,
    /// User who created this indicator
    pub creator_id: Uuid,
    /// Mathematical formula used to compute the indicator
    pub formula: IndicatorFormula,
    /// User-configurable parameters keyed by parameter name
    pub parameters: HashMap<String, IndicatorParameter>,
    /// When the indicator was created
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Indicator formula definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum IndicatorFormula {
    /// Simple expression-based formula
    Simple {
        /// Mathematical expression string
        expression: String,
    },
    /// Moving average formula
    MovingAverage {
        /// Number of periods
        period: u32,
        /// Weighting scheme
        weight_type: WeightType,
    },
    /// Composite formula combining multiple indicators
    Composite {
        /// UUIDs of the base indicators to combine
        base_indicators: Vec<Uuid>,
        /// Combination expression
        combination: String,
    },
    /// Arbitrary custom code formula
    Custom {
        /// Source code string to execute in sandbox
        code: String,
    },
}

/// Weight scheme for moving average calculations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WeightType {
    /// Equal weight for all periods (SMA)
    Equal,
    /// Exponentially decreasing weight (EMA)
    Exponential,
    /// Linearly increasing weight (WMA)
    Weighted,
}

/// Indicator parameter
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndicatorParameter {
    /// Parameter name
    pub name: String,
    /// Data type of the parameter value
    pub param_type: ParameterType,
    /// String representation of the default value
    pub default_value: String,
    /// Minimum allowable value (inclusive)
    pub min_value: Option<Decimal>,
    /// Maximum allowable value (inclusive)
    pub max_value: Option<Decimal>,
}

/// Data type of an indicator parameter
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ParameterType {
    /// 32-bit integer value
    Integer,
    /// Arbitrary-precision decimal value
    Decimal,
    /// UTF-8 string value
    String,
    /// Boolean flag
    Boolean,
}

impl CustomIndicator {
    /// Create a new custom indicator
    pub fn new(
        name: String,
        description: String,
        creator_id: Uuid,
        formula: IndicatorFormula,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            name,
            description,
            creator_id,
            formula,
            parameters: HashMap::new(),
            created_at: chrono::Utc::now(),
        }
    }

    /// Add a parameter
    pub fn add_parameter(&mut self, parameter: IndicatorParameter) {
        self.parameters.insert(parameter.name.clone(), parameter);
    }

    /// Calculate indicator value (simplified)
    pub fn calculate(&self, price_data: &[Decimal]) -> Result<Vec<Decimal>, CoreError> {
        if price_data.is_empty() {
            return Ok(vec![]);
        }

        match &self.formula {
            IndicatorFormula::Simple { expression: _ } => {
                // In a real implementation, would parse and evaluate expression
                Ok(price_data.to_vec())
            }
            IndicatorFormula::MovingAverage {
                period,
                weight_type,
            } => self.calculate_moving_average(price_data, *period, weight_type),
            IndicatorFormula::Composite {
                base_indicators: _,
                combination: _,
            } => {
                // Would combine multiple indicators
                Ok(price_data.to_vec())
            }
            IndicatorFormula::Custom { code: _ } => {
                // Would execute custom code in sandbox
                Ok(price_data.to_vec())
            }
        }
    }

    fn calculate_moving_average(
        &self,
        price_data: &[Decimal],
        period: u32,
        weight_type: &WeightType,
    ) -> Result<Vec<Decimal>, CoreError> {
        if price_data.len() < period as usize {
            return Err(CoreError::Validation(
                "Insufficient data for moving average".to_string(),
            ));
        }

        let mut result = Vec::new();

        match weight_type {
            WeightType::Equal => {
                // Simple Moving Average
                for i in (period as usize - 1)..price_data.len() {
                    let sum: Decimal = price_data[i - (period as usize - 1)..=i].iter().sum();
                    result.push(sum / Decimal::from(period));
                }
            }
            WeightType::Exponential => {
                // Exponential Moving Average
                let multiplier = Decimal::from(2) / (Decimal::from(period) + Decimal::ONE);
                let mut ema = price_data[0];
                result.push(ema);

                for price in price_data.iter().skip(1) {
                    ema = (price - ema) * multiplier + ema;
                    result.push(ema);
                }
            }
            WeightType::Weighted => {
                // Weighted Moving Average
                for i in (period as usize - 1)..price_data.len() {
                    let mut weighted_sum = Decimal::ZERO;
                    let mut weight_sum = Decimal::ZERO;

                    for (j, price) in price_data[i - (period as usize - 1)..=i].iter().enumerate() {
                        let weight = Decimal::from(j + 1);
                        weighted_sum += price * weight;
                        weight_sum += weight;
                    }

                    result.push(weighted_sum / weight_sum);
                }
            }
        }

        Ok(result)
    }
}

/// Indicator backtesting framework
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndicatorBacktest {
    /// Indicator that was backtested
    pub indicator_id: Uuid,
    /// Start of the backtesting period
    pub start_date: chrono::DateTime<chrono::Utc>,
    /// End of the backtesting period
    pub end_date: chrono::DateTime<chrono::Utc>,
    /// Aggregated performance results
    pub results: BacktestResults,
}

/// Aggregated performance statistics for a backtest run
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacktestResults {
    /// Total number of signals generated
    pub total_signals: u32,
    /// Number of signals that produced a positive return
    pub profitable_signals: u32,
    /// Win rate (profitable / total)
    pub win_rate: Decimal,
    /// Average profit on winning signals
    pub avg_profit: Decimal,
    /// Average loss on losing signals
    pub avg_loss: Decimal,
    /// Maximum peak-to-trough drawdown observed
    pub max_drawdown: Decimal,
    /// Sharpe ratio of the strategy
    pub sharpe_ratio: Decimal,
}

impl BacktestResults {
    /// Create new backtest results
    pub fn new() -> Self {
        Self {
            total_signals: 0,
            profitable_signals: 0,
            win_rate: Decimal::ZERO,
            avg_profit: Decimal::ZERO,
            avg_loss: Decimal::ZERO,
            max_drawdown: Decimal::ZERO,
            sharpe_ratio: Decimal::ZERO,
        }
    }

    /// Calculate metrics
    pub fn calculate_metrics(&mut self, signals: &[SignalResult]) {
        self.total_signals = signals.len() as u32;
        self.profitable_signals =
            signals.iter().filter(|s| s.profit > Decimal::ZERO).count() as u32;

        if self.total_signals > 0 {
            self.win_rate =
                Decimal::from(self.profitable_signals) / Decimal::from(self.total_signals);
        }

        let profits: Vec<_> = signals
            .iter()
            .filter(|s| s.profit > Decimal::ZERO)
            .collect();
        let losses: Vec<_> = signals
            .iter()
            .filter(|s| s.profit < Decimal::ZERO)
            .collect();

        if !profits.is_empty() {
            self.avg_profit =
                profits.iter().map(|s| s.profit).sum::<Decimal>() / Decimal::from(profits.len());
        }

        if !losses.is_empty() {
            self.avg_loss =
                losses.iter().map(|s| s.profit).sum::<Decimal>() / Decimal::from(losses.len());
        }
    }
}

impl Default for BacktestResults {
    fn default() -> Self {
        Self::new()
    }
}

/// Single signal result from a backtest run
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SignalResult {
    /// Timestamp of the signal
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// Profit or loss realised from acting on this signal
    pub profit: Decimal,
}

/// Indicator composition for combining multiple indicators
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndicatorComposition {
    /// Unique identifier of this composition
    pub id: Uuid,
    /// Human-readable name for the combined indicator
    pub name: String,
    /// IDs of the constituent indicators
    pub base_indicators: Vec<Uuid>,
    /// Rule used to combine the base indicator signals
    pub composition_logic: CompositionLogic,
}

/// Logic for combining multiple indicator signals
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CompositionLogic {
    /// All indicators must agree for a signal
    And,
    /// Any single indicator triggers a signal
    Or,
    /// Weighted combination of indicator signals
    Weighted {
        /// Per-indicator weights (aligned with base_indicators)
        weights: Vec<Decimal>,
    },
    /// Custom expression-based combination
    Custom {
        /// Expression string for signal combination
        expression: String,
    },
}

impl IndicatorComposition {
    /// Create a new composition
    pub fn new(name: String, base_indicators: Vec<Uuid>, logic: CompositionLogic) -> Self {
        Self {
            id: Uuid::new_v4(),
            name,
            base_indicators,
            composition_logic: logic,
        }
    }

    /// Evaluate composition
    pub fn evaluate(&self, signals: &HashMap<Uuid, bool>) -> bool {
        match &self.composition_logic {
            CompositionLogic::And => self
                .base_indicators
                .iter()
                .all(|id| signals.get(id).copied().unwrap_or(false)),
            CompositionLogic::Or => self
                .base_indicators
                .iter()
                .any(|id| signals.get(id).copied().unwrap_or(false)),
            CompositionLogic::Weighted { weights } => {
                let mut weighted_sum = Decimal::ZERO;
                let mut total_weight = Decimal::ZERO;

                for (indicator_id, weight) in self.base_indicators.iter().zip(weights.iter()) {
                    if signals.get(indicator_id).copied().unwrap_or(false) {
                        weighted_sum += weight;
                    }
                    total_weight += weight;
                }

                weighted_sum / total_weight > Decimal::new(5, 1) // > 0.5
            }
            CompositionLogic::Custom { expression: _ } => {
                // Would evaluate custom expression
                false
            }
        }
    }
}

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

    #[test]
    fn test_api_version_compatibility() {
        let v1 = ApiVersion::new(1, 0, 0);
        let v2 = ApiVersion::new(1, 1, 0);
        let v3 = ApiVersion::new(2, 0, 0);

        assert!(v2.is_compatible(&v1));
        assert!(!v1.is_compatible(&v2));
        assert!(!v3.is_compatible(&v1));
    }

    #[test]
    fn test_plugin_metadata() {
        let mut metadata = PluginMetadata::new(
            "Test Plugin".to_string(),
            "1.0.0".to_string(),
            "Author".to_string(),
            "Description".to_string(),
            ApiVersion::new(1, 0, 0),
        );

        metadata.add_permission(PluginPermission::ReadMarketData);
        assert!(metadata.has_permission(&PluginPermission::ReadMarketData));
        assert!(!metadata.has_permission(&PluginPermission::ExecuteTrades));
    }

    #[test]
    fn test_plugin_sandbox() {
        let mut sandbox =
            PluginSandbox::new(Uuid::new_v4(), vec![PluginPermission::ReadMarketData]);

        assert!(sandbox.can_execute(&PluginPermission::ReadMarketData));
        assert!(!sandbox.can_execute(&PluginPermission::ExecuteTrades));

        sandbox.record_execution();
        assert_eq!(sandbox.execution_count, 1);
    }

    #[test]
    fn test_plugin_registry() {
        let mut registry = PluginRegistry::new(ApiVersion::new(1, 0, 0));

        let metadata = PluginMetadata::new(
            "Test Plugin".to_string(),
            "1.0.0".to_string(),
            "Author".to_string(),
            "Description".to_string(),
            ApiVersion::new(1, 0, 0),
        );

        let plugin_id = metadata.id;
        assert!(registry.register(metadata).is_ok());
        assert!(registry.get(&plugin_id).is_some());
    }

    #[test]
    fn test_marketplace_listing() {
        let metadata = PluginMetadata::new(
            "Test Plugin".to_string(),
            "1.0.0".to_string(),
            "Author".to_string(),
            "Description".to_string(),
            ApiVersion::new(1, 0, 0),
        );

        let mut listing = MarketplaceListing::new(metadata, Decimal::from(10), "BTC".to_string());

        listing.record_download();
        assert_eq!(listing.downloads, 1);

        listing.add_review(Decimal::from(5));
        assert_eq!(listing.reviews, 1);
        assert_eq!(listing.rating, Decimal::from(5));
    }

    #[test]
    fn test_custom_indicator_sma() {
        let indicator = CustomIndicator::new(
            "SMA".to_string(),
            "Simple Moving Average".to_string(),
            Uuid::new_v4(),
            IndicatorFormula::MovingAverage {
                period: 3,
                weight_type: WeightType::Equal,
            },
        );

        let prices = vec![
            Decimal::from(10),
            Decimal::from(20),
            Decimal::from(30),
            Decimal::from(40),
        ];

        let result = indicator.calculate(&prices).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], Decimal::from(20)); // (10+20+30)/3
        assert_eq!(result[1], Decimal::from(30)); // (20+30+40)/3
    }

    #[test]
    fn test_indicator_composition_and() {
        let comp = IndicatorComposition::new(
            "Test".to_string(),
            vec![Uuid::new_v4(), Uuid::new_v4()],
            CompositionLogic::And,
        );

        let mut signals = HashMap::new();
        signals.insert(comp.base_indicators[0], true);
        signals.insert(comp.base_indicators[1], true);

        assert!(comp.evaluate(&signals));

        signals.insert(comp.base_indicators[1], false);
        assert!(!comp.evaluate(&signals));
    }

    #[test]
    fn test_backtest_results() {
        let mut results = BacktestResults::new();

        let signals = vec![
            SignalResult {
                timestamp: chrono::Utc::now(),
                profit: Decimal::from(10),
            },
            SignalResult {
                timestamp: chrono::Utc::now(),
                profit: Decimal::from(-5),
            },
            SignalResult {
                timestamp: chrono::Utc::now(),
                profit: Decimal::from(15),
            },
        ];

        results.calculate_metrics(&signals);
        assert_eq!(results.total_signals, 3);
        assert_eq!(results.profitable_signals, 2);
    }
}