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
//! Regulatory Reporting System
//!
//! This module provides comprehensive regulatory reporting capabilities including:
//! - Trade reporting (EMIR, MiFID II compliant structures)
//! - Transaction reporting
//! - Position reporting
//! - Best execution reporting

use anyhow::Result;
use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Regulatory regime
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RegulatoryRegime {
    /// European Market Infrastructure Regulation
    EMIR,
    /// Markets in Financial Instruments Directive II
    MiFIDII,
    /// Dodd-Frank (US)
    DoddFrank,
    /// Securities and Exchange Commission (US)
    SEC,
    /// Financial Conduct Authority (UK)
    FCA,
    /// Generic/Custom reporting
    Custom,
}

/// Trade report for regulatory submission
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TradeReport {
    /// Unique trade identifier
    pub trade_id: String,
    /// Reporting regime
    pub regime: RegulatoryRegime,
    /// Trade timestamp
    pub trade_timestamp: DateTime<Utc>,
    /// Instrument identifier (ISIN, etc.)
    pub instrument_id: String,
    /// Instrument type
    pub instrument_type: InstrumentType,
    /// Trade quantity
    pub quantity: Decimal,
    /// Trade price
    pub price: Decimal,
    /// Trade currency
    pub currency: String,
    /// Buyer identifier
    pub buyer_id: String,
    /// Seller identifier
    pub seller_id: String,
    /// Venue identifier
    pub venue_id: String,
    /// Trade type
    pub trade_type: TradeType,
    /// Settlement date
    pub settlement_date: DateTime<Utc>,
    /// Additional fields
    pub additional_data: HashMap<String, String>,
}

/// Instrument type for regulatory classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InstrumentType {
    /// Stock or share
    Equity,
    /// Fixed-income instrument
    Bond,
    /// Options, futures, or other derivative
    Derivative,
    /// Physical commodity
    Commodity,
    /// Foreign-exchange pair
    Forex,
    /// Cryptocurrency or digital asset
    Crypto,
    /// Instrument that does not fit another category
    Other,
}

/// Trade type classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TradeType {
    /// Purchase of an instrument
    Buy,
    /// Sale of an instrument
    Sell,
    /// Exchange of one asset for another
    Exchange,
    /// Transfer of ownership without a market transaction
    Transfer,
}

/// Transaction report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionReport {
    /// Transaction identifier
    pub transaction_id: String,
    /// Transaction timestamp
    pub timestamp: DateTime<Utc>,
    /// Account identifier
    pub account_id: String,
    /// Transaction type
    pub transaction_type: TransactionType,
    /// Amount
    pub amount: Decimal,
    /// Currency
    pub currency: String,
    /// From account/wallet
    pub from_account: Option<String>,
    /// To account/wallet
    pub to_account: Option<String>,
    /// Transaction status
    pub status: TransactionStatus,
    /// Fees paid
    pub fees: Option<Decimal>,
    /// Reference data
    pub reference: Option<String>,
}

/// Transaction type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransactionType {
    /// Funds deposited into the platform
    Deposit,
    /// Funds withdrawn from the platform
    Withdrawal,
    /// Trade execution
    Trade,
    /// Internal transfer between accounts
    Transfer,
    /// Platform fee charged
    Fee,
    /// Reward or incentive payment
    Reward,
    /// Transaction that does not fit another category
    Other,
}

/// Transaction status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransactionStatus {
    /// Transaction submitted but not yet processed
    Pending,
    /// Transaction successfully completed
    Completed,
    /// Transaction encountered an error
    Failed,
    /// Transaction was cancelled before processing
    Cancelled,
}

/// Position report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PositionReport {
    /// Report date
    pub report_date: DateTime<Utc>,
    /// Account identifier
    pub account_id: String,
    /// Instrument identifier
    pub instrument_id: String,
    /// Position quantity (positive for long, negative for short)
    pub quantity: Decimal,
    /// Average entry price
    pub average_price: Decimal,
    /// Current market price
    pub market_price: Decimal,
    /// Unrealized P&L
    pub unrealized_pnl: Decimal,
    /// Currency
    pub currency: String,
    /// Position type
    pub position_type: PositionType,
}

/// Position type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PositionType {
    /// Net long position (owns more than owed)
    Long,
    /// Net short position (owes more than owned)
    Short,
    /// Zero net position
    Neutral,
}

/// Best execution report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BestExecutionReport {
    /// Reporting period start
    pub period_start: DateTime<Utc>,
    /// Reporting period end
    pub period_end: DateTime<Utc>,
    /// Order identifier
    pub order_id: String,
    /// Client identifier
    pub client_id: String,
    /// Instrument identifier
    pub instrument_id: String,
    /// Order timestamp
    pub order_timestamp: DateTime<Utc>,
    /// Execution timestamp
    pub execution_timestamp: Option<DateTime<Utc>>,
    /// Requested quantity
    pub requested_quantity: Decimal,
    /// Executed quantity
    pub executed_quantity: Decimal,
    /// Requested price (if limit order)
    pub requested_price: Option<Decimal>,
    /// Executed price
    pub executed_price: Option<Decimal>,
    /// Execution venues considered
    pub venues_considered: Vec<String>,
    /// Selected venue
    pub selected_venue: String,
    /// Execution quality metrics
    pub quality_metrics: ExecutionQualityMetrics,
    /// Justification for venue selection
    pub justification: String,
}

