# Optiqo Wallet Rules & Trading Engine Architecture

## 📋 Overview

This document describes the complete wallet rule engine and trading behavior management system for the Optiqo binary options trading platform.

The system supports three wallet types with different trading rules, permissions, payout behavior, and market access:

1. **DEMO ACCOUNT** - Fair trading for learning
2. **BONUS ACCOUNT** - Promotional bonus with conversion requirements
3. **REAL ACCOUNT** - Dynamic trading with risk management

## 🎯 Key Requirements

### Global Platform Requirement

**CRITICAL**: All users across the platform see:
- Identical OTC prices
- Identical crypto prices
- Identical candle movement
- Identical chart behavior

The platform NEVER generates different chart prices for different users. Charts and market movement remain globally synchronized.

## 🏗️ System Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    User Request (Trade)                      │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────┐
│                  Wallet Rule Engine                          │
│  ┌──────────────────────────────────────────────────────┐  │
│  │  • Check wallet type permissions                      │  │
│  │  • Validate market access                             │  │
│  │  │  • Validate trade amount                            │  │
│  └──────────────────────────────────────────────────────┘  │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────┐
│                  Risk Management Engine                      │
│  ┌──────────────────────────────────────────────────────┐  │
│  │  • Evaluate exposure risk                             │  │
│  │  • Check balance risk                                 │  │
│  │  • Assess concentration risk                          │  │
│  │  • Calculate risk score                               │  │
│  └──────────────────────────────────────────────────────┘  │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────┐
│                Payout Calculation Engine                     │
│  ┌──────────────────────────────────────────────────────┐  │
│  │  • Get applicable payout rule                         │  │
│  │  • Apply wallet-specific adjustments                  │  │
│  │  • Calculate dynamic payout (real wallet)             │  │
│  │  • Calculate potential profit                         │  │
│  └──────────────────────────────────────────────────────┘  │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────┐
│                Exposure Management Engine                    │
│  ┌──────────────────────────────────────────────────────┐  │
│  │  • Track trade exposure                               │  │
│  │  • Monitor direction imbalance                        │  │
│  │  • Update exposure records                            │  │
│  └──────────────────────────────────────────────────────┘  │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────┐
│                    Trade Execution                           │
│  ┌──────────────────────────────────────────────────────┐  │
│  │  • Lock wallet balance                                │  │
│  │  • Create trade record                                │  │
│  │  • Log transaction                                    │  │
│  │  • Queue expiry job                                   │  │
│  └──────────────────────────────────────────────────────┘  │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────┐
│              Bonus Conversion Engine (if bonus)              │
│  ┌──────────────────────────────────────────────────────┐  │
│  │  • Track turnover contribution                        │  │
│  │  • Update trade count                                 │  │
│  │  • Check completion requirements                      │  │
│  │  • Convert bonus if complete                          │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

## 💼 Wallet Types

### 1. DEMO ACCOUNT

**Purpose**: User learning, onboarding, trust building

**Characteristics**:
- Uses real market movement
- Fair OTC behavior
- No hidden restrictions
- No payout manipulation
- No forced losses
- No execution delays
- No trade interference

**Rules**:
```php
'can_trade_crypto' => true,
'can_trade_otc' => true,
'can_withdraw' => false,
'fair_trading' => true,
'max_trade_amount' => '10000',
'initial_balance' => '10000'
```

**Payout**: Fixed 85%

### 2. BONUS ACCOUNT

**Purpose**: Promotional bonus with conversion requirements

**Deposit Rule**:
```
User deposits $20
System adds: +$20 bonus
Result:
  - Real balance = $20
  - Bonus balance = $20
```

**Bonus Reset Rule**:
Once user makes first successful bonus conversion OR bonus balance converts to real balance, all remaining bonus balance becomes ZERO until user receives a new bonus.

**Trading Rules**:
- Can ONLY trade OTC markets
- Cannot trade real crypto markets
- Cannot withdraw bonus balance directly

**Conversion Requirements** (configurable):
- Turnover multiplier (e.g., 30x)
- Minimum trade count (e.g., 50 trades)
- Required trading volume
- Minimum active days

**Market Behavior**:
- Beginner friendly
- Higher probability favorable outcomes (+15% boost)
- Smoother volatility
- Lower aggressive reversals
- Market behavior still looks natural

**Rules**:
```php
'can_trade_crypto' => false,
'can_trade_otc' => true,
'can_withdraw' => false,
'beginner_friendly' => true,
'win_probability_boost' => 0.15,
'max_trade_amount' => '1000'
```

**Payout**: 88% base (beginner friendly boost)

### 3. REAL ACCOUNT

**Purpose**: Real money trading with dynamic behavior

**Trading Access**:
- Can trade real crypto markets
- Can trade OTC markets
- Can withdraw funds

**Engine Features**:
- Dynamic market analysis
- Volatility analysis
- Payout optimization
- Risk engine
- Exposure balancing
- Candle momentum analysis

**Risk Management**:
- House exposure protection
- Payout balancing
- Liquidity simulation
- Volatility-driven movement
- Candle continuation logic

