# Quick Start Guide - Intelligent Automation System

## 🚀 Get Started in 5 Minutes

This guide will help you quickly integrate the new Smart Trade Hub and Live Performance Dashboard into your existing application.

---

## Prerequisites

- Backend running on `http://localhost:8000`
- Frontend running on `http://localhost:3000`
- Python 3.11+
- Node.js 18+

---

## Step 1: Backend Setup (2 minutes)

The backend API routes are already registered. Just restart your server:

```bash
cd backend
python -m uvicorn app.main:app --reload --port 8000
```

**Verify Backend**:
```bash
# Check health
curl http://localhost:8000/health

# Test Smart Trade Hub API
curl -X POST http://localhost:8000/api/smart-trade-hub/prefill \
  -H "Content-Type: application/json" \
  -d '{"symbol": "XAU/USD", "action": "BUY"}'

# Test Live Dashboard API
curl http://localhost:8000/api/live-dashboard/status
```

You should see JSON responses with no errors.

---

## Step 2: Frontend Integration (3 minutes)

### Option A: Quick Demo (No Code Changes)

1. Open your browser's console on the existing app
2. Import the new components directly:

```tsx
// In your browser console or a test file
import SmartTradeHub from './components/SmartTradeHub';
import LivePerformanceDashboard from './components/LivePerformanceDashboard';
```

### Option B: Full Integration

**Edit** `frontend/src/App.tsx`:

```tsx
import SmartTradeHub from './components/SmartTradeHub';
import LivePerformanceDashboard from './components/LivePerformanceDashboard';

export default function App() {
  const [currentPrice, setCurrentPrice] = useState(2034.25);
  
  return (
    <div className="app-container">
      {/* 1. Add sticky performance dashboard at the top */}
      <LivePerformanceDashboard 
        position="sticky"
        refreshInterval={5000}
        onLimitReached={() => {
          alert('⛔ Daily trading limits reached!');
        }}
      />
      
      <div className="main-content">
        {/* 2. Replace old trade entry with Smart Trade Hub */}
        <SmartTradeHub 
          currentPrice={currentPrice}
          onTradeExecuted={(trade) => {
            console.log('✅ Trade executed:', trade);
            // Refresh your portfolio, charts, etc.
            refreshPortfolio();
            refreshCharts();
          }}
        />
        
        {/* Your existing components... */}
        <LiveMarketPanel />
        <GoldChart />
        {/* etc... */}
      </div>
    </div>
  );
}
```

**Restart frontend**:
```bash
cd frontend
npm run dev
```

---

## Step 3: Test the Flow (1 minute)

### Test Smart Trade Hub

1. Open `http://localhost:3000`
2. You should see the **Smart Trade Hub** component
3. Click **"BUY"** button
4. Verify:
   - ✅ Quantity auto-fills from last trade (or defaults to 1.0)
   - ✅ Price auto-fills with current market price
   - ✅ AI guard suggestions appear (ATR-based SL/TP)
5. Click **"🟢 Execute Buy"**
6. Verify success message: "✅ Trade executed: BUY 1.0 XAU/USD @ $2034.25"

### Test Live Dashboard

1. Look at the top of the page for **"📊 Today's Performance"**
2. Verify you see:
   - Daily target progress bar
   - Max loss buffer
   - Trade count (should show 1/3 after your test trade)
3. Execute 2 more trades
4. Verify alert: **"⚠️ Only 1 trade remaining before limit"**

---

## Common Issues & Fixes

### Issue 1: "Failed to load smart suggestions"
**Cause**: Backend not running or wrong URL  
**Fix**: 
```bash
# Check backend is running
curl http://localhost:8000/health

# If not, start it:
cd backend
python -m uvicorn app.main:app --reload --port 8000
```

### Issue 2: "Unable to load performance data"
**Cause**: No trading plan configured  
**Fix**: The system creates a default plan. If you see this error, check:
```bash
curl http://localhost:8000/api/live-dashboard/status
```
You should see a plan with `target: 500, max_loss: 250, max_trades: 3`

### Issue 3: Dashboard not updating
**Cause**: Auto-refresh might be disabled  
**Fix**: Check the `refreshInterval` prop (default 5000ms). Force refresh:
```tsx
<LivePerformanceDashboard refreshInterval={5000} />
```

### Issue 4: Guards not applying
**Cause**: Smart guards toggle disabled  
**Fix**: In Smart Trade Hub, ensure the checkbox is checked:
```
✅ Apply Smart Guards (ATR-based SL/TP)
```

---

## API Reference - Quick Cheat Sheet

### Smart Trade Hub Endpoints