/// Execution quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionQualityMetrics {
    /// Price improvement vs benchmark
    pub price_improvement: Option<Decimal>,
    /// Slippage
    pub slippage: Option<Decimal>,
    /// Fill rate (percentage)
    pub fill_rate: Decimal,
    /// Speed of execution (milliseconds)
    pub execution_speed_ms: u64,
    /// Likelihood of execution score
    pub execution_likelihood: f64,
}

/// Regulatory report generator
pub struct RegulatoryReportGenerator;

impl RegulatoryReportGenerator {
    /// Generate trade report for a given regime
    pub fn generate_trade_report(
        trade_id: impl Into<String>,
        regime: RegulatoryRegime,
    ) -> TradeReport {
        TradeReport {
            trade_id: trade_id.into(),
            regime,
            trade_timestamp: Utc::now(),
            instrument_id: String::new(),
            instrument_type: InstrumentType::Other,
            quantity: Decimal::ZERO,
            price: Decimal::ZERO,
            currency: "USD".to_string(),
            buyer_id: String::new(),
            seller_id: String::new(),
            venue_id: String::new(),
            trade_type: TradeType::Buy,
            settlement_date: Utc::now(),
            additional_data: HashMap::new(),
        }
    }

    /// Generate transaction report
    pub fn generate_transaction_report(transaction_id: impl Into<String>) -> TransactionReport {
        TransactionReport {
            transaction_id: transaction_id.into(),
            timestamp: Utc::now(),
            account_id: String::new(),
            transaction_type: TransactionType::Trade,
            amount: Decimal::ZERO,
            currency: "USD".to_string(),
            from_account: None,
            to_account: None,
            status: TransactionStatus::Completed,
            fees: None,
            reference: None,
        }
    }

    /// Generate position report
    pub fn generate_position_report(
        account_id: impl Into<String>,
        instrument_id: impl Into<String>,
    ) -> PositionReport {
        PositionReport {
            report_date: Utc::now(),
            account_id: account_id.into(),
            instrument_id: instrument_id.into(),
            quantity: Decimal::ZERO,
            average_price: Decimal::ZERO,
            market_price: Decimal::ZERO,
            unrealized_pnl: Decimal::ZERO,
            currency: "USD".to_string(),
            position_type: PositionType::Neutral,
        }
    }

    /// Generate best execution report
    pub fn generate_best_execution_report(
        order_id: impl Into<String>,
        client_id: impl Into<String>,
    ) -> BestExecutionReport {
        BestExecutionReport {
            period_start: Utc::now(),
            period_end: Utc::now(),
            order_id: order_id.into(),
            client_id: client_id.into(),
            instrument_id: String::new(),
            order_timestamp: Utc::now(),
            execution_timestamp: None,
            requested_quantity: Decimal::ZERO,
            executed_quantity: Decimal::ZERO,
            requested_price: None,
            executed_price: None,
            venues_considered: Vec::new(),
            selected_venue: String::new(),
            quality_metrics: ExecutionQualityMetrics {
                price_improvement: None,
                slippage: None,
                fill_rate: Decimal::ZERO,
                execution_speed_ms: 0,
                execution_likelihood: 0.0,
            },
            justification: String::new(),
        }
    }
}

/// Report submission tracker
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportSubmission {
    /// Unique identifier for this submission attempt
    pub submission_id: String,
    /// Kind of regulatory report being submitted
    pub report_type: ReportType,
    /// Regulatory regime this submission targets
    pub regime: RegulatoryRegime,
    /// When the report was submitted
    pub submission_timestamp: DateTime<Utc>,
    /// Current status of the submission
    pub status: SubmissionStatus,
    /// Reference number returned by the regulatory authority on acknowledgment
    pub acknowledgment_ref: Option<String>,
    /// Error description if the submission was rejected or failed
    pub error_message: Option<String>,
}

/// Report type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReportType {
    /// Trade-level regulatory report
    Trade,
    /// Transaction-level report
    Transaction,
    /// Position-level report
    Position,
    /// Best execution report (MiFID II RTS 27/28)
    BestExecution,
}

/// Submission status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SubmissionStatus {
    /// Report queued for submission
    Pending,
    /// Report sent to the regulatory authority
    Submitted,
    /// Regulatory authority confirmed receipt
    Acknowledged,
    /// Regulatory authority rejected the report
    Rejected,
    /// Submission failed due to a technical error
    Failed,
}

/// Report validator
pub struct ReportValidator;