**Rules**:
```php
'can_trade_crypto' => true,
'can_trade_otc' => true,
'can_withdraw' => true,
'dynamic_payout' => true,
'risk_management' => true,
'max_trade_amount' => '50000'
```

**Payout**: 85% base, dynamically adjusted (75-90% range)

## 🗄️ Database Schema

### Core Tables

#### wallet_balances
```sql
- id, user_id, wallet_type (demo/bonus/real)
- balance, locked_balance, bonus_balance
- currency, is_active
```

#### wallet_rules
```sql
- id, wallet_type, rule_name, rule_key
- rule_value (JSON/boolean/numeric)
- is_active, priority, description
```

#### bonus_rules
```sql
- id, name, bonus_percentage
- turnover_multiplier, min_deposit_amount
- max_bonus_amount, min_trade_count
- min_trade_amount, min_active_days
- expiry_days, is_active, priority
```

#### bonus_conversions
```sql
- id, user_id, wallet_balance_id, bonus_rule_id
- initial_deposit_amount, bonus_amount
- required_turnover, current_turnover
- trade_count, active_days, status
- converted_amount, started_at, completed_at, expires_at
```

#### bonus_transactions
```sql
- id, bonus_conversion_id, trade_id
- transaction_type (deposit/trade/conversion/reset/expiry)
- amount, turnover_contribution
- description, metadata
```

#### payout_rules
```sql
- id, wallet_type, market_type, asset_id
- base_payout_percentage, min_payout_percentage, max_payout_percentage
- volatility_adjustment, exposure_adjustment
- is_active, priority
```

#### trade_exposure
```sql
- id, asset_id, market_type, wallet_type, direction
- total_amount, trade_count, potential_payout
- timestamp
```

#### risk_settings
```sql
- id, setting_key, setting_value (JSON)
- description, is_active
```

## 🔧 Core Engines

### 1. WalletRuleEngine

**Location**: `app/Trading/Rules/WalletRuleEngine.php`

**Responsibilities**:
- Load and cache wallet rules
- Check trading permissions
- Validate trade amounts
- Get wallet-specific settings

**Key Methods**:
```php
canTradeCrypto(WalletBalance $wallet): bool
canTradeOTC(WalletBalance $wallet): bool
canWithdraw(WalletBalance $wallet): bool
usesFairTrading(WalletBalance $wallet): bool
isBeginnerFriendly(WalletBalance $wallet): bool
getWinProbabilityBoost(WalletBalance $wallet): float
getMaxTradeAmount(WalletBalance $wallet): string
validateTradeAmount(WalletBalance $wallet, string $amount): array
```

### 2. BonusConversionEngine

**Location**: `app/Trading/Bonus/BonusConversionEngine.php`

**Responsibilities**:
- Create bonus conversions on deposit
- Track turnover progress
- Process trade contributions
- Complete conversions
- Reset bonus balance
- Expire old conversions

**Key Methods**:
```php
createBonusConversion(User $user, WalletBalance $wallet, string $depositAmount): BonusConversion
processTrade(BonusConversion $conversion, int $tradeId, string $amount, bool $isWin): void
completeConversion(BonusConversion $conversion): void
resetBonusBalance(WalletBalance $wallet): void
expireConversions(): int
getConversionProgress(User $user): ?array
```

### 3. ExposureManagementEngine

**Location**: `app/Trading/Exposure/ExposureManagementEngine.php`

**Responsibilities**:
- Track trade exposure by direction
- Monitor exposure imbalance
- Calculate exposure ratios
- Check exposure limits
- Provide exposure statistics

**Key Methods**:
```php
addExposure(Asset $asset, MarketType $marketType, WalletType $walletType, string $direction, string $amount, string $potentialPayout): TradeExposure
removeExposure(...): void
getAssetExposure(Asset $asset, MarketType $marketType, WalletType $walletType): array
getDirectionExposureRatio(...): float
exceedsExposureLimit(...): bool
getExposureStatistics(WalletType $walletType): array
```

### 4. RiskManagementEngine

**Location**: `app/Trading/Risk/RiskManagementEngine.php`

**Responsibilities**:
- Evaluate trade risk
- Check exposure limits
- Assess balance risk
- Monitor concentration risk
- Calculate risk scores
- Provide risk warnings

**Key Methods**:
```php
evaluateTradeRisk(WalletBalance $wallet, Asset $asset, MarketType $marketType, string $direction, string $amount): array
getRecommendedTradeSize(WalletBalance $wallet): string
getRiskSettings(): array
updateRiskSetting(string $key, array $value): bool
needsRebalancing(Asset $asset, MarketType $marketType, WalletType $walletType): bool
```

### 5. PayoutCalculationEngine

**Location**: `app/Trading/Payout/PayoutCalculationEngine.php`

**Responsibilities**:
- Calculate payout percentages
- Apply wallet-specific adjustments
- Handle dynamic payouts for real wallets
- Calculate potential profits
- Manage payout rules

