1use super::*;
2
3struct RuleVerdict {
5 passed: bool,
6 flagged: bool,
7 message: String,
8 recommendation: String,
9}
10
11pub struct ComplianceMonitor {
13 compliance_rules: HashMap<String, ComplianceRule>,
14 surveillance_engine: SurveillanceEngine,
15 reporting_engine: ReportingEngine,
16}
17
18pub struct SurveillanceEngine {
20 surveillance_rules: HashMap<String, SurveillanceRule>,
21 anomaly_detector: AnomalyDetector,
22 alert_manager: AlertManager,
23}
24
25#[derive(Debug, Clone)]
27pub struct SurveillanceRule {
28 pub rule_id: String,
29 pub rule_name: String,
30 pub rule_type: SurveillanceRuleType,
31 pub conditions: Vec<SurveillanceCondition>,
32 pub actions: Vec<SurveillanceAction>,
33}
34
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub enum SurveillanceRuleType {
38 MarketManipulation,
39 InsiderTrading,
40 FrontRunning,
41 BestExecution,
42 TradeReporting,
43}
44
45#[derive(Debug, Clone)]
47pub struct SurveillanceCondition {
48 pub condition_id: String,
49 pub field: String,
50 pub operator: ComparisonOperator,
51 pub value: SurveillanceValue,
52}
53
54#[derive(Debug, Clone)]
56pub enum SurveillanceValue {
57 String(String),
58 Number(f64),
59 Boolean(bool),
60}
61
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
64pub enum SurveillanceAction {
65 Alert,
66 Block,
67 Escalate,
68 Report,
69}
70
71pub struct AnomalyDetector {
73 detection_algorithms: HashMap<String, DetectionAlgorithm>,
74 anomaly_patterns: HashMap<String, AnomalyPattern>,
75}
76
77#[derive(Debug, Clone)]
79pub struct DetectionAlgorithm {
80 pub algorithm_id: String,
81 pub algorithm_type: DetectionAlgorithmType,
82 pub parameters: DetectionAlgorithmParameters,
83}
84
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87pub enum DetectionAlgorithmType {
88 Statistical,
89 MachineLearning,
90 RuleBased,
91 Hybrid,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct DetectionAlgorithmParameters {
97 pub confidence_threshold: f64,
98 pub sensitivity: f64,
99 pub lookback_period: u32,
100}
101
102#[derive(Debug, Clone)]
104pub struct AnomalyPattern {
105 pub pattern_id: String,
106 pub pattern_name: String,
107 pub pattern_type: AnomalyPatternType,
108 pub characteristics: Vec<String>,
109}
110
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
113pub enum AnomalyPatternType {
114 Price,
115 Volume,
116 Timing,
117 Sequence,
118}
119
120pub struct AlertManager {
122 alerts: HashMap<String, Alert>,
123 alert_escalation: AlertEscalation,
124 notification_system: NotificationSystem,
125}
126
127#[derive(Debug, Clone)]
129pub struct Alert {
130 pub alert_id: String,
131 pub alert_type: AlertType,
132 pub severity: AlertSeverity,
133 pub description: String,
134 pub source: String,
135 pub timestamp: u64,
136 pub status: AlertStatus,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub enum AlertType {
142 Compliance,
143 Risk,
144 Operational,
145 Security,
146}
147
148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub enum AlertSeverity {
151 Low,
152 Medium,
153 High,
154 Critical,
155}
156
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub enum AlertStatus {
160 New,
161 Acknowledged,
162 Investigating,
163 Resolved,
164 Closed,
165}
166
167pub struct AlertEscalation {
169 escalation_rules: HashMap<String, EscalationRule>,
170 escalation_history: HashMap<String, EscalationHistory>,
171}
172
173#[derive(Debug, Clone)]
175pub struct EscalationRule {
176 pub rule_id: String,
177 pub conditions: Vec<EscalationCondition>,
178 pub actions: Vec<EscalationAction>,
179}
180
181#[derive(Debug, Clone)]
183pub struct EscalationCondition {
184 pub condition_id: String,
185 pub field: String,
186 pub operator: ComparisonOperator,
187 pub value: EscalationValue,
188}
189
190#[derive(Debug, Clone)]
192pub enum EscalationValue {
193 String(String),
194 Number(f64),
195 Boolean(bool),
196}
197
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
200pub enum EscalationAction {
201 Notify,
202 Escalate,
203 Block,
204 Report,
205}
206
207#[derive(Debug, Clone)]
209pub struct EscalationHistory {
210 pub history_id: String,
211 pub alert_id: String,
212 pub escalation_steps: Vec<EscalationStep>,
213}
214
215#[derive(Debug, Clone)]
217pub struct EscalationStep {
218 pub step_id: String,
219 pub action: EscalationAction,
220 pub timestamp: u64,
221 pub performed_by: String,
222}
223
224pub struct NotificationSystem {
226 notification_channels: HashMap<String, NotificationChannel>,
227 notification_templates: HashMap<String, NotificationTemplate>,
228}
229
230#[derive(Debug, Clone)]
232pub struct NotificationChannel {
233 pub channel_id: String,
234 pub channel_type: NotificationChannelType,
235 pub configuration: ChannelConfiguration,
236}
237
238#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
240pub enum NotificationChannelType {
241 Email,
242 SMS,
243 Slack,
244 Webhook,
245 InApp,
246}
247
248#[derive(Debug, Clone)]
250pub struct ChannelConfiguration {
251 pub endpoint: String,
252 pub authentication: AuthenticationMethod,
253 pub format: NotificationFormat,
254}
255
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
258pub enum NotificationFormat {
259 Text,
260 HTML,
261 JSON,
262 Custom,
263}
264
265#[derive(Debug, Clone)]
267pub struct NotificationTemplate {
268 pub template_id: String,
269 pub template_name: String,
270 pub template_type: NotificationTemplateType,
271 pub content: String,
272}
273
274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
276pub enum NotificationTemplateType {
277 Alert,
278 Report,
279 Summary,
280 Custom,
281}
282
283impl ComplianceMonitor {
284 pub fn new() -> Self {
286 Self {
287 compliance_rules: HashMap::new(),
288 surveillance_engine: SurveillanceEngine::new(),
289 reporting_engine: ReportingEngine::new(),
290 }
291 }
292
293 pub fn initialize(&mut self) -> Result<(), FinancialError> {
295 self.surveillance_engine.initialize()?;
296 self.reporting_engine.initialize()?;
297 Ok(())
298 }
299
300 pub fn add_rule(&mut self, rule: ComplianceRule) {
303 self.compliance_rules.insert(rule.rule_id.clone(), rule);
304 }
305
306 pub fn rule_count(&self) -> usize {
308 self.compliance_rules.len()
309 }
310
311 pub fn check_compliance(
326 &mut self,
327 portfolio: &Portfolio,
328 ) -> Result<ComplianceResult, FinancialError> {
329 let mut violations = Vec::new();
330 let mut recommendations = Vec::new();
331 let mut audit_entries = Vec::new();
332 let mut failed = 0usize;
333 let mut flagged = 0usize;
334 let now = portfolio.last_updated;
335
336 if self.compliance_rules.is_empty() {
338 if portfolio.assets.is_empty() {
339 return Ok(ComplianceResult {
341 result_id: format!("compliance_{}_{}", portfolio.portfolio_id, now),
342 portfolio_id: portfolio.portfolio_id.clone(),
343 status: ComplianceStatus::Compliant,
344 risk_score: 0.0,
345 violations: Vec::new(),
346 recommendations: Vec::new(),
347 audit_entries: Vec::new(),
348 });
349 }
350 return Ok(ComplianceResult {
352 result_id: format!("compliance_{}_{}", portfolio.portfolio_id, now),
353 portfolio_id: portfolio.portfolio_id.clone(),
354 status: ComplianceStatus::Flagged,
355 risk_score: 1.0,
356 violations: vec![
357 "No compliance rules registered — cannot assert compliance for a non-empty portfolio."
358 .to_string(),
359 ],
360 recommendations: vec![
361 "Register compliance rules (position limits, KYC/AML, margin, trading restrictions) before asserting compliance."
362 .to_string(),
363 ],
364 audit_entries: Vec::new(),
365 });
366 }
367
368 let total_rules = self.compliance_rules.len();
369
370 let mut rule_ids: Vec<&String> = self.compliance_rules.keys().collect();
372 rule_ids.sort();
373
374 for rule_id in rule_ids {
375 let rule = &self.compliance_rules[rule_id];
376 let verdict = Self::evaluate_rule(rule, portfolio);
377
378 audit_entries.push(AuditEntry {
379 entry_id: format!("audit_{}_{}", rule.rule_id, now),
380 timestamp: now,
381 user_id: String::new(),
382 portfolio_id: portfolio.portfolio_id.clone(),
383 action: PortfolioAction::ComplianceCheck,
384 details: format!(
385 "Rule '{}' ({}): {} — {}",
386 rule.rule_id,
387 rule.rule_type_as_str(),
388 if verdict.passed { "PASS" } else { "FAIL" },
389 verdict.message
390 ),
391 ip_address: String::new(),
392 });
393
394 if !verdict.passed {
395 failed += 1;
396 violations.push(format!("{}: {}", rule.rule_id, verdict.message));
397 recommendations.push(verdict.recommendation);
398 } else if verdict.flagged {
399 flagged += 1;
400 }
401 }
402
403 let risk_score = failed as f64 / total_rules as f64;
404
405 let status = if failed > 0 {
406 ComplianceStatus::NonCompliant
407 } else if flagged > 0 {
408 ComplianceStatus::Flagged
409 } else {
410 ComplianceStatus::Compliant
411 };
412
413 Ok(ComplianceResult {
414 result_id: format!("compliance_{}_{}", portfolio.portfolio_id, now),
415 portfolio_id: portfolio.portfolio_id.clone(),
416 status,
417 risk_score,
418 violations,
419 recommendations,
420 audit_entries,
421 })
422 }
423
424 fn evaluate_rule(rule: &ComplianceRule, portfolio: &Portfolio) -> RuleVerdict {
426 match rule.rule_type {
427 ComplianceRuleType::PositionLimit => {
428 let max_position = rule.parameters.get("max_position").copied().unwrap_or(0.0);
429 if max_position <= 0.0 {
430 return RuleVerdict {
431 passed: false,
432 flagged: false,
433 message: "PositionLimit rule has no max_position parameter".to_string(),
434 recommendation: "Set the 'max_position' parameter to a positive value."
435 .to_string(),
436 };
437 }
438 for asset in &portfolio.assets {
440 if asset.market_value > max_position {
441 return RuleVerdict {
442 passed: false,
443 flagged: false,
444 message: format!(
445 "Asset {} market value {:.2} exceeds max_position {:.2}",
446 asset.symbol, asset.market_value, max_position
447 ),
448 recommendation: format!(
449 "Reduce position in {} to at most {:.2}",
450 asset.symbol, max_position
451 ),
452 };
453 }
454 }
455 RuleVerdict {
456 passed: true,
457 flagged: false,
458 message: "All positions within limit".to_string(),
459 recommendation: String::new(),
460 }
461 }
462 ComplianceRuleType::KYC => {
463 let kyc_required = rule.parameters.get("kyc_required").copied().unwrap_or(1.0);
464 if kyc_required >= 1.0 {
465 let verified = matches!(
469 portfolio.risk_profile.risk_tolerance,
470 RiskTolerance::Conservative
471 | RiskTolerance::Moderate
472 | RiskTolerance::Aggressive
473 | RiskTolerance::VeryAggressive
474 ) && !portfolio.owner_id.is_empty();
475 if !verified {
476 return RuleVerdict {
477 passed: false,
478 flagged: false,
479 message: "KYC verification required but owner identity not verified"
480 .to_string(),
481 recommendation: "Complete KYC verification before trading.".to_string(),
482 };
483 }
484 }
485 RuleVerdict {
486 passed: true,
487 flagged: false,
488 message: "KYC verified".to_string(),
489 recommendation: String::new(),
490 }
491 }
492 ComplianceRuleType::AML => {
493 let aml_required = rule.parameters.get("kyc_required").copied().unwrap_or(1.0);
494 if aml_required >= 1.0 && portfolio.owner_id.is_empty() {
495 return RuleVerdict {
496 passed: false,
497 flagged: false,
498 message: "AML clearance required but no owner identified".to_string(),
499 recommendation: "Provide owner identification for AML screening."
500 .to_string(),
501 };
502 }
503 RuleVerdict {
504 passed: true,
505 flagged: false,
506 message: "AML cleared".to_string(),
507 recommendation: String::new(),
508 }
509 }
510 ComplianceRuleType::MarginRequirement => {
511 let margin_pct = rule.parameters.get("margin_pct").copied().unwrap_or(0.0);
512 if margin_pct <= 0.0 {
513 return RuleVerdict {
514 passed: false,
515 flagged: false,
516 message: "MarginRequirement rule has no margin_pct parameter".to_string(),
517 recommendation: "Set the 'margin_pct' parameter to a positive value."
518 .to_string(),
519 };
520 }
521 let required_margin = portfolio.total_value * margin_pct / 100.0;
522 if portfolio.cash_balance < required_margin {
523 return RuleVerdict {
524 passed: false,
525 flagged: false,
526 message: format!(
527 "Cash balance {:.2} below required margin {:.2} ({:.1}% of {:.2})",
528 portfolio.cash_balance,
529 required_margin,
530 margin_pct,
531 portfolio.total_value
532 ),
533 recommendation: format!(
534 "Increase cash balance to at least {:.2} to meet margin requirement.",
535 required_margin
536 ),
537 };
538 }
539 RuleVerdict {
540 passed: true,
541 flagged: false,
542 message: format!(
543 "Margin satisfied: {:.2} >= {:.2}",
544 portfolio.cash_balance, required_margin
545 ),
546 recommendation: String::new(),
547 }
548 }
549 ComplianceRuleType::TradingRestriction => {
550 let restricted = rule
551 .string_parameters
552 .get("restricted_assets")
553 .map(|s| s.as_str())
554 .unwrap_or("");
555 if restricted.is_empty() {
556 return RuleVerdict {
557 passed: true,
558 flagged: true,
559 message: "TradingRestriction rule has no restricted_assets list — no assets restricted".to_string(),
560 recommendation: "Populate 'restricted_assets' if trading restrictions are intended.".to_string(),
561 };
562 }
563 let restricted_set: Vec<&str> = restricted.split(',').map(|s| s.trim()).collect();
564 for asset in &portfolio.assets {
565 if restricted_set.contains(&asset.symbol.as_str()) {
566 return RuleVerdict {
567 passed: false,
568 flagged: false,
569 message: format!("Asset {} is on the restricted list", asset.symbol),
570 recommendation: format!("Divest restricted asset {}.", asset.symbol),
571 };
572 }
573 }
574 RuleVerdict {
575 passed: true,
576 flagged: false,
577 message: "No restricted assets held".to_string(),
578 recommendation: String::new(),
579 }
580 }
581 ComplianceRuleType::Custom => {
582 RuleVerdict {
584 passed: true,
585 flagged: true,
586 message: "Custom rule — no built-in check, passes by default".to_string(),
587 recommendation: "Implement a custom evaluator if enforcement is needed."
588 .to_string(),
589 }
590 }
591 }
592 }
593}
594
595impl SurveillanceEngine {
596 pub fn new() -> Self {
598 Self {
599 surveillance_rules: HashMap::new(),
600 anomaly_detector: AnomalyDetector::new(),
601 alert_manager: AlertManager::new(),
602 }
603 }
604
605 pub fn initialize(&mut self) -> Result<(), FinancialError> {
607 self.anomaly_detector.initialize()?;
608 self.alert_manager.initialize()?;
609 Ok(())
610 }
611
612 pub fn add_surveillance_rule(&mut self, rule: SurveillanceRule) {
614 self.surveillance_rules.insert(rule.rule_id.clone(), rule);
615 }
616
617 pub fn get_surveillance_rule(&self, rule_id: &str) -> Option<&SurveillanceRule> {
619 self.surveillance_rules.get(rule_id)
620 }
621
622 pub fn list_surveillance_rules(&self) -> Vec<String> {
624 self.surveillance_rules.keys().cloned().collect()
625 }
626}
627
628impl AnomalyDetector {
629 pub fn new() -> Self {
631 Self {
632 detection_algorithms: HashMap::new(),
633 anomaly_patterns: HashMap::new(),
634 }
635 }
636
637 pub fn initialize(&mut self) -> Result<(), FinancialError> {
639 Ok(())
640 }
641
642 pub fn add_detection_algorithm(&mut self, algorithm: DetectionAlgorithm) {
644 self.detection_algorithms
645 .insert(algorithm.algorithm_id.clone(), algorithm);
646 }
647
648 pub fn get_detection_algorithm(&self, algorithm_id: &str) -> Option<&DetectionAlgorithm> {
650 self.detection_algorithms.get(algorithm_id)
651 }
652
653 pub fn list_detection_algorithms(&self) -> Vec<String> {
655 self.detection_algorithms.keys().cloned().collect()
656 }
657
658 pub fn add_anomaly_pattern(&mut self, pattern: AnomalyPattern) {
660 self.anomaly_patterns
661 .insert(pattern.pattern_id.clone(), pattern);
662 }
663
664 pub fn get_anomaly_pattern(&self, pattern_id: &str) -> Option<&AnomalyPattern> {
666 self.anomaly_patterns.get(pattern_id)
667 }
668
669 pub fn list_anomaly_patterns(&self) -> Vec<String> {
671 self.anomaly_patterns.keys().cloned().collect()
672 }
673}
674
675impl AlertManager {
676 pub fn new() -> Self {
678 Self {
679 alerts: HashMap::new(),
680 alert_escalation: AlertEscalation::new(),
681 notification_system: NotificationSystem::new(),
682 }
683 }
684
685 pub fn initialize(&mut self) -> Result<(), FinancialError> {
687 Ok(())
688 }
689
690 pub fn add_alert(&mut self, alert: Alert) {
692 self.alerts.insert(alert.alert_id.clone(), alert);
693 }
694
695 pub fn get_alert(&self, alert_id: &str) -> Option<&Alert> {
697 self.alerts.get(alert_id)
698 }
699
700 pub fn list_alerts(&self) -> Vec<String> {
702 self.alerts.keys().cloned().collect()
703 }
704
705 pub fn alert_escalation(&self) -> &AlertEscalation {
707 &self.alert_escalation
708 }
709
710 pub fn alert_escalation_mut(&mut self) -> &mut AlertEscalation {
712 &mut self.alert_escalation
713 }
714
715 pub fn notification_system(&self) -> &NotificationSystem {
717 &self.notification_system
718 }
719
720 pub fn notification_system_mut(&mut self) -> &mut NotificationSystem {
722 &mut self.notification_system
723 }
724}
725
726impl AlertEscalation {
727 pub fn new() -> Self {
729 Self {
730 escalation_rules: HashMap::new(),
731 escalation_history: HashMap::new(),
732 }
733 }
734
735 pub fn add_escalation_rule(&mut self, rule: EscalationRule) {
737 self.escalation_rules.insert(rule.rule_id.clone(), rule);
738 }
739
740 pub fn get_escalation_rule(&self, rule_id: &str) -> Option<&EscalationRule> {
742 self.escalation_rules.get(rule_id)
743 }
744
745 pub fn list_escalation_rules(&self) -> Vec<String> {
747 self.escalation_rules.keys().cloned().collect()
748 }
749
750 pub fn add_escalation_history(&mut self, history: EscalationHistory) {
752 self.escalation_history
753 .insert(history.history_id.clone(), history);
754 }
755
756 pub fn get_escalation_history(&self, history_id: &str) -> Option<&EscalationHistory> {
758 self.escalation_history.get(history_id)
759 }
760
761 pub fn list_escalation_history(&self) -> Vec<String> {
763 self.escalation_history.keys().cloned().collect()
764 }
765}
766
767impl NotificationSystem {
768 pub fn new() -> Self {
770 Self {
771 notification_channels: HashMap::new(),
772 notification_templates: HashMap::new(),
773 }
774 }
775
776 pub fn add_channel(&mut self, channel: NotificationChannel) {
778 self.notification_channels
779 .insert(channel.channel_id.clone(), channel);
780 }
781
782 pub fn get_channel(&self, channel_id: &str) -> Option<&NotificationChannel> {
784 self.notification_channels.get(channel_id)
785 }
786
787 pub fn list_channels(&self) -> Vec<String> {
789 self.notification_channels.keys().cloned().collect()
790 }
791
792 pub fn add_template(&mut self, template: NotificationTemplate) {
794 self.notification_templates
795 .insert(template.template_id.clone(), template);
796 }
797
798 pub fn get_template(&self, template_id: &str) -> Option<&NotificationTemplate> {
800 self.notification_templates.get(template_id)
801 }
802
803 pub fn list_templates(&self) -> Vec<String> {
805 self.notification_templates.keys().cloned().collect()
806 }
807}