# Optiqo - Binary Options Trading Platform Backend

A production-ready Laravel backend for a modern binary options trading platform with real-time market data from Binance.

## 🚀 Features

- **User Authentication** - Laravel Sanctum token-based authentication
- **Wallet System** - Multi-currency wallet with transaction logging
- **Trading Engine** - Binary options trading (UP/DOWN) with automatic expiry
- **Real-time Market Data** - Binance WebSocket integration for 20 crypto pairs
- **Admin Panel** - Complete admin system for user and platform management
- **Security** - Rate limiting, audit logging, role-based access control
- **Scalable Architecture** - Service-based, clean architecture, queue support

## 📋 Requirements

- PHP 8.2+
- MySQL 8.0+
- Redis (for caching, queues, broadcasting)
- Composer
- Node.js & NPM (for Laravel Mix/Vite)

## 🛠️ Installation

### 1. Clone and Install Dependencies

```bash
git clone <repository-url>
cd backend
composer install
```

### 2. Environment Configuration

```bash
cp .env.example .env
php artisan key:generate
```

Edit `.env` file with your configuration:
- Database credentials
- Redis configuration
- Binance WebSocket URL (default: wss://stream.binance.com:9443/ws)
- Frontend URL for CORS
- Mail configuration
- Payment gateway credentials (if needed)

### 3. Database Setup

**Option A: Using SQL Schema (Recommended)**
```bash
mysql -u root -p optiqo < database/schema.sql
```

**Option B: Using Laravel Migrations**
```bash
php artisan migrate
```

### 4. Create Storage Link

```bash
php artisan storage:link
```

### 5. Start Services

**Queue Worker (for background jobs)**
```bash
php artisan queue:work --tries=3
```

**WebSocket Server (for market data)**
```bash
php artisan websocket:serve
```

**Development Server**
```bash
php artisan serve
```

## 📁 Project Structure

```
backend/
├── app/
│   ├── Actions/              # Single-purpose action classes
│   ├── DTOs/                 # Data Transfer Objects
│   ├── Enums/                # Enum classes
│   ├── Events/               # Event classes
│   │   └── MarketPriceUpdated.php
│   ├── Helpers/              # Helper functions
│   ├── Http/
│   │   ├── Controllers/
│   │   │   └── API/V1/       # API Controllers
│   │   │       ├── AuthController.php
│   │   │       ├── TradeController.php
│   │   │       ├── WalletController.php
│   │   │       ├── MarketController.php
│   │   │       └── Admin/    # Admin controllers
│   │   └── Middleware/
│   │       └── AdminMiddleware.php
│   ├── Jobs/                 # Queue jobs
│   │   └── ProcessExpiredTrades.php
│   ├── Listeners/            # Event listeners
│   ├── Market/               # Market data handling
│   │   └── BinanceWebSocketClient.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
│   ├── Services/             # Business logic
│   │   ├── WalletService.php
│   │   └── TradeService.php
│   ├── Traits/               # Reusable traits
│   └── WebSockets/           # WebSocket handlers
├── config/                   # Configuration files
├── database/
│   ├── migrations/           # Database migrations
│   └── schema.sql            # Complete SQL schema
├── routes/
│   └── api.php               # API routes
└── .env.example              # Environment template
```

## 🔌 API Endpoints

### Authentication
```
POST   /api/v1/auth/register
POST   /api/v1/auth/login
POST   /api/v1/auth/logout
GET    /api/v1/auth/me
PUT    /api/v1/auth/profile
PUT    /api/v1/auth/password
```

### Market Data
```
GET    /api/v1/market/assets
GET    /api/v1/market/assets/{id}
GET    /api/v1/market/price/{symbol}
GET    /api/v1/market/candles/{symbol}
GET    /api/v1/market/history/{symbol}
```

### Trading
```
POST   /api/v1/trades/open
GET    /api/v1/trades/active
GET    /api/v1/trades/history
GET    /api/v1/trades/statistics
GET    /api/v1/trades/{uuid}
```

### Wallet
```
GET    /api/v1/wallet/balance
GET    /api/v1/wallet/transactions
```

### Admin (requires admin role)
```
GET    /api/v1/admin/dashboard
GET    /api/v1/admin/statistics
GET    /api/v1/admin/users
PUT    /api/v1/admin/users/{id}/status
GET    /api/v1/admin/withdrawals
PUT    /api/v1/admin/withdrawals/{id}/approve
GET    /api/v1/admin/assets
POST   /api/v1/admin/assets
```

## 🎯 Trading Flow

1. **User opens trade**
   - Validates asset, amount, expiry time
   - Locks balance in wallet
   - Creates trade record with entry price
   - Logs transaction

2. **Trade expiry**
   - Background job checks expired trades
   - Fetches current market price
   - Determines win/loss based on direction
   - Unlocks balance
   - Credits profit or logs loss
   - Updates trade status

3. **Result calculation**
   - UP trade: wins if exit_price > entry_price
   - DOWN trade: wins if exit_price < entry_price
   - Profit = investment × payout_percentage

## 📊 Database Schema

### Core Tables
- `users` - User accounts with roles
- `wallets` - User balances (balance + locked_balance)
- `assets` - Trading pairs (20 crypto assets)
- `trades` - Binary options trades
- `transactions` - All financial operations
- `deposits` - Deposit records
- `withdrawals` - Withdrawal requests
- `market_prices` - Real-time price data
- `candle_data` - OHLCV candle data
- `admin_logs` - Audit trail

## 🔐 Security Features

- **Authentication**: Laravel Sanctum token-based auth
- **Authorization**: Role-based access control (user/admin)
- **Rate Limiting**: API rate limits per endpoint
- **Validation**: Request validation on all inputs
- **Audit Logging**: Admin action logging
- **Database Transactions**: ACID compliance for financial operations
- **Password Hashing**: Bcrypt password hashing
- **CORS**: Configurable CORS for frontend

## 🌐 Market Data Integration

### Binance WebSocket
- Connects to Binance public WebSocket streams
- No API key required
- Real-time 1-second kline data
- Supports 20 trading pairs
- Auto-reconnection on disconnect
- Broadcasts to frontend via Laravel Broadcasting

### Supported Assets
BTCUSDT, ETHUSDT, BNBUSDT, SOLUSDT, XRPUSDT, DOGEUSDT, ADAUSDT, AVAXUSDT, LINKUSDT, LTCUSDT, TRXUSDT, DOTUSDT, BCHUSDT, MATICUSDT, UNIUSDT, ETCUSDT, FILUSDT, APTUSDT, ATOMUSDT, NEARUSDT

## 📦 Required Packages

Add these to `composer.json`:

```json
{
    "require": {
        "php": "^8.2",
        "laravel/framework": "^11.0",
        "laravel/sanctum": "^4.0",
        "predis/predis": "^2.0",
        "cboden/ratchet": "^0.4",
        "react/event-loop": "^1.3"
    }
}
```

## 🚀 Deployment

### Production Checklist

1. **Environment**
   - Set `APP_ENV=production`
   - Set `APP_DEBUG=false`
   - Generate secure `APP_KEY`
   - Configure production database
   - Set up Redis

2. **Optimization**
   ```bash
   php artisan config:cache
   php artisan route:cache
   php artisan view:cache
   composer install --optimize-autoloader --no-dev
   ```

3. **Queue Workers**
   ```bash
   # Use Supervisor to manage queue workers
   php artisan queue:work --tries=3 --timeout=90
   ```

4. **Scheduler**
   ```bash
   # Add to crontab
   * * * * * cd /path-to-project && php artisan schedule:run >> /dev/null 2>&1
   ```

5. **WebSocket Server**
   ```bash
   # Run as background service
   php artisan websocket:serve
   ```

6. **Security**
   - Enable HTTPS
   - Configure firewall
   - Set up rate limiting
   - Regular backups
   - Monitor logs

## 🔧 Configuration Files

### `config/sanctum.php`
Configure token expiration, stateful domains

### `config/cors.php`
Configure CORS for frontend

### `config/broadcasting.php`
Configure broadcasting driver (Redis/Pusher)

### `config/queue.php`
Configure queue driver and connections

## 📝 Scheduled Tasks

Add to `app/Console/Kernel.php`:

```php
protected function schedule(Schedule $schedule)
{
    // Process expired trades every minute
    $schedule->job(new ProcessExpiredTrades)->everyMinute();
    
    // Clean old market prices (keep last 24 hours)
    $schedule->command('market:cleanup')->daily();
    
    // Generate daily reports
    $schedule->command('reports:generate')->dailyAt('00:00');
}
```

## 🐛 Debugging

Enable detailed logging:
```bash
tail -f storage/logs/laravel.log
```

Queue monitoring:
```bash
php artisan queue:monitor
```

## 📚 Additional Resources

- [Laravel Documentation](https://laravel.com/docs)
- [Laravel Sanctum](https://laravel.com/docs/sanctum)
- [Binance WebSocket API](https://binance-docs.github.io/apidocs/spot/en/#websocket-market-streams)

## 🤝 Support

For issues and questions, please create an issue in the repository.

## 📄 License

This project is proprietary software. All rights reserved.