# Trading Modal - Quick Reference Guide

## User Workflow

### Opening a Trade

1. **Navigate to Trading Dashboard**
   - URL: `/user/live/trade` or `/dashboard`

2. **Search or Browse Instruments**
   - Use search bar to find specific instruments
   - Filter by type: Crypto, Stocks, Forex, Commodities, Bonds

3. **Click "Trade" Button**
   - Each instrument has a blue "Trade" button with trending-up icon
   - Modal opens with instrument details

4. **Modal Displays**
   - **Current Price** - Live trading price
   - **24h Change** - Percentage change (green if positive, red if negative)
   - **Your Balance** - Available trading balance

5. **Fill Trade Form**
   - **Amount to Invest ($)** - Enter amount (must be ≤ balance)
   - **Trading Hours** - Use +/- buttons or type (1-720 hours)
   - **Select Trade Type** - Click BUY (green, ↑) or SELL (red, ↓)

6. **Review Trade Summary**
   - Shows: Amount, Duration, Entry Price
   - Verify details are correct

7. **Click "Place Trade" Button**
   - Button shows loading spinner during submission
   - Will be disabled if no amount entered

8. **View Result**
   - **Success:** Green alert with Trade ID, modal closes after 2 seconds
   - **Error:** Red alert with error message, can retry

9. **Check Notifications**
   - New notification in user's notification center
   - Admin receives email with trade details

---

## Form Validation

### Client-Side (Immediate)
- Amount cannot be empty
- Amount must be a valid number
- Amount must be less than or equal to balance

### Server-Side (Before Saving)
- Amount must be ≥ $0.01
- Hours must be between 1-720
- Trade type must be 'buy' or 'sell'
- Instrument ID must be valid
- User balance must be sufficient

---

## Error Messages & Solutions

| Error Message | Cause | Solution |
|---|---|---|
| "Insufficient balance. Not enough money in your trading account." | Amount > user balance | Enter a smaller amount or deposit more funds |
| "Please enter a valid amount" | Amount is 0, negative, or not a number | Enter a positive decimal amount |
| "Validation failed" | Missing or invalid field data | Check all fields are filled correctly |
| "An error occurred..." | Server error | Contact support, check browser console for details |

---

## Modal Sections Breakdown

### Header (Blue Gradient)
- Instrument logo/icon
- Instrument name
- Instrument symbol
- Close (X) button

### Pair Details Row
- **Current Price** - Real-time trading price
- **24h Change** - Percentage with up/down indicator
- **Your Balance** - Account balance in USD

### Trade Form
1. **Amount Input**
   - $ currency prefix
   - Accepts decimals (e.g., 100.50)
   - Must not exceed balance

2. **Hours Selector**
   - Minus button (-) to decrease
   - Number input to type directly
   - Plus button (+) to increase
   - Range: 1-720 hours
   - Text helper showing valid range

3. **Trade Type Buttons**
   - BUY: Green background, shows when selected
   - SELL: Red background, shows when selected
   - Click to toggle between them

### Trade Summary Box
- Trade Amount (formatted with commas)
- Duration (hours)
- Entry Price (current instrument price)

### Messages Section
- **Error Message**: Red background, alert icon, shows validation or error messages
- **Success Message**: Green background, check icon, shows trade ID and success

### Footer Buttons
- **Cancel**: Gray button, closes modal without saving
- **Place Trade**: Blue button, disabled when loading or amount is empty

---

## Response Data (After Successful Trade)

The system returns:
```json
{
  "success": true,
  "message": "Trade placed successfully!",
  "trade": {
    "id": 123,
    "trade_id": "uuid-string",
    "symbol": "BTC/USD",
    "amount": 500,
    "type": "buy",
    "expires_at": "2026-03-03 15:30:00"
  },
  "new_balance": 2500.00
}
```

---

## Key Features

✅ **Real-time Price Display**
- Shows current market price
- Updates from server data

✅ **24-Hour Change Indicator**
- Green arrow up for gains
- Red arrow down for losses

✅ **Balance Validation**
- Prevents over-trading
- Protects user account

✅ **Flexible Duration**
- 1 to 720 hours (30 days maximum)
- Easy increment/decrement controls

✅ **Clear Trade Summary**
- Shows all details before submission
- Amount in USD with proper formatting

✅ **Real-time Feedback**
- Error messages in red
- Success messages in green
- Loading spinner during processing

✅ **Mobile Responsive**
- Works on phones, tablets, desktops
- Touch-friendly buttons
- Proper text sizing

✅ **Dark Mode Support**
- Adapts to user's dark/light theme preference
- Maintains readability in both modes

---

## Technical Details for Developers

### API Endpoint
```
POST /trade/place
```

### Required Headers
- `Content-Type: application/json`
- `X-CSRF-Token: {token}`

### Request Body
```json
{
  "instrument_id": 1,
  "instrument_name": "Bitcoin",
  "instrument_symbol": "BTC/USD",
  "amount": 500.50,
  "hours": 24,
  "trade_type": "buy",
  "entry_price": 113692.00
}
```

### Success Response (200 OK)
```json
{
  "success": true,
  "message": "Trade placed successfully!",
  "trade": {...},
  "new_balance": 2500.00
}
```

### Error Response (422 Unprocessable Entity)
```json
{
  "success": false,
  "message": "Insufficient balance...",
  "balance": 2000,
  "required": 5000
}
```

### Failed Validation (422)
```json
{
  "success": false,
  "message": "Validation failed",
  "errors": {
    "amount": ["The amount field is required."],
    "trade_type": ["The trade type field is invalid."]
  }
}
```

---

## Database Records Created

When a trade is successfully placed:

1. **Trade Record** (in `trades` table)
   - Stores all trade details
   - Marked as 'open' initially
   - Expires after specified hours

2. **Notification Record** (in `notifications` table)
   - User notification about trade opening
   - Marked as 'UNREAD'
   - Contains trade summary

3. **User Balance Update** (in `users` table)
   - Balance reduced by trade amount
   - Reflected immediately in next API response

4. **Email Log** (implicit via Mail system)
   - Admin email sent with full trade details
   - Email is logged for audit trail

---

## Monitoring Trades

### For Users
- View open trades in Trade History
- Check notifications for updates
- Monitor from Admin Panel (if accessible)

### For Admin
- Receives email notification immediately
- Can view all user trades in admin panel
- Can monitor position risk
- Can take action if needed

---

## Closing a Trade

### Manual Close by User
```
POST /trade/close/{tradeId}
Body: {
  "exit_price": 115000.00
}
```

### Automatic Features (Future)
- Auto-close on expiry time
- Auto-close on stop-loss
- Auto-close on take-profit

---

## Best Practices

✅ **For Users:**
- Always verify trade details before clicking "Place Trade"
- Ensure sufficient balance before attempting trade
- Note the expiration time for managing positions
- Monitor market conditions during trade duration

✅ **For Admins:**
- Review each trade notification promptly
- Check user's trading history for patterns
- Set appropriate risk limits
- Monitor total user exposure
- Ensure position sizes are appropriate

✅ **For Developers:**
- Always validate on both frontend and backend
- Use proper error handling and logging
- Test with edge cases (max amount, min amount, invalid data)
- Keep audit trail of all trades
- Monitor email delivery
- Set up alerts for large trades

---

## Contact & Support

For issues or questions about the Trading Modal:
1. Check error messages in the modal
2. Review browser console for JavaScript errors
3. Check server logs for backend errors
4. Contact system administrator

---

**Last Updated:** March 2, 2026
**Status:** Production Ready ✅
