# Trading Modal Implementation - Complete Guide

## Overview
A complete trading modal system has been implemented that allows users to open trades on various instruments. The system includes balance validation, trade notifications, and admin email alerts.

---

## Files Created

### 1. **TradeController** 
**Location:** `core/app/Http/Controllers/TradeController.php`

**Key Features:**
- `store()` - Places new trades with balance validation
- `close()` - Closes open trades manually
- `history()` - Retrieves user's trade history

**Functionality:**
- Validates user input (amount, hours, trade type)
- Checks user balance before allowing trade
- Deducts trade amount from user balance
- Creates notification for user
- Sends email notification to admin
- Stores complete trade details in database

**Error Handling:**
- Insufficient balance validation
- Validation exceptions with detailed error messages
- Logging of all errors for debugging

---

## Files Modified

### 1. **Trade Model** 
**Location:** `core/app/Models/Trade.php`

**Added Fields:**
- `trade_type` - Buy or Sell
- `opened_at` - Trade opening timestamp
- `closed_at` - Trade closing timestamp
- `profit_loss` - Calculated profit or loss

**Updated Casts:**
- `opened_at` → datetime
- `closed_at` → datetime
- `profit_loss` → decimal:2

---

### 2. **Live Dashboard View**
**Location:** `core/resources/views/dashboard/live.blade.php`

**Components Added:**
- Trade button for each instrument
- Complete trading modal with:
  - Instrument details display (name, symbol, price, 24h change)
  - User balance display
  - Amount input field (with $ prefix)
  - Trading hours selector (1-720 hours with +/- buttons)
  - Buy/Sell toggle buttons
  - Trade summary display
  - Error and success messages
  - Loading state during submission

**Alpine.js Data Properties:**
```javascript
showTradeModal: false,
selectedInstrument: null,
tradeForm: { hours: 1, amount: '', tradeType: 'buy' },
isLoading: false,
errorMessage: '',
successMessage: '',
userBalance: (from database)
```

**Alpine.js Methods:**
- `openTradeModal(instrument)` - Opens modal with selected instrument
- `placeTrade()` - Validates and submits trade to backend

---

### 3. **Routes**
**Location:** `core/routes/dashboard.php`

**New Routes Added:**
```php
Route::post('/trade/place', [TradeController::class, 'store'])
    ->name('trade.place');

Route::get('/trade/history', [TradeController::class, 'history'])
    ->name('trade.history.api');

Route::post('/trade/close/{tradeId}', [TradeController::class, 'close'])
    ->name('trade.close');
```

---

### 4. **TradeOpenNotification**
**Location:** `core/app/Notifications/TradeOpenNotification.php`

