# Optiqo Backend - Architecture Documentation

## 🏗️ System Architecture

### Overview
Optiqo is a binary options trading platform built with Laravel 12, following clean architecture principles and service-based design patterns.

```
┌─────────────────────────────────────────────────────────────┐
│                        Frontend (Next.js)                    │
│                     https://optiqo.com                       │
└────────────────────────┬────────────────────────────────────┘
                         │ REST API / WebSocket
                         ▼
┌─────────────────────────────────────────────────────────────┐
│                    Laravel Backend API                       │
│                  https://api.optiqo.com                      │
├─────────────────────────────────────────────────────────────┤
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐     │
│  │ Controllers  │  │  Services    │  │ Repositories │     │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘     │
│         │                  │                  │              │
│         └──────────────────┴──────────────────┘              │
│                            │                                 │
│                            ▼                                 │
│                    ┌──────────────┐                         │
│                    │    Models    │                         │
│                    └──────┬───────┘                         │
└───────────────────────────┼─────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                      MySQL Database                          │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                    Binance WebSocket                         │
│              wss://stream.binance.com:9443                   │
└────────────────────────┬────────────────────────────────────┘
                         │ Real-time Market Data
                         ▼
┌─────────────────────────────────────────────────────────────┐
│              Market Data Processing Service                  │
│                  (BinanceWebSocketClient)                    │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ├──► Store in Database
                         └──► Broadcast to Frontend
```

## 📂 Directory Structure

```
backend/
├── app/
│   ├── Actions/              # Single-purpose action classes
│   │   └── Trade/
│   │       ├── OpenTradeAction.php
│   │       └── CloseTradeAction.php
│   │
│   ├── DTOs/                 # Data Transfer Objects
│   │   ├── TradeDTO.php
│   │   └── WalletDTO.php
│   │
│   ├── Enums/                # Enumeration classes
│   │   ├── TradeStatus.php
│   │   ├── TradeDirection.php
│   │   └── UserRole.php
│   │
│   ├── Events/               # Event classes
│   │   ├── MarketPriceUpdated.php
│   │   ├── TradeOpened.php
│   │   └── TradeClosed.php
│   │
│   ├── Helpers/              # Helper functions
│   │   └── helpers.php
│   │
│   ├── Http/
│   │   ├── Controllers/
│   │   │   └── API/V1/
│   │   │       ├── AuthController.php
│   │   │       ├── TradeController.php
│   │   │       ├── WalletController.php
│   │   │       ├── MarketController.php
│   │   │       └── Admin/
│   │   │           ├── AdminController.php
│   │   │           ├── UserManagementController.php
│   │   │           ├── AssetManagementController.php
│   │   │           └── WithdrawalManagementController.php
│   │   │
│   │   └── Middleware/
│   │       ├── AdminMiddleware.php
│   │       └── RateLimitMiddleware.php
│   │
│   ├── Jobs/                 # Queue jobs
│   │   ├── ProcessExpiredTrades.php
│   │   ├── ProcessDeposit.php
│   │   └── SendTradeNotification.php
│   │
│   ├── Listeners/            # Event listeners
│   │   ├── LogTradeActivity.php
│   │   └── NotifyUserOfTradeResult.php
│   │
│   ├── Market/               # Market data handling
│   │   ├── BinanceWebSocketClient.php
│   │   ├── MarketDataProcessor.php
│   │   └── PriceAggregator.php
│   │
│   ├── Models/               # Eloquent models
│   │   ├── User.php
│   │   ├── Wallet.php
│   │   ├── Asset.php
│   │   ├── Trade.php
│   │   ├── Transaction.php
│   │   ├── Deposit.php
│   │   ├── Withdrawal.php
│   │   ├── MarketPrice.php
│   │   ├── CandleData.php
│   │   └── AdminLog.php
│   │
│   ├── Repositories/         # Repository pattern
│   │   ├── TradeRepository.php
│   │   ├── WalletRepository.php
│   │   └── UserRepository.php
│   │
│   ├── Services/             # Business logic
│   │   ├── WalletService.php
│   │   ├── TradeService.php
│   │   ├── DepositService.php
│   │   └── WithdrawalService.php
│   │
│   ├── Traits/               # Reusable traits
│   │   ├── HasUuid.php
│   │   └── Auditable.php
│   │
│   └── WebSockets/           # WebSocket handlers
│       └── MarketDataHandler.php
│
├── config/                   # Configuration files
│   ├── app.php
│   ├── database.php
│   ├── sanctum.php
│   ├── cors.php
│   └── broadcasting.php
│
├── database/
│   ├── migrations/           # Database migrations
│   └── schema.sql            # Complete SQL schema
│
├── routes/
│   └── api.php               # API routes
│
├── storage/
│   └── logs/                 # Application logs
│
├── .env.example              # Environment template
├── composer.json             # PHP dependencies
├── README.md                 # Project documentation
├── DEPLOYMENT.md             # Deployment guide
└── ARCHITECTURE.md           # This file
```

