# Trading Modal - Code Reference & Examples

## 1. How to Use the Trade Modal in Frontend

### Opening the Modal
```javascript
// This is called when user clicks Trade button
openTradeModal(instrument) {
    this.selectedInstrument = instrument;
    this.tradeForm = {
        hours: 1,
        amount: '',
        tradeType: 'buy'
    };
    this.errorMessage = '';
    this.successMessage = '';
    this.showTradeModal = true;  // Opens the modal
}

// Button usage in Blade:
<button @click="openTradeModal(instrument)" class="...">
    Trade
</button>
```

### Placing a Trade
```javascript
async placeTrade() {
    // 1. Validate locally
    if (!this.tradeForm.amount || this.tradeForm.amount <= 0) {
        this.errorMessage = 'Please enter a valid amount';
        return;
    }

    if (this.tradeForm.amount > this.userBalance) {
        this.errorMessage = 'Insufficient balance...';
        return;
    }

    // 2. Show loading state
    this.isLoading = true;
    this.errorMessage = '';
    this.successMessage = '';

    try {
        // 3. Send to server
        const response = await fetch('{{ route("trade.place") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({
                instrument_id: this.selectedInstrument.id,
                instrument_name: this.selectedInstrument.name,
                instrument_symbol: this.selectedInstrument.symbol,
                amount: this.tradeForm.amount,
                hours: this.tradeForm.hours,
                trade_type: this.tradeForm.tradeType,
                entry_price: this.selectedInstrument.price
            })
        });

        const data = await response.json();

        // 4. Handle response
        if (data.success) {
            this.successMessage = 'Trade placed successfully! ID: ' + data.trade.trade_id;
            this.userBalance = data.new_balance;
            
            // Close modal after 2 seconds
            setTimeout(() => {
                this.showTradeModal = false;
                this.tradeForm = { hours: 1, amount: '', tradeType: 'buy' };
            }, 2000);
        } else {
            this.errorMessage = data.message;
        }
    } catch (error) {
        this.errorMessage = 'An error occurred: ' + error.message;
    } finally {
        this.isLoading = false;
    }
}
```

---

## 2. Backend Examples

### TradeController - Place Trade
```php
public function store(Request $request)
{
    try {
        // Validate input
        $validated = $request->validate([
            'instrument_id' => 'required|integer',
            'instrument_name' => 'required|string',
            'instrument_symbol' => 'required|string',
            'amount' => 'required|numeric|min:0.01',
            'hours' => 'required|integer|min:1',
            'trade_type' => 'required|in:buy,sell',
            'entry_price' => 'required|numeric|min:0.01',
        ]);

        // Get user
        $user = Auth::user();

        // Check balance
        if ($user->balance < $validated['amount']) {
            return response()->json([
                'success' => false,
                'message' => 'Insufficient balance...',
                'balance' => $user->balance,
                'required' => $validated['amount'],
            ], 422);
        }

        // Calculate expiration
        $expiresAt = Carbon::now()->addHours($validated['hours']);

        // Create trade
        $trade = Trade::create([
            'trade_id' => Str::uuid(),
            'user_id' => $user->id,
            'instrument_id' => $validated['instrument_id'],
            'instrument_name' => $validated['instrument_name'],
            'instrument_symbol' => $validated['instrument_symbol'],
            'amount' => $validated['amount'],
            'entry_price' => $validated['entry_price'],
            'trade_type' => $validated['trade_type'],
            'status' => 'open',
            'hours' => $validated['hours'],
            'expires_at' => $expiresAt,
            'opened_at' => now(),
        ]);

        // Deduct from balance
        $user->balance -= $validated['amount'];
        $user->save();

        // Create notification
        Notification::create([
            'user_id' => $user->id,
            'title' => 'Trade Opened Successfully',
            'description' => "Your {$validated['trade_type']} trade on {$validated['instrument_symbol']} for {$validated['amount']} has been opened.",
            'status' => 'UNREAD',
            'type' => 'trade_open',
        ]);

        // Send notifications
        $user->notify(new TradeOpenNotification($trade));
        
        $admin = User::where('id', 1)->first();
        if ($admin) {
            Mail::to($admin->email)->send(new TradeOpenMail($trade, $user));
        }

        // Return success
        return response()->json([
            'success' => true,
            'message' => 'Trade placed successfully!',
            'trade' => [
                'id' => $trade->id,
                'trade_id' => $trade->trade_id,
                'symbol' => $trade->instrument_symbol,
                'amount' => $trade->amount,
                'type' => $trade->trade_type,
                'expires_at' => $trade->expires_at->format('Y-m-d H:i:s'),
            ],
            'new_balance' => $user->balance,
        ]);

    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $e->errors(),
        ], 422);
    } catch (\Exception $e) {
        \Log::error('Trade placement error: ' . $e->getMessage());
        return response()->json([
            'success' => false,
            'message' => 'An error occurred: ' . $e->getMessage(),
        ], 500);
    }
}
```

