# Migration Guide: PyQt6 to Web Architecture

This guide explains the migration from PyQt6 desktop application to web-based architecture.

## Overview

The application has been migrated from a PyQt6 desktop app to a modern web-based architecture while preserving 90% of the existing Python backend code.

## What Changed

### Architecture

**Before (PyQt6)**:
```
PyQt6 UI → Direct Python calls → Services → Database
```

**After (Web)**:
```
React UI → HTTP/WebSocket → FastAPI → Services → Database
```

### Code Structure

**Before**:
```
crypto_trader/
├── src/
│   ├── ui/          # PyQt6 widgets
│   ├── trading/     # Trading engine
│   ├── strategies/  # Strategy framework
│   └── ...
└── packaging/       # AppImage build
```

**After**:
```
crypto_trader/
├── backend/         # FastAPI application
│   ├── api/        # API endpoints
│   └── core/       # Dependencies, schemas
├── frontend/        # React application
│   └── src/
│       ├── pages/  # Page components
│       ├── api/    # API client
│       └── ...
├── src/            # Existing Python code (unchanged)
└── docker-compose.yml
```

## What Was Preserved

### 100% Preserved (No Changes)

- `src/trading/engine.py` - Trading engine
- `src/strategies/` - Strategy framework
- `src/portfolio/` - Portfolio tracker
- `src/backtesting/` - Backtesting engine
- `src/risk/` - Risk management
- `src/data/` - Data collection
- `src/exchanges/` - Exchange integrations
- `src/core/database.py` - Database models
- All business logic

### What Was Replaced

- **UI Layer**: PyQt6 widgets → React components
- **Communication**: Direct function calls → HTTP API
- **Real-time Updates**: Signal/slot → WebSocket
- **Deployment**: AppImage → Docker

## Migration Steps

### 1. API Layer Creation

Created FastAPI application that wraps existing services:

```python
# backend/api/trading.py
@router.post("/orders")
async def create_order(order_data: OrderCreate):
    # Uses existing trading_engine.execute_order()
    order = trading_engine.execute_order(...)
    return OrderResponse.from_orm(order)
```

### 2. Frontend Development

Created React frontend with:
- Material-UI for modern components
- React Query for data fetching
- TypeScript for type safety
- WebSocket for real-time updates

### 3. Docker Deployment

Created Docker setup for easy deployment:
- Multi-stage build (frontend + backend)
- Single container deployment
- Volume mounts for data persistence

## Running the New Architecture

### Development

1. **Backend**:
   ```bash
   cd backend
   python -m uvicorn main:app --reload
   ```

2. **Frontend**:
   ```bash
   cd frontend
   npm install
   npm run dev
   ```

### Production

```bash
docker-compose up --build
```

Access at: http://localhost:8000

## API Endpoints

All functionality is now available via REST API:

- **Trading**: `/api/trading/*`
- **Portfolio**: `/api/portfolio/*`
- **Strategies**: `/api/strategies/*`
- **Backtesting**: `/api/backtesting/*`
- **WebSocket**: `/ws/` for real-time updates

See API documentation at: http://localhost:8000/docs

## Key Differences

### UI Development

**Before (PyQt6)**:
```python
# Complex QSS styling
self.setStyleSheet("""
    QPushButton {
        background-color: #1E1E1E;
        ...
    }
""")
```

**After (React)**:
```tsx
// Modern CSS-in-JS
<Button variant="contained" color="primary">
  Place Order
</Button>
```

### Data Fetching

**Before (PyQt6)**:
```python
# Direct function calls
order = trading_engine.execute_order(...)
```

**After (React)**:
```tsx
// API calls with React Query
const { data } = useQuery({
  queryKey: ['orders'],
  queryFn: () => tradingApi.getOrders()
})
```

### Real-time Updates

**Before (PyQt6)**:
```python
# Signal/slot connections
collector.signals.price_updated.connect(self._on_price_update)
```

**After (React)**:
```tsx
// WebSocket hook
const { lastMessage } = useWebSocket('ws://localhost:8000/ws/')
```

## Benefits

1. **Modern UI**: Access to entire web ecosystem
2. **Cross-platform**: Works on any device
3. **Easier deployment**: Docker vs AppImage
4. **Better development**: Hot-reload, better tooling
5. **Maintainability**: Easier to update
6. **Accessibility**: Access from anywhere

## Backward Compatibility

The existing Python code remains unchanged. You can still:
- Import and use services directly
- Run existing tests
- Use the code in other projects

## Next Steps

1. Add authentication (JWT)
2. Enhance WebSocket integration
3. Add more charting features
4. Improve mobile responsiveness
5. Add more strategy management features

## Support

For issues or questions:
- Check API docs: http://localhost:8000/docs
- Review deployment guide: `docs/deployment/web_architecture.md`
- Check backend logs: `docker-compose logs`