## 🔄 Request Flow

### 1. API Request Flow

```
Client Request
    │
    ▼
Nginx (Rate Limiting, SSL)
    │
    ▼
Laravel Router (routes/api.php)
    │
    ▼
Middleware Stack
    ├─► Authentication (Sanctum)
    ├─► Authorization (Admin)
    └─► Rate Limiting
    │
    ▼
Controller (API/V1/*)
    │
    ▼
Service Layer (Services/*)
    │
    ├─► Business Logic
    ├─► Validation
    └─► Database Transactions
    │
    ▼
Repository/Model Layer
    │
    ▼
Database (MySQL)
    │
    ▼
Response (JSON)
    │
    ▼
Client
```

### 2. Trade Execution Flow

```
User Opens Trade
    │
    ▼
TradeController::open()
    │
    ▼
TradeService::openTrade()
    │
    ├─► Validate Asset
    ├─► Validate Amount
    ├─► Check Balance
    │
    ▼
Database Transaction START
    │
    ├─► Lock Wallet Balance
    ├─► Create Trade Record
    ├─► Create Transaction Log
    │
    ▼
Database Transaction COMMIT
    │
    ▼
Dispatch TradeOpened Event
    │
    ▼
Return Trade Object
    │
    ▼
Background Job (ProcessExpiredTrades)
    │
    ├─► Check Expiry Time
    ├─► Fetch Current Price
    ├─► Determine Win/Loss
    │
    ▼
TradeService::closeTrade()
    │
    ├─► Update Trade Status
    ├─► Unlock Balance
    ├─► Credit/Debit Wallet
    ├─► Create Transaction Log
    │
    ▼
Dispatch TradeClosed Event
    │
    ▼
Notify User
```

### 3. Market Data Flow

```
Binance WebSocket Stream
    │
    ▼
BinanceWebSocketClient::connect()
    │
    ▼
Receive Kline Data (1s interval)
    │
    ▼
BinanceWebSocketClient::handleMessage()
    │
    ├─► Parse JSON Data
    ├─► Validate Data
    │
    ▼
Store in Database
    │
    ├─► MarketPrice (real-time)
    └─► CandleData (OHLCV)
    │
    ▼
Broadcast to Frontend
    │
    ├─► Laravel Broadcasting
    ├─► Redis Pub/Sub
    └─► WebSocket to Client
    │
    ▼
Frontend Chart Update
```

## 🗄️ Database Design

### Entity Relationship Diagram

```
┌─────────────┐
│    Users    │
└──────┬──────┘
       │ 1
       │
       │ *
┌──────▼──────┐         ┌─────────────┐
│   Wallets   │────────►│Transactions │
└──────┬──────┘    *    └─────────────┘
       │ 1
       │
       │ *
┌──────▼──────┐         ┌─────────────┐
│   Trades    │────────►│   Assets    │
└──────┬──────┘    *    └──────┬──────┘
       │                       │ 1
       │                       │
       │ *                     │ *
┌──────▼──────┐         ┌──────▼──────┐
│Transactions │         │MarketPrices │
└─────────────┘         └─────────────┘
                        ┌─────────────┐
                        │ CandleData  │
                        └─────────────┘
```

