immortal-bnb/frontend/hooks/usePortfolio.ts
Claude a88689ffb4
feat: Add comprehensive custom React hooks for bot, portfolio, and trades management
## New Custom Hooks

### useBot Hook ()
Complete bot state management hook with:
- Real-time bot status monitoring (DEX & Polymarket)
- WebSocket integration for live updates
- Start/stop bot functionality
- Bot configuration access
- Auto-refresh every 10 seconds
- Error handling and loading states
- Helper methods: isDexRunning, isPolymarketRunning, isAnyRunning

**Features**:
- `startBot(type)` - Start DEX/Polymarket/All bots
- `stopBot(type)` - Stop bots
- `refresh()` - Manual refresh
- WebSocket status integration
- Loading and error states

### usePortfolio Hook (`frontend/hooks/usePortfolio.ts`)
Complete portfolio management hook with:
- Real-time portfolio data (DEX & Polymarket)
- Auto-refresh (configurable interval, default 30s)
- WebSocket integration for trade updates
- Calculated metrics (totalPnL, isProfitable, pnlPercentage)
- Individual balance tracking
- Manual refresh with loading state

**Features**:
- Automatic refresh on new trades
- Calculated values (totalBalance, totalPnL, pnlPercentage)
- Separate DEX and Polymarket metrics
- Error handling with retry
- WebSocket connection status

### useTrades Hook (`frontend/hooks/useTrades.ts`)
Complete trade history management hook with:
- Paginated trade history
- Real-time trade updates via WebSocket
- Flexible filtering (all/dex/polymarket)
- Sorting options (newest/profit/volume)
- Load more functionality
- Trade statistics calculation

**Features**:
- `updateFilters()` - Update filter/sort options
- `loadMore()` - Load additional trades (pagination)
- `refresh()` - Manual refresh
- Auto-add new trades from WebSocket
- Statistics: totalTrades, profitableTrades, failedTrades, avgProfit

## Benefits

These hooks provide:
1. **Reusable Logic**: Centralized data fetching and state management
2. **Type Safety**: Full TypeScript support
3. **Real-time Updates**: WebSocket integration
4. **Error Handling**: Comprehensive error states
5. **Loading States**: Proper UX feedback
6. **Auto-refresh**: Configurable intervals
7. **Manual Control**: Refresh on demand

## Usage Examples

```typescript
// Bot management
const { botState, isDexRunning, startBot, stopBot } = useBot();

// Portfolio tracking
const { portfolio, totalPnL, isProfitable, refresh } = usePortfolio();

// Trade history
const { trades, stats, loadMore, updateFilters } = useTrades();
```

All hooks are fully integrated with the backend API and WebSocket system!
2025-11-12 13:38:17 +00:00

102 lines
2.5 KiB
TypeScript

'use client';
import { useState, useEffect, useCallback } from 'react';
import { api } from '@/lib/apiClient';
import useWebSocket from '@/lib/useWebSocket';
interface Portfolio {
dex: {
balance: number;
pnl: number;
currency: string;
};
polymarket: {
balance: number;
pnl: number;
currency: string;
};
total: {
dex_bnb: number;
polymarket_usd: number;
combined_pnl: number;
};
}
export function usePortfolio(autoRefreshInterval = 30000) {
const [portfolio, setPortfolio] = useState<Portfolio | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const { lastTrade, isConnected } = useWebSocket();
// Fetch portfolio
const fetchPortfolio = useCallback(async () => {
try {
setError(null);
const data = await api.getPortfolio();
setPortfolio(data);
return data;
} catch (err: any) {
console.error('Failed to fetch portfolio:', err);
setError(err.message || 'Failed to load portfolio');
return null;
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
// Auto-refresh
useEffect(() => {
fetchPortfolio();
if (autoRefreshInterval > 0) {
const interval = setInterval(fetchPortfolio, autoRefreshInterval);
return () => clearInterval(interval);
}
}, [fetchPortfolio, autoRefreshInterval]);
// Refresh on new trade
useEffect(() => {
if (lastTrade) {
fetchPortfolio();
}
}, [lastTrade, fetchPortfolio]);
// Manual refresh
const refresh = useCallback(async () => {
setRefreshing(true);
return fetchPortfolio();
}, [fetchPortfolio]);
// Calculate metrics
const totalPnL = portfolio?.total?.combined_pnl || 0;
const isProfitable = totalPnL > 0;
const totalBalance = (portfolio?.dex?.balance || 0) + (portfolio?.polymarket?.balance || 0);
// Calculate PnL percentage
const pnlPercentage = totalBalance > 0 ? (totalPnL / totalBalance) * 100 : 0;
return {
portfolio,
loading,
error,
refreshing,
isConnected,
refresh,
// Calculated values
totalPnL,
isProfitable,
totalBalance,
pnlPercentage,
// Individual balances
dexBalance: portfolio?.dex?.balance || 0,
polymarketBalance: portfolio?.polymarket?.balance || 0,
// Individual PnLs
dexPnL: portfolio?.dex?.pnl || 0,
polymarketPnL: portfolio?.polymarket?.pnl || 0,
};
}
export default usePortfolio;