# Position Assistant - Integration Example

## Quick Integration

Add the Position Assistant to your trading interface in 3 steps:

### Step 1: Import the Component
```tsx
// In your App.tsx or main trading view
import PositionAssistant from './components/PositionAssistant';
```

### Step 2: Add to Your Layout
```tsx
function TradingView() {
  return (
    <div className="container mx-auto p-4">
      {/* Your existing components */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
        <ManualTradeLogger />
        <DailyTradingPlan />
      </div>
      
      {/* Add Position Assistant */}
      <div className="mb-4">
        <PositionAssistant refreshInterval={10000} />
      </div>
      
      {/* Other components */}
      <TradingPerformanceChart />
    </div>
  );
}
```

### Step 3: Start Backend & Frontend
```bash
# Terminal 1: Start backend
cd backend
./start.sh

# Terminal 2: Start frontend  
cd frontend
npm run dev
```

## Live Demo

### Test with Your Scenario
1. Open the app at `http://localhost:5173`
2. Scroll to "Position Assistant" section
3. Enter your position:
   - **Direction:** SHORT
   - **Entry Price:** 4070
   - **Current Price:** 4085
   - **Stop Loss:** 4109
   - **Quantity:** 1.0
4. Click **"Get Mitigation Plan"**

### What You'll See
```
🛡️ Position Assistant
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

⚠️ AT RISK                    -$15.00
   6.8 hours in trade          -0.37%

Distance to Stop Loss: $24.00
█████░░░░░░░░░░░░░░░░░░░░░░░░ 0.59%

💡 Consider closing 50% at break-even to reduce risk

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 NEXT ACTIONS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
• Primary: Close 50% of position at $4070.00
• Watch for reversal at $4008.95 (End of day)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🛡️ MITIGATION STRATEGIES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

[LOW RISK] Break-Even Exit (Partial)
Close 50% of position at $4070.00
💡 Reduces exposure while keeping upside potential
✅ Cuts risk by 50%, frees up margin

[MEDIUM RISK] Scale Out Gradually
Close 25% now, 25% at $4070, keep 50%
💡 Balanced approach between risk reduction and profit
✅ Reduces emotional pressure, maintains upside

... (3 more strategies)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔮 PREDICTED REVERSAL ZONES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

$4008.95    [70% probability]    End of day
Estimated previous day low - strong support
[Daily Support] [Psychological Level]

$4079.27    [65% probability]    2-4 hours
38.2% Fibonacci retracement
[Fibonacci 38.2%]

... (1 more zone)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ OPTIMAL EXIT PLAN
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Level 1: Close 100% at $4008.95
         High probability reversal zone

Level 2: Close 50% at $4079.27
         Quick bounce opportunity

[← Edit Position]  [🔄 Refresh Analysis]
```

## Auto-Refresh Feature

Enable the checkbox to get real-time updates every 10 seconds:
```
[✓] Auto-refresh (10s)
```

As the price moves, you'll see:
- P&L updating in real-time
- Status changing (HEALTHY → AT_RISK → CRITICAL)
- Distance to stop loss shrinking/growing
- New alerts appearing

## API Testing (Alternative)

If you want to test the API directly without the UI:

```bash
curl -X POST 'http://localhost:8000/api/position-assistant/analyze?current_price=4085' \
  -H 'Content-Type: application/json' \
  -d '{
    "symbol": "XAU/USD",
    "direction": "SHORT",
    "entry_price": 4070,
    "quantity": 1.0,
    "stop_loss": 4109,
    "entry_time": "2025-11-24T10:00:00Z"
  }'
```

Response:
```json
{
  "health": {
    "status": "AT_RISK",
    "current_pnl": -15.0,
    ...
  },
  "mitigation_strategies": [ ... ],
  "reversal_zones": [ ... ],
  ...
}
```

## Browser Notifications (Future Enhancement)

To get alerts when position becomes CRITICAL, you can add:

```tsx
// In PositionAssistant.tsx
useEffect(() => {
  if (plan?.health.status === 'CRITICAL') {
    if ('Notification' in window && Notification.permission === 'granted') {
      new Notification('Position Alert!', {
        body: 'Your position is CRITICAL - immediate action needed',
        icon: '/alert-icon.png'
      });
    }
  }
}, [plan?.health.status]);
```

## Styling Notes

The component uses Tailwind CSS classes matching your existing design:
- `.card` - Main container
- `.input` - Input fields
- Background colors match dark theme
- Status colors: green (WINNING), blue (HEALTHY), amber (AT_RISK), red (CRITICAL)

## Mobile Responsiveness

Component is responsive with:
- Grid layouts that stack on mobile
- Readable text sizes
- Touch-friendly buttons

Test on mobile by opening DevTools → Device Toolbar.

## Tips for Best Experience

1. **Keep Backend Running**: Make sure `./start.sh` is active
2. **Enable Auto-Refresh**: For active positions, let it update automatically
3. **Set Browser Alerts**: Get notified when you need to act
4. **Use Alongside Daily Plan**: Position Assistant + Live Dashboard = complete monitoring

## Troubleshooting

**Component not showing?**
- Check console for import errors
- Verify backend is running on port 8000
- Check CORS settings in backend/app/main.py

**Styles look wrong?**
- Ensure Tailwind CSS is configured
- Check that dark theme classes are available
- Review existing component styles for consistency

**API errors?**
- Verify backend is running: `curl http://localhost:8000/docs`
- Check browser console for network errors
- Ensure prices are valid numbers

## Next Steps

1. ✅ Add component to your main trading view
2. ✅ Test with your current position
3. ✅ Execute a mitigation strategy
4. ✅ Compare results to "just holding"
5. ✅ Build confidence in systematic risk management

**Ready to use!** The Position Assistant is fully functional and waiting to help you manage your trades intelligently.