### Key Tables

1. **users** - User accounts with authentication
2. **wallets** - User balances (balance + locked_balance)
3. **assets** - Trading pairs configuration
4. **trades** - Binary options trades
5. **transactions** - All financial operations
6. **deposits** - Deposit records
7. **withdrawals** - Withdrawal requests
8. **market_prices** - Real-time price data
9. **candle_data** - OHLCV candle data
10. **admin_logs** - Audit trail

## 🔐 Security Architecture

### Authentication Flow

```
User Login Request
    │
    ▼
AuthController::login()
    │
    ├─► Validate Credentials
    ├─► Check User Status
    │
    ▼
Generate Sanctum Token
    │
    ├─► Store in personal_access_tokens
    ├─► Set Expiration
    │
    ▼
Return Token to Client
    │
    ▼
Client Stores Token
    │
    ▼
Subsequent Requests
    │
    ├─► Include Token in Header
    │   (Authorization: Bearer {token})
    │
    ▼
Sanctum Middleware
    │
    ├─► Validate Token
    ├─► Load User
    ├─► Check Expiration
    │
    ▼
Authorized Request
```

### Security Layers

1. **Transport Layer**: HTTPS/TLS encryption
2. **Authentication**: Laravel Sanctum token-based auth
3. **Authorization**: Role-based access control (RBAC)
4. **Rate Limiting**: API rate limits per endpoint
5. **Input Validation**: Request validation on all inputs
6. **SQL Injection**: Eloquent ORM with prepared statements
7. **XSS Protection**: Output escaping
8. **CSRF Protection**: Token validation
9. **Audit Logging**: Admin action logging

## 📊 Service Layer Architecture

### Service Pattern

```php
// Service handles business logic
class TradeService
{
    protected WalletService $walletService;
    
    public function openTrade(
        User $user,
        Asset $asset,
        string $direction,
        string $amount,
        int $expirySeconds,
        string $entryPrice
    ): Trade {
        // 1. Validate inputs
        // 2. Check business rules
        // 3. Execute in transaction
        // 4. Log operations
        // 5. Dispatch events
        // 6. Return result
    }
}
```

### Key Services

1. **WalletService** - Balance management, transactions
2. **TradeService** - Trade execution, expiry processing
3. **DepositService** - Deposit processing
4. **WithdrawalService** - Withdrawal processing
5. **MarketDataService** - Market data aggregation

## 🔄 Queue Architecture

### Queue Workers

```
┌─────────────────────────────────────────┐
│         Laravel Queue System            │
├─────────────────────────────────────────┤
│                                         │
│  ┌────────────────────────────────┐   │
│  │  ProcessExpiredTrades (1 min)  │   │
│  └────────────────────────────────┘   │
│                                         │
│  ┌────────────────────────────────┐   │
│  │  ProcessDeposit (on demand)    │   │
│  └────────────────────────────────┘   │
│                                         │
│  ┌────────────────────────────────┐   │
│  │  SendNotification (on demand)  │   │
│  └────────────────────────────────┘   │
│                                         │
└─────────────────────────────────────────┘
                    │
                    ▼
            Redis Queue Driver
```

### Job Processing

- **Sync**: Immediate execution (development)
- **Redis**: Queue-based (production)
- **Supervisor**: Process management
- **Retry Logic**: 3 attempts with exponential backoff

## 🌐 Broadcasting Architecture

### Real-time Updates

```
Market Data Update
    │
    ▼
Laravel Event (MarketPriceUpdated)
    │
    ▼
Broadcasting System
    │
    ├─► Redis Pub/Sub
    │
    ▼
WebSocket Server
    │
    ├─► Socket.io / Pusher
    │
    ▼
Frontend Clients
    │
    └─► Update Charts in Real-time
```