---

## 3. Database Examples

### Create Trade Record
```php
// Using Eloquent
$trade = Trade::create([
    'trade_id' => Str::uuid(),
    'user_id' => Auth::id(),
    'instrument_id' => 1,
    'instrument_name' => 'Bitcoin',
    'instrument_symbol' => 'BTC/USD',
    'amount' => 500.00,
    'entry_price' => 113692.00,
    'trade_type' => 'buy',
    'status' => 'open',
    'hours' => 24,
    'expires_at' => Carbon::now()->addHours(24),
    'opened_at' => now(),
]);

// Alternative: Raw SQL
DB::table('trades')->insert([
    'trade_id' => Str::uuid(),
    'user_id' => Auth::id(),
    'instrument_id' => 1,
    'instrument_name' => 'Bitcoin',
    'instrument_symbol' => 'BTC/USD',
    'amount' => 500.00,
    'entry_price' => 113692.00,
    'trade_type' => 'buy',
    'status' => 'open',
    'hours' => 24,
    'expires_at' => now()->addHours(24),
    'opened_at' => now(),
    'created_at' => now(),
    'updated_at' => now(),
]);
```

### Query Trades
```php
// Get user's open trades
$openTrades = Trade::where('user_id', Auth::id())
    ->where('status', 'open')
    ->orderBy('created_at', 'desc')
    ->get();

// Get specific trade
$trade = Trade::find($tradeId);

// Get expired trades
$expired = Trade::where('status', 'open')
    ->where('expires_at', '<', now())
    ->get();

// Get profit/loss summary
$profitLoss = Trade::where('user_id', Auth::id())
    ->where('status', 'closed')
    ->sum('profit_loss');
```

---

## 4. Notification Examples

### User Notification in Database
```php
// Create notification
Notification::create([
    'user_id' => $user->id,
    'title' => 'Trade Opened Successfully',
    'description' => "Your BUY trade on BTC/USD for $500 has been opened.",
    'status' => 'UNREAD',
    'type' => 'trade_open',
]);

// Query notifications
$notifications = Notification::where('user_id', Auth::id())
    ->where('status', 'UNREAD')
    ->orderBy('created_at', 'desc')
    ->get();
```

### Send Notification
```php
// Send to user
$user->notify(new TradeOpenNotification($trade));

// Send email
Mail::to($admin->email)->send(new TradeOpenMail($trade, $user));
```

---

## 5. HTML Modal Structure

### Minimal Modal Example
```blade
<div x-show="showTradeModal" class="fixed inset-0 bg-black/50 z-40"></div>

<div x-show="showTradeModal" class="fixed inset-0 z-50">
    <div class="bg-white rounded-2xl max-w-2xl mx-auto">
        <!-- Header -->
        <div class="bg-gradient-to-r from-blue-600 to-blue-700 p-6">
            <h2 x-text="selectedInstrument?.name"></h2>
        </div>

        <!-- Body -->
        <div class="p-6 space-y-6">
            <!-- Amount Input -->
            <div>
                <label>Amount to Invest</label>
                <input type="number" x-model.number="tradeForm.amount" min="0.01" step="0.01" />
            </div>

            <!-- Hours Input -->
            <div>
                <label>Trading Hours</label>
                <input type="number" x-model.number="tradeForm.hours" min="1" max="720" />
            </div>

            <!-- Trade Type -->
            <div class="flex gap-3">
                <button @click="tradeForm.tradeType = 'buy'">BUY</button>
                <button @click="tradeForm.tradeType = 'sell'">SELL</button>
            </div>
        </div>

        <!-- Footer -->
        <div class="p-6 flex gap-3">
            <button @click="showTradeModal = false">Cancel</button>
            <button @click="placeTrade">Place Trade</button>
        </div>
    </div>
</div>
```

---

## 6. Form Validation Examples

### Frontend Validation
```javascript
// Validate amount
if (!tradeForm.amount) {
    errorMessage = 'Amount is required';
} else if (tradeForm.amount <= 0) {
    errorMessage = 'Amount must be positive';
} else if (tradeForm.amount > userBalance) {
    errorMessage = 'Insufficient balance';
}

// Validate hours
if (!tradeForm.hours) {
    errorMessage = 'Hours is required';
} else if (tradeForm.hours < 1 || tradeForm.hours > 720) {
    errorMessage = 'Hours must be between 1 and 720';
}

// Validate trade type
if (!['buy', 'sell'].includes(tradeForm.tradeType)) {
    errorMessage = 'Invalid trade type';
}
```