**Key Methods**:
```php
calculatePayoutPercentage(WalletBalance $wallet, Asset $asset, MarketType $marketType, string $direction, float $volatility): float
calculatePotentialProfit(string $amount, float $payoutPercentage): string
calculateTotalReturn(string $amount, float $payoutPercentage): string
getPayoutInfo(...): array
updatePayoutRule(...): bool
```

## 🔄 Trade Flow

### Opening a Trade

```php
1. User submits trade request
2. WalletRuleEngine validates:
   - Can trade this market type?
   - Trade amount within limits?
   - Sufficient balance?
3. RiskManagementEngine evaluates:
   - Exposure risk
   - Balance risk
   - Concentration risk
4. PayoutCalculationEngine calculates:
   - Payout percentage (wallet-specific)
   - Potential profit
5. ExposureManagementEngine:
   - Adds exposure tracking
6. Trade execution:
   - Lock balance
   - Create trade record
   - Log transaction
7. BonusConversionEngine (if bonus wallet):
   - Track for turnover
```

### Closing a Trade

```php
1. Trade expires or is closed
2. Determine win/loss based on price
3. ExposureManagementEngine:
   - Remove exposure
4. Calculate actual profit/loss
5. Update wallet balance:
   - Unlock balance
   - Credit/debit based on result
6. BonusConversionEngine (if bonus wallet):
   - Add turnover contribution
   - Check if conversion complete
   - Convert bonus if requirements met
7. Log transaction
8. Notify user
```

## 🎮 Admin Control Features

Admins can configure:

1. **Wallet Rules**:
   - Enable/disable rules per wallet type
   - Set max trade amounts
   - Configure permissions

2. **Bonus System**:
   - Bonus percentage
   - Turnover requirements
   - Trade count requirements
   - Expiry settings

3. **Payout Rules**:
   - Base payout percentages
   - Min/max ranges
   - Volatility adjustment toggle
   - Exposure adjustment toggle

4. **Risk Settings**:
   - Max exposure per asset
   - Max exposure per direction
   - Exposure rebalancing thresholds
   - Payout adjustment ranges

5. **OTC Markets**:
   - Volatility levels
   - Beginner-friendly mode
   - Win probability boost
   - Pause/resume markets

## 🔒 Security Features

1. **Database Transactions**: All financial operations use DB transactions
2. **Audit Logs**: All admin actions logged
3. **Rule Validation**: Input validation on all rules
4. **Anti-Abuse Protection**: Rate limiting, exposure limits
5. **Secure Wallet Operations**: Balance locking, atomic updates
6. **Queue-Based Settlement**: Async trade processing

## 📊 Monitoring & Analytics

Track:
- Wallet type distribution
- Bonus conversion rates
- Exposure imbalances
- Risk scores
- Payout adjustments
- Trade volumes by wallet type

## 🚀 Usage Examples

### Check if User Can Trade

```php
$ruleEngine = app(WalletRuleEngine::class);
$wallet = $user->walletBalances()->where('wallet_type', 'bonus')->first();

if ($ruleEngine->canTradeOTC($wallet)) {
    // Allow OTC trading
}

if (!$ruleEngine->canTradeCrypto($wallet)) {
    // Block crypto trading for bonus wallet
}
```

### Calculate Trade Payout

```php
$payoutEngine = app(PayoutCalculationEngine::class);

$payoutInfo = $payoutEngine->getPayoutInfo(
    $wallet,
    $asset,
    MarketType::OTC,
    'up',
    '100.00'
);

// Returns:
// [
//     'payout_percentage' => 88.0,
//     'investment_amount' => '100.00',
//     'potential_profit' => '88.00',
//     'total_return' => '188.00',
//     ...
// ]
```

### Evaluate Trade Risk

```php
$riskEngine = app(RiskManagementEngine::class);

$riskAssessment = $riskEngine->evaluateTradeRisk(
    $wallet,
    $asset,
    MarketType::OTC,
    'up',
    '500.00'
);

if (!$riskAssessment['can_trade']) {
    // Block trade, show risks
    return response()->json([
        'error' => 'Trade blocked',
        'risks' => $riskAssessment['risks']
    ], 400);
}
```

### Process Bonus Deposit

```php
$bonusEngine = app(BonusConversionEngine::class);

$conversion = $bonusEngine->createBonusConversion(
    $user,
    $bonusWallet,
    '20.00' // deposit amount
);

// Bonus added to wallet
// Conversion tracking started
```

## 📝 Best Practices

1. **Always use engines** - Don't bypass the rule engines
2. **Cache rules** - Rules are cached for performance
3. **Log everything** - Comprehensive logging for audit
4. **Validate inputs** - Always validate before processing
5. **Use transactions** - Wrap financial operations in DB transactions
6. **Monitor exposure** - Keep track of exposure imbalances
7. **Test thoroughly** - Test all wallet types and scenarios

## 🔗 Related Documentation

- [OTC Architecture](OTC_ARCHITECTURE.md)
- [Main Architecture](ARCHITECTURE.md)
- [Deployment Guide](DEPLOYMENT.md)

---

**Made with Bob** - Optiqo Wallet Rules & Trading Engine