# Admin Trade Control - Quick Reference

## 🎯 What It Does

Allows **admin users** to pause and resume auto-trading from the dashboard.

- **When PAUSED**: No new trade entries are placed
- **When RUNNING**: Normal auto-trading resumes
- **Always**: Existing positions continue to be managed (exits, SL, TP)

---

## 🔐 Security

| Check | Implementation |
|-------|----------------|
| Authentication | All endpoints require valid JWT token |
| Authorization | Pause/Resume require `role = 'admin'` |
| UI Guards | Controls hidden for non-admin users |
| Audit Logs | All actions logged with user and reason |

---

## 📡 API Endpoints

### Get Status
```bash
GET /internal/trading/status
Authorization: Bearer <token>

Response:
{
  "mode": "RUNNING",
  "lastChangedBy": "admin@example.com",
  "lastChangedAt": 1708200000000,
  "reason": "Manual resume"
}
```

### Pause Trading
```bash
POST /internal/trading/pause
Authorization: Bearer <admin-token>
Content-Type: application/json

{
  "reason": "Market volatility"
}

Response:
{
  "success": true,
  "status": { "mode": "PAUSED", ... }
}
```

### Resume Trading
```bash
POST /internal/trading/resume
Authorization: Bearer <admin-token>
Content-Type: application/json

{
  "reason": "Conditions normalized"
}

Response:
{
  "success": true,
  "status": { "mode": "RUNNING", ... }
}
```

---

## 🖥️ UI Components

### Header Badge (All Pages)
```
┌─────────────────────────┐
│ ⏸️ Trading Paused       │  ← Orange when paused
│ No new entries          │
└─────────────────────────┘

┌─────────────────────────┐
│ ▶️ Trading Active       │  ← Green when running
│ Entries allowed         │
└─────────────────────────┘
```

### Admin Tab Controls
```
Trading Control
┌───────────────────────────────────────────┐
│ AUTO-TRADING: PAUSED                      │
│ No new positions will be opened.          │
│ Existing positions are still managed.     │
│                                           │
│ Last Changed: 2026-02-17 5:30 PM          │
│ by admin@example.com                      │
└───────────────────────────────────────────┘

┌──────────────────┐  ┌──────────────────────┐
│ ⏸️ Pause Auto    │  │ ▶️ Resume Auto       │
│    Trading       │  │    Trading           │
│ (disabled)       │  │ (enabled)            │
└──────────────────┘  └──────────────────────┘

⚠️ Safety Note: Pausing blocks new entries only.
   Existing positions continue to be managed.
```

---

## 🔧 Code Integration

### Check if Paused
```typescript
import { healthTracker } from './services/healthTracker';

if (healthTracker.isPaused()) {
    logger.info('Entry blocked: Trading is paused');
    return;
}
```

### Programmatic Control
```typescript
// Pause
healthTracker.recordTradingControl({
    mode: 'PAUSED',
    lastChangedBy: 'system',
    lastChangedAt: Date.now(),
    reason: 'Automated safety pause'
});

// Resume
healthTracker.recordTradingControl({
    mode: 'RUNNING',
    lastChangedBy: 'system',
    lastChangedAt: Date.now(),
    reason: 'Conditions normalized'
});
```

---

## 🛡️ Enforcement Points

| File | Line | What It Does |
|------|------|--------------|
| `AutoTrader.ts` | 106-109 | Blocks new entries when paused |
| `TradeExecutor.ts` | 531-534 | Blocks openPosition when paused |

**What Continues:**
- ✅ Exit orders
- ✅ Stop-loss monitoring
- ✅ Take-profit monitoring
- ✅ Position reconciliation
- ✅ Order status sync

---

## 💾 State Persistence

```
In-Memory (HealthTracker)
    ↓
Disk (bot_state.json)
    ↓
Database (Supabase)
```

**On Restart:**
1. Load from Supabase (preferred)
2. Fallback to `bot_state.json`
3. Default to `RUNNING` if not found

---

## 🧪 Testing Checklist

### Backend
- [ ] Pause blocks new entries
- [ ] Resume allows new entries
- [ ] Existing positions continue when paused
- [ ] State persists across restart
- [ ] Non-admin gets 403

### Frontend
- [ ] Pause button disabled when paused
- [ ] Resume button disabled when running
- [ ] Header badge shows correct status
- [ ] Error displayed on API failure
- [ ] Loading state shown during API call

---

## 📊 Monitoring

### Metrics to Track
- Pause/resume event count
- Blocked entry attempts while paused
- Pause duration (time between pause/resume)
- Who paused (user tracking)

### Alerts
- Trading paused > 1 hour
- Multiple pause/resume cycles in short time
- Pause during high volatility

---

## 🚨 Troubleshooting

### Issue: Pause button not working
**Check:**
1. User has `role = 'admin'` in profile
2. Valid JWT token in request
3. Backend logs for errors
4. Network tab for API response

### Issue: Status not updating in UI
**Check:**
1. WebSocket connection active
2. `health_update` events received
3. Browser console for errors
4. Refresh page to force sync

### Issue: Entries still being placed when paused
**Check:**
1. Backend logs show pause enforcement
2. `healthTracker.isPaused()` returns true
3. AutoTrader/TradeExecutor checking pause state
4. No cached state in trading loop

### Issue: State lost after restart
**Check:**
1. `bot_state.json` exists and readable
2. Supabase connection working
3. `loadState()` called on startup
4. Logs show state restoration

---

## 📚 Documentation Files

| File | Purpose |
|------|---------|
| `ADMIN_TRADE_CONTROL_SUMMARY.md` | Executive summary |
| `ADMIN_TRADE_CONTROL_IMPLEMENTATION.md` | Full implementation guide |
| `ADMIN_TRADE_CONTROL_TEST_PLAN.md` | Testing requirements |
| `ADMIN_TRADE_CONTROL_ARCHITECTURE.md` | Visual diagrams |
| `ADMIN_TRADE_CONTROL_QUICK_REF.md` | This quick reference |

---

## ✅ Pre-Production Checklist

- [ ] All backend unit tests pass
- [ ] All frontend component tests pass
- [ ] Integration tests pass
- [ ] Manual testing completed
- [ ] Security review completed
- [ ] Documentation reviewed
- [ ] Audit logging verified
- [ ] State persistence verified
- [ ] Error handling verified
- [ ] UI/UX reviewed

---

## 🎉 Quick Start

### For Admins
1. Login as admin user
2. Go to Admin tab (🛡️)
3. Find "Trading Control" section
4. Click "Pause" or "Resume"
5. Check header badge for status

### For Developers
1. Read `ADMIN_TRADE_CONTROL_IMPLEMENTATION.md`
2. Review enforcement points in code
3. Run test suite
4. Deploy to staging
5. Verify functionality
6. Deploy to production

---

## 🔗 Related Systems

- **Health Tracker**: Stores trading control state
- **API Server**: Exposes control endpoints
- **AutoTrader**: Enforces pause on entries
- **TradeExecutor**: Enforces pause on openPosition
- **WebSocket**: Broadcasts state updates
- **Dashboard**: Displays status and controls

---

## 📞 Support

**Issues?** Check:
1. Backend logs: `bytelyst-trading-bot-service/logs/`
2. Frontend console: Browser DevTools
3. API responses: Network tab
4. State file: `bot_state.json`

**Questions?** See:
- Implementation guide
- Test plan
- Architecture diagram