impl ReportValidator {
    /// Validate trade report completeness
    pub fn validate_trade_report(report: &TradeReport) -> Result<()> {
        if report.trade_id.is_empty() {
            anyhow::bail!("Trade ID is required");
        }
        if report.instrument_id.is_empty() {
            anyhow::bail!("Instrument ID is required");
        }
        if report.quantity == Decimal::ZERO {
            anyhow::bail!("Quantity must be non-zero");
        }
        if report.price == Decimal::ZERO {
            anyhow::bail!("Price must be non-zero");
        }
        Ok(())
    }

    /// Validate transaction report
    pub fn validate_transaction_report(report: &TransactionReport) -> Result<()> {
        if report.transaction_id.is_empty() {
            anyhow::bail!("Transaction ID is required");
        }
        if report.account_id.is_empty() {
            anyhow::bail!("Account ID is required");
        }
        if report.amount == Decimal::ZERO {
            anyhow::bail!("Amount must be non-zero");
        }
        Ok(())
    }

    /// Validate position report
    pub fn validate_position_report(report: &PositionReport) -> Result<()> {
        if report.account_id.is_empty() {
            anyhow::bail!("Account ID is required");
        }
        if report.instrument_id.is_empty() {
            anyhow::bail!("Instrument ID is required");
        }
        Ok(())
    }

    /// Validate best execution report
    pub fn validate_best_execution_report(report: &BestExecutionReport) -> Result<()> {
        if report.order_id.is_empty() {
            anyhow::bail!("Order ID is required");
        }
        if report.client_id.is_empty() {
            anyhow::bail!("Client ID is required");
        }
        if report.venues_considered.is_empty() {
            anyhow::bail!("At least one venue must be considered");
        }
        if report.selected_venue.is_empty() {
            anyhow::bail!("Selected venue is required");
        }
        if report.justification.is_empty() {
            anyhow::bail!("Justification for venue selection is required");
        }
        Ok(())
    }
}

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

    #[test]
    fn test_trade_report_generation() {
        let report =
            RegulatoryReportGenerator::generate_trade_report("TRADE123", RegulatoryRegime::MiFIDII);
        assert_eq!(report.trade_id, "TRADE123");
        assert_eq!(report.regime, RegulatoryRegime::MiFIDII);
    }

    #[test]
    fn test_transaction_report_generation() {
        let report = RegulatoryReportGenerator::generate_transaction_report("TXN456");
        assert_eq!(report.transaction_id, "TXN456");
        assert_eq!(report.status, TransactionStatus::Completed);
    }

    #[test]
    fn test_position_report_generation() {
        let report = RegulatoryReportGenerator::generate_position_report("ACC789", "INST001");
        assert_eq!(report.account_id, "ACC789");
        assert_eq!(report.instrument_id, "INST001");
    }

    #[test]
    fn test_best_execution_report_generation() {
        let report = RegulatoryReportGenerator::generate_best_execution_report("ORD001", "CLI001");
        assert_eq!(report.order_id, "ORD001");
        assert_eq!(report.client_id, "CLI001");
    }

    #[test]
    fn test_trade_report_validation_fails_empty_id() {
        let mut report =
            RegulatoryReportGenerator::generate_trade_report("", RegulatoryRegime::EMIR);
        assert!(ReportValidator::validate_trade_report(&report).is_err());

        report.trade_id = "TRADE123".to_string();
        assert!(ReportValidator::validate_trade_report(&report).is_err()); // Still fails due to empty instrument_id
    }

    #[test]
    fn test_trade_report_validation_success() {
        let mut report =
            RegulatoryReportGenerator::generate_trade_report("TRADE123", RegulatoryRegime::EMIR);
        report.instrument_id = "INST001".to_string();
        report.quantity = dec!(100);
        report.price = dec!(50.5);

        assert!(ReportValidator::validate_trade_report(&report).is_ok());
    }

    #[test]
    fn test_transaction_report_validation() {
        let mut report = RegulatoryReportGenerator::generate_transaction_report("TXN123");
        report.account_id = "ACC123".to_string();
        report.amount = dec!(1000);

        assert!(ReportValidator::validate_transaction_report(&report).is_ok());
    }

    #[test]
    fn test_position_report_validation() {
        let report = RegulatoryReportGenerator::generate_position_report("ACC123", "INST001");
        assert!(ReportValidator::validate_position_report(&report).is_ok());
    }

    #[test]
    fn test_best_execution_report_validation() {
        let mut report =
            RegulatoryReportGenerator::generate_best_execution_report("ORD001", "CLI001");
        report.venues_considered = vec!["VENUE1".to_string(), "VENUE2".to_string()];
        report.selected_venue = "VENUE1".to_string();
        report.justification = "Best price and liquidity".to_string();

        assert!(ReportValidator::validate_best_execution_report(&report).is_ok());
    }

    #[test]
    fn test_report_submission_tracking() {
        let submission = ReportSubmission {
            submission_id: "SUB001".to_string(),
            report_type: ReportType::Trade,
            regime: RegulatoryRegime::MiFIDII,
            submission_timestamp: Utc::now(),
            status: SubmissionStatus::Pending,
            acknowledgment_ref: None,
            error_message: None,
        };

        assert_eq!(submission.status, SubmissionStatus::Pending);
        assert_eq!(submission.report_type, ReportType::Trade);
    }
}