## 📈 Scalability Considerations

### Horizontal Scaling

1. **Load Balancer**: Nginx/HAProxy
2. **Multiple App Servers**: PHP-FPM pools
3. **Database Replication**: Master-slave setup
4. **Redis Cluster**: Distributed caching
5. **Queue Workers**: Multiple worker processes

### Vertical Scaling

1. **OPcache**: PHP bytecode caching
2. **Query Optimization**: Indexes, query caching
3. **Connection Pooling**: Persistent connections
4. **Resource Limits**: PHP-FPM tuning

### Caching Strategy

```
Request
    │
    ▼
Check Cache (Redis)
    │
    ├─► Cache Hit ──► Return Cached Data
    │
    └─► Cache Miss
            │
            ▼
        Query Database
            │
            ▼
        Store in Cache
            │
            ▼
        Return Data
```

## 🔍 Monitoring & Logging

### Log Levels

1. **Emergency**: System is unusable
2. **Alert**: Action must be taken immediately
3. **Critical**: Critical conditions
4. **Error**: Error conditions
5. **Warning**: Warning conditions
6. **Notice**: Normal but significant
7. **Info**: Informational messages
8. **Debug**: Debug-level messages

### Monitoring Points

1. **Application Logs**: Laravel logs
2. **Queue Monitoring**: Failed jobs, processing time
3. **Database Monitoring**: Query performance, connections
4. **Server Monitoring**: CPU, memory, disk
5. **API Monitoring**: Response times, error rates
6. **WebSocket Monitoring**: Connection status, message rate

## 🚀 Performance Optimization

### Database Optimization

1. **Indexes**: On frequently queried columns
2. **Query Optimization**: Eager loading, select specific columns
3. **Connection Pooling**: Persistent connections
4. **Read Replicas**: Separate read/write operations

### Application Optimization

1. **OPcache**: PHP bytecode caching
2. **Route Caching**: Pre-compiled routes
3. **Config Caching**: Pre-compiled configuration
4. **View Caching**: Pre-compiled Blade templates
5. **Query Caching**: Redis caching layer

### API Optimization

1. **Response Caching**: Cache frequent requests
2. **Pagination**: Limit result sets
3. **Compression**: Gzip responses
4. **CDN**: Static asset delivery

## 📝 Best Practices

### Code Organization

1. **Single Responsibility**: Each class has one purpose
2. **Dependency Injection**: Constructor injection
3. **Interface Segregation**: Small, focused interfaces
4. **Repository Pattern**: Data access abstraction
5. **Service Layer**: Business logic separation

### Error Handling

1. **Try-Catch Blocks**: Wrap risky operations
2. **Custom Exceptions**: Meaningful error types
3. **Logging**: Log all errors with context
4. **User-Friendly Messages**: Don't expose internals
5. **Rollback Transactions**: On failure

### Testing Strategy

1. **Unit Tests**: Test individual components
2. **Integration Tests**: Test component interactions
3. **Feature Tests**: Test complete features
4. **API Tests**: Test API endpoints
5. **Load Tests**: Test under high load

## 🔄 Deployment Strategy

### CI/CD Pipeline

```
Git Push
    │
    ▼
GitHub Actions / GitLab CI
    │
    ├─► Run Tests
    ├─► Code Quality Checks
    ├─► Build Assets
    │
    ▼
Deploy to Staging
    │
    ├─► Run Migrations
    ├─► Clear Cache
    ├─► Restart Services
    │
    ▼
Manual Approval
    │
    ▼
Deploy to Production
    │
    ├─► Zero-Downtime Deployment
    ├─► Health Checks
    └─► Rollback on Failure
```

## 📚 Additional Resources

- [Laravel Documentation](https://laravel.com/docs)
- [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)
- [SOLID Principles](https://en.wikipedia.org/wiki/SOLID)
- [Repository Pattern](https://designpatternsphp.readthedocs.io/en/latest/More/Repository/README.html)