# Decimal Precision Hardening - Audit Report

## Current Decimal Precision Status

### Financial Tables Audit

#### profit_distributions
- total_equity: decimal(15, 2) ✅
- previous_equity: decimal(15, 2) ✅
- total_profit: decimal(15, 2) ✅
- safety_fund: decimal(15, 2) ✅
- sharing_profit: decimal(15, 2) ✅
- referral_share: decimal(15, 2) ✅
- investor_share: decimal(15, 2) ✅
- ecm_share: decimal(15, 2) ✅

**Recommendation:** Current precision (15,2) is adequate for most trading operations. For high-frequency trading or very large funds, consider upgrading to (20,8).

#### investor_profit_logs
- equity: decimal(15, 2) ✅
- profit_amount: decimal(15, 2) ✅
- previous_balance: decimal(15, 2) ✅
- new_balance: decimal(15, 2) ✅
- unit_share_ratio: decimal(10, 8) ✅ (high precision for unit calculations)

**Recommendation:** unit_share_ratio already uses high precision (10,8) which is correct for ratio calculations.

#### safety_funds
- amount: decimal(15, 2) ✅
- cumulative_balance: decimal(15, 2) ✅

**Recommendation:** Current precision is adequate for safety fund tracking.

#### referral_commissions
- referee_profit: decimal(15, 2) ✅
- commission_rate: decimal(5, 5) ✅
- commission_amount: decimal(15, 2) ✅

**Recommendation:** commission_rate precision is adequate for percentage calculations.

#### trades
- volume: decimal(10, 2) ✅
- open_price: decimal(15, 5) ✅ (high precision for price)
- current_price: decimal(15, 5) ✅
- sl: decimal(15, 5) ✅
- tp: decimal(15, 5) ✅
- profit: decimal(15, 2) ✅
- swap: decimal(15, 2) ✅
- commission: decimal(15, 2) ✅

**Recommendation:** Price fields already use (15,5) which is appropriate for trading prices. Financial fields use (15,2) which is standard.

#### trade_histories
- volume: decimal(10, 2) ✅
- open_price: decimal(15, 5) ✅
- close_price: decimal(15, 5) ✅
- profit: decimal(15, 2) ✅
- swap: decimal(15, 2) ✅
- commission: decimal(15, 2) ✅

**Recommendation:** Same as trades table - appropriate precision.

#### investors
- equity: decimal(15, 2) ✅
- available_balance: decimal(15, 2) ✅
- total_profit: decimal(15, 2) ✅

**Recommendation:** Standard precision for investor balances.

#### mt5_accounts
- balance: decimal(15, 2) ✅
- equity: decimal(15, 2) ✅
- margin: decimal(15, 2) ✅
- free_margin: decimal(15, 2) ✅
- floating_profit: decimal(15, 2) ✅

**Recommendation:** Standard precision for MT5 account metrics.

## Precision Recommendations

### Current State: ADEQUATE

The current decimal precision (15,2) for financial amounts is adequate for:
- Funds up to ~$999 trillion
- Precision to 2 decimal places (cents)
- Most trading operations
- Standard accounting practices

### When to Upgrade to (20,8)

Consider upgrading to decimal(20,8) if:
1. **Fund Size Exceeds $1 Trillion** - (15,2) can handle up to ~$999 trillion, but (20,8) provides headroom
2. **High-Frequency Trading** - More decimal places reduce rounding errors in rapid calculations
3. **Cryptocurrency Trading** - Crypto often requires 8 decimal places
4. **Cross-Currency Conversions** - More precision reduces conversion errors
5. **Regulatory Requirements** - Some jurisdictions require higher precision

### Recommended Migration Path

If upgrading to (20,8):

```php
// Migration example
$table->decimal('total_profit', 20, 8)->change();
```

**Impact Analysis:**
- Requires ALTER TABLE on all financial columns
- May cause temporary table locks during migration
- Requires backup before migration
- Test thoroughly in staging environment

## Float Usage Detection

### PHP Float Operations

**Current Concerns:**
- PHP's float type uses IEEE 754 double precision
- Can cause rounding errors in financial calculations
- Should use bcmath for critical calculations

**Recommendations:**

1. **Use BCMath for Critical Calculations:**
```php
// Instead of:
$total = $amount1 + $amount2;

// Use:
$total = bcadd($amount1, $amount2, 8);
```

2. **Use Decimal Casts in Models:**
```php
protected $casts = [
    'profit_amount' => 'decimal:8',
];
```

3. **Avoid Direct Float Arithmetic in Business Logic:**
```php
// Bad:
$percentage = $profit / $total * 100;

// Good:
$percentage = bcmul(bcdiv($profit, $total, 8), '100', 2);
```

### Laravel Decimal Handling

**Current Implementation:**
- Laravel casts decimal columns to PHP strings
- Prevents float precision loss
- Model casts preserve decimal precision

**Verification:**
All financial models already use decimal casts, which is correct.

## Production Recommendations

### Immediate Actions (No Changes Required)
1. ✅ Current decimal precision is adequate for most use cases
2. ✅ All models use decimal casts correctly
3. ✅ Price fields use appropriate precision (15,5)
4. ✅ Ratio fields use high precision (10,8)

### Future Considerations
1. Monitor fund growth - upgrade to (20,8) if approaching $1T AUM
2. Consider BCMath for complex calculations
3. Add precision validation in business logic
4. Implement rounding rules (banker's rounding vs standard rounding)

### Monitoring
- Monitor for rounding errors in reconciliation
- Track precision-related calculation discrepancies
- Alert on cumulative rounding drift

## Conclusion

**Status:** PASS - No immediate changes required

The current decimal precision implementation is production-ready for standard trading operations. The use of decimal(15,2) for financial amounts and decimal(15,5) for prices follows industry best practices. Ratio calculations use appropriate high precision (10,8).

**Recommendation:** Keep current precision unless specific requirements emerge (fund size, regulatory, or operational needs).