### Backend Validation
```php
$validated = $request->validate([
    'instrument_id' => 'required|integer|exists:instruments,id',
    'instrument_name' => 'required|string|max:255',
    'instrument_symbol' => 'required|string|max:255',
    'amount' => 'required|numeric|min:0.01|max:999999.99',
    'hours' => 'required|integer|min:1|max:720',
    'trade_type' => 'required|in:buy,sell',
    'entry_price' => 'required|numeric|min:0.00001',
]);
```

---

## 7. Error Handling Examples

### Try-Catch Pattern
```php
try {
    // Attempt operation
    $trade = Trade::create($data);
    return response()->json(['success' => true, 'trade' => $trade]);
    
} catch (\Illuminate\Validation\ValidationException $e) {
    return response()->json([
        'success' => false,
        'message' => 'Validation failed',
        'errors' => $e->errors(),
    ], 422);
    
} catch (\Exception $e) {
    \Log::error('Trade error: ' . $e->getMessage());
    return response()->json([
        'success' => false,
        'message' => 'An error occurred',
    ], 500);
}
```

### Frontend Error Display
```javascript
try {
    const response = await fetch(url, options);
    const data = await response.json();
    
    if (data.success) {
        // Success
        successMessage = data.message;
    } else {
        // Error from API
        errorMessage = data.message;
    }
} catch (error) {
    // Network or parse error
    errorMessage = 'Error: ' + error.message;
} finally {
    isLoading = false;
}
```

---

## 8. Email Template Variables

### Available in trade-opened.blade.php
```php
// User variables
$user->id
$user->name
$user->username
$user->email
$user->balance

// Trade variables
$trade->id
$trade->trade_id          // UUID
$trade->instrument_symbol // BTC/USD
$trade->instrument_name   // Bitcoin
$trade->amount            // 500.00
$trade->entry_price       // 113692.00
$trade->trade_type        // buy/sell
$trade->hours             // 24
$trade->status            // open/closed
$trade->opened_at         // Timestamp
$trade->expires_at        // Timestamp
```

---

## 9. API Response Examples

### Successful Trade Placement
```json
HTTP/1.1 200 OK
Content-Type: application/json

{
  "success": true,
  "message": "Trade placed successfully!",
  "trade": {
    "id": 123,
    "trade_id": "550e8400-e29b-41d4-a716-446655440000",
    "symbol": "BTC/USD",
    "amount": 500.00,
    "type": "buy",
    "expires_at": "2026-03-03 15:30:00"
  },
  "new_balance": 2500.00
}
```

### Validation Error
```json
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "success": false,
  "message": "Validation failed",
  "errors": {
    "amount": [
      "The amount field is required."
    ],
    "hours": [
      "The hours must be at least 1."
    ]
  }
}
```

### Insufficient Balance
```json
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "success": false,
  "message": "Insufficient balance. Not enough money in your trading account.",
  "balance": 2000.00,
  "required": 5000.00
}
```

### Server Error
```json
HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
  "success": false,
  "message": "An error occurred: Database connection failed"
}
```

---

## 10. Testing Examples

### Manual Testing in Tinker
```php
php artisan tinker

// Create test user with balance
$user = User::find(1);
$user->balance = 5000;
$user->save();

// Create test trade
$trade = Trade::create([
    'trade_id' => Str::uuid(),
    'user_id' => 1,
    'instrument_id' => 1,
    'instrument_name' => 'Bitcoin',
    'instrument_symbol' => 'BTC/USD',
    'amount' => 500,
    'entry_price' => 113692,
    'trade_type' => 'buy',
    'status' => 'open',
    'hours' => 24,
    'expires_at' => now()->addHours(24),
    'opened_at' => now(),
]);

// Query trades
Trade::where('user_id', 1)->get();

// Send test email
Mail::to('admin@example.com')->send(new TradeOpenMail($trade, $user));
```

### Unit Test Example
```php
public function test_user_can_place_trade()
{
    $user = User::factory()->create(['balance' => 5000]);
    $this->actingAs($user);
    
    $response = $this->postJson('/trade/place', [
        'instrument_id' => 1,
        'instrument_name' => 'Bitcoin',
        'instrument_symbol' => 'BTC/USD',
        'amount' => 500,
        'hours' => 24,
        'trade_type' => 'buy',
        'entry_price' => 113692,
    ]);
    
    $response->assertSuccessful();
    $this->assertDatabaseHas('trades', ['user_id' => $user->id]);
    $this->assertEquals(4500, $user->refresh()->balance);
}
```

---

**Last Updated:** March 2, 2026
**Status:** Complete ✅