#### Execute Trade
```bash
POST /api/smart-trade-hub/execute
Body: {
  "action": "BUY" | "SELL" | "CLOSE",
  "symbol": "XAU/USD",
  "quantity": 1.0,          # Optional, auto-filled
  "price": 2034.25,         # Optional, uses market price
  "apply_smart_guards": true,
  "use_last_trade_defaults": true
}
```

#### Get Pre-Fill Suggestions
```bash
POST /api/smart-trade-hub/prefill?symbol=XAU/USD&action=BUY
```

#### Get Guard Suggestions
```bash
GET /api/smart-trade-hub/suggestions?symbol=XAU/USD&action=BUY&quantity=1.0
```

### Live Dashboard Endpoints

#### Get Dashboard Status
```bash
GET /api/live-dashboard/status
```

#### Get Full Widget Data
```bash
GET /api/live-dashboard/widget
```

#### Check Trading Limits
```bash
POST /api/live-dashboard/check-limits
```

#### Get Session Summary
```bash
GET /api/live-dashboard/session-summary
```

---

## Component Props Reference

### SmartTradeHub

```tsx
interface SmartTradeHubProps {
  currentPrice?: number;              // Current market price
  onTradeExecuted?: (trade: TradeResponse) => void;  // Callback after trade
}
```

### LivePerformanceDashboard

```tsx
interface LivePerformanceDashboardProps {
  refreshInterval?: number;           // Auto-refresh in ms (default: 5000)
  position?: 'sticky' | 'inline';     // Layout position (default: 'sticky')
  onLimitReached?: () => void;        // Callback when limits hit
}
```

---

## Customization Examples

### Change Default Risk Settings

Edit `backend/app/api/smart_trade_hub.py`:

```python
# Change max risk from 2% to 1%
if risk_percent > 1.0:  # Was 2.0
    adjusted_quantity = (equity * 0.01) / sl_distance  # Was 0.02
    risk_percent = 1.0  # Was 2.0
```

### Change Daily Plan Defaults

Edit `backend/app/api/live_dashboard.py`:

```python
def _get_today_plan_from_storage() -> Optional[Dict]:
    return {
        "date": date.today().isoformat(),
        "daily_target": 1000.0,  # Change from 500
        "max_loss": 500.0,        # Change from 250
        "max_trades": 5,          # Change from 3
        "bias": "NEUTRAL",
    }
```

### Change Dashboard Colors

Edit `frontend/src/components/LivePerformanceDashboard.tsx`:

```tsx
const getProgressBarColor = () => {
  if (daily_plan.actual_pnl >= daily_plan.target) return 'bg-purple-500';  // Was green
  if (daily_plan.progress_percent >= 70) return 'bg-teal-500';  // Was blue
  // ...
};
```

---

## Performance Tips

1. **Reduce Dashboard Refresh Rate** (for slower networks):
   ```tsx
   <LivePerformanceDashboard refreshInterval={10000} /> // 10 seconds
   ```

2. **Disable Smart Guards** (for manual traders):
   ```tsx
   // In SmartTradeHub, uncheck the checkbox or:
   const [useSmartGuards, setUseSmartGuards] = useState(false);
   ```

3. **Collapse Dashboard by Default**:
   ```tsx
   const [collapsed, setCollapsed] = useState(true); // In LivePerformanceDashboard
   ```

---

## Next Steps

1. ✅ **Test the basics** - Execute a few trades, see dashboard update
2. ✅ **Customize** - Adjust colors, defaults, risk settings
3. 🔜 **Phase 2** - Implement AI Daily Plan Automation
4. 🔜 **Phase 3** - Add Intelligent Risk Automation
5. 🔜 **Phase 4** - Enable Auto-Context Journaling

---

## Support

- **Backend Issues**: Check `backend/app/api/smart_trade_hub.py` and `live_dashboard.py`
- **Frontend Issues**: Check `frontend/src/components/SmartTradeHub.tsx` and `LivePerformanceDashboard.tsx`
- **Documentation**: See `INTELLIGENT_AUTOMATION_IMPLEMENTATION.md` for detailed info
- **Roadmap**: See `INTELLIGENT_AUTOMATION_ROADMAP.md` for future phases

---

## Success Checklist

- [ ] Backend running and health check passes
- [ ] Frontend displays Smart Trade Hub
- [ ] Frontend displays Live Performance Dashboard
- [ ] Can execute a BUY trade successfully
- [ ] Dashboard updates with trade count and P&L
- [ ] AI guard suggestions appear
- [ ] Dashboard shows alerts when near limits
- [ ] Can execute CLOSE trade
- [ ] Dashboard shows "target met" or "limit reached" status

Once all checked, you're ready! 🎉

---

**Quick Start Version**: 1.0  
**Last Updated**: November 24, 2025  
**Estimated Setup Time**: 5 minutes