**Updated to use database channel:**
- Sends notification to database (user's notification table)
- Includes trade details (ID, symbol, type, amount, entry price, expiry time)

---

### 5. **Email Templates**
**Location:** `core/resources/views/emails/admin/trade-opened.blade.php`

**Updated with Trade model data:**
- User information (name, username, email, balance)
- Trade details (symbol, name, amount, entry price, type, duration)
- Trade status and timestamps
- Admin action recommendations
- Direct link to admin panel

---

## New Files Created

### 1. **TradeOpenMail Class**
**Location:** `core/app/Mail/TradeOpenMail.php`

```php
public function __construct($trade, $user)
public function build()
```

**Features:**
- Formats subject with user name, symbol, and amount
- Passes trade and user data to template
- Automatically sent when trade is placed

---

## How It Works

### User Places a Trade:

1. **User clicks "Trade" button** on an instrument
2. **Modal opens** with:
   - Current instrument price
   - 24h change percentage
   - User's available balance
   
3. **User fills in:**
   - Amount to invest ($ amount)
   - Trading hours (1-720)
   - Trade type (Buy/Sell)

4. **Modal shows summary:**
   - Trade amount
   - Duration
   - Entry price

5. **User clicks "Place Trade"**

### Backend Processing:

1. **Validates data:**
   - Amount > 0
   - Amount < user balance
   - All required fields present

2. **If validation fails:**
   - Returns error message to modal
   - User can correct and retry

3. **If validation passes:**
   - Creates Trade record with:
     - UUID (trade_id)
     - User ID
     - Instrument details
     - Amount and price
     - Status: 'open'
     - Expiration time (now + hours)
   
4. **Deducts amount from user balance**

5. **Creates notification:**
   - Message: "Your {type} trade on {symbol} for ${amount} has been opened"
   - Status: UNREAD

6. **Sends email to admin:**
   - Detailed trade information
   - User account details
   - Action recommendations

7. **Returns success response:**
   - New trade ID
   - Updated user balance
   - Success message displays in modal

8. **Modal closes after 2 seconds**

---

## Database Requirements

### Ensure Trade table has these columns:

```sql
- id (primary key)
- trade_id (UUID, unique)
- user_id (foreign key)
- instrument_id (integer)
- instrument_name (string)
- instrument_symbol (string)
- amount (decimal)
- entry_price (decimal)
- exit_price (decimal, nullable)
- trade_type (enum: 'buy', 'sell')
- status (enum: 'open', 'closed')
- hours (integer)
- opened_at (timestamp)
- closed_at (timestamp, nullable)
- expires_at (timestamp)
- profit_loss (decimal, nullable)
- notes (text, nullable)
- created_at (timestamp)
- updated_at (timestamp)
```

If migration doesn't exist, create:
```bash
php artisan make:migration add_trading_fields_to_trades_table
```

---

## Error Messages Displayed to User

1. **"Insufficient balance. Not enough money in your trading account."**
   - Amount exceeds user balance

2. **"Please enter a valid amount"**
   - Amount is 0 or negative

3. **"Instrument not selected"**
   - System error in modal

4. **Validation errors with specific field details**
   - From server-side validation

---

## Admin Email Contains

- ✅ User's full name and username
- ✅ User's email address
- ✅ Current account balance
- ✅ Trade pair (symbol)
- ✅ Instrument name
- ✅ Entry amount in USD
- ✅ Entry price
- ✅ Trade type (BUY/SELL)
- ✅ Trading duration (hours)
- ✅ Exact timestamps (opened, expires)
- ✅ Unique trade ID
- ✅ Recommended actions for monitoring
- ✅ Link to admin panel

---

## Frontend Features

### Modal UI:
- ✅ Responsive design (mobile & desktop)
- ✅ Dark mode support
- ✅ Real-time price display
- ✅ 24h change percentage with color coding
- ✅ User balance display
- ✅ Amount input with currency prefix
- ✅ Hours selector with increment/decrement buttons
- ✅ Buy/Sell toggle buttons (color coded: green/red)
- ✅ Trade summary box
- ✅ Error messages (red alert box)
- ✅ Success messages (green alert box)
- ✅ Loading spinner during submission
- ✅ Disabled submit button when loading or no amount

### Interactions:
- Click trade button → Modal opens with instrument data
- Enter amount → Summary updates
- Adjust hours → Summary updates
- Click Buy/Sell → Toggle selection
- Click "Place Trade" → Submit with loading state
- Success → Close after 2 seconds
- Error → Show message, allow retry

---

## Security Features

✅ CSRF token validation (included in request header)
✅ Authentication required (middleware)
✅ Balance validation before trade placement
✅ Input validation on both frontend and backend
✅ Exception handling and logging
✅ Database transactions for data consistency

---

## Testing the Implementation

### Step 1: Access Dashboard
Navigate to: `/user/live/trade` or `/dashboard`

### Step 2: Find an Instrument
Search for an instrument or scroll through categories

### Step 3: Click Trade Button
Opens trading modal with instrument details

### Step 4: Enter Trade Details
- Enter amount (must be less than balance)
- Select hours (1-720)
- Choose Buy or Sell

### Step 5: Submit
Click "Place Trade" button

### Step 6: Verify
- Check for success message
- Balance should be updated
- Admin should receive email notification
- Trade should appear in history

---

## API Endpoints

### Place Trade
```
POST /trade/place
Headers: X-CSRF-Token
Body: {
  instrument_id: number,
  instrument_name: string,
  instrument_symbol: string,
  amount: number,
  hours: number,
  trade_type: 'buy'|'sell',
  entry_price: number
}
```

### Get Trade History
```
GET /trade/history
Response: Paginated list of user's trades
```

### Close Trade
```
POST /trade/close/{tradeId}
Body: {
  exit_price: number
}
```

---

## Troubleshooting

**Modal doesn't open:**
- Check browser console for errors
- Verify Alpine.js is loaded
- Ensure x-cloak is working

**Trade not saving:**
- Check database migrations are run
- Verify Trade model is correct
- Check server logs for errors

**Email not sending:**
- Verify MAIL_* environment variables
- Check admin email configuration
- Test mail in tinker: `Mail::fake()`

**Balance not updating:**
- Verify user exists in database
- Check balance column in users table
- Verify transaction is committed

---

## Future Enhancements

- [ ] Add trade profit/loss calculation on close
- [ ] Implement automatic trade closure on expiry
- [ ] Add real-time price updates via WebSocket
- [ ] Add stop-loss and take-profit levels
- [ ] Add trade chart visualization
- [ ] Implement copy trading from this trade
- [ ] Add trade notifications at price levels
- [ ] Export trade history to CSV

---

**Implementation Date:** March 2, 2026
**Status:** ✅ Complete and Ready for Testing
