## 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!
141 lines
3.6 KiB
TypeScript
141 lines
3.6 KiB
TypeScript
'use client';
|
|
|
|
import { useState, useEffect, useCallback } from 'react';
|
|
import { api } from '@/lib/apiClient';
|
|
import useWebSocket from '@/lib/useWebSocket';
|
|
|
|
interface BotState {
|
|
dex: {
|
|
status: 'RUNNING' | 'STOPPED' | 'ERROR';
|
|
lastTrade: number | null;
|
|
balance: number;
|
|
config: {
|
|
maxTradeAmount: number;
|
|
confidenceThreshold: number;
|
|
stopLoss: number;
|
|
maxSlippage: number;
|
|
};
|
|
};
|
|
polymarket: {
|
|
status: 'RUNNING' | 'STOPPED' | 'ERROR';
|
|
lastTrade: number | null;
|
|
config: {
|
|
maxBetAmount: number;
|
|
confidenceThreshold: number;
|
|
maxSlippage: number;
|
|
};
|
|
};
|
|
websocket: {
|
|
connected: number;
|
|
status: string;
|
|
};
|
|
}
|
|
|
|
export function useBot() {
|
|
const [botState, setBotState] = useState<BotState | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [starting, setStarting] = useState(false);
|
|
const [stopping, setStopping] = useState(false);
|
|
|
|
const { botStatus: wsBotStatus, isConnected: wsConnected } = useWebSocket();
|
|
|
|
// Fetch bot status
|
|
const fetchStatus = useCallback(async () => {
|
|
try {
|
|
setError(null);
|
|
const data = await api.getBotStatus();
|
|
setBotState(data as any);
|
|
} catch (err: any) {
|
|
console.error('Failed to fetch bot status:', err);
|
|
setError(err.message || 'Failed to fetch bot status');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
// Auto-refresh
|
|
useEffect(() => {
|
|
fetchStatus();
|
|
const interval = setInterval(fetchStatus, 10000); // Every 10s
|
|
return () => clearInterval(interval);
|
|
}, [fetchStatus]);
|
|
|
|
// Update from WebSocket
|
|
useEffect(() => {
|
|
if (wsBotStatus && botState) {
|
|
setBotState((prev) => ({
|
|
...prev!,
|
|
dex: { ...prev!.dex, status: wsBotStatus.dex.status as any },
|
|
polymarket: { ...prev!.polymarket, status: wsBotStatus.polymarket.status as any },
|
|
}));
|
|
}
|
|
}, [wsBotStatus, botState]);
|
|
|
|
// Start bot
|
|
const startBot = useCallback(async (type: 'dex' | 'polymarket' | 'all') => {
|
|
try {
|
|
setStarting(true);
|
|
setError(null);
|
|
const result = await api.startBot(type);
|
|
|
|
if (result.success) {
|
|
await fetchStatus();
|
|
return { success: true, message: result.message };
|
|
}
|
|
|
|
throw new Error(result.message || 'Failed to start bot');
|
|
} catch (err: any) {
|
|
const errorMsg = err.message || 'Failed to start bot';
|
|
setError(errorMsg);
|
|
return { success: false, message: errorMsg };
|
|
} finally {
|
|
setStarting(false);
|
|
}
|
|
}, [fetchStatus]);
|
|
|
|
// Stop bot
|
|
const stopBot = useCallback(async (type: 'dex' | 'polymarket' | 'all') => {
|
|
try {
|
|
setStopping(true);
|
|
setError(null);
|
|
const result = await api.stopBot(type);
|
|
|
|
if (result.success) {
|
|
await fetchStatus();
|
|
return { success: true, message: result.message };
|
|
}
|
|
|
|
throw new Error(result.message || 'Failed to stop bot');
|
|
} catch (err: any) {
|
|
const errorMsg = err.message || 'Failed to stop bot';
|
|
setError(errorMsg);
|
|
return { success: false, message: errorMsg };
|
|
} finally {
|
|
setStopping(false);
|
|
}
|
|
}, [fetchStatus]);
|
|
|
|
// Check if bot is running
|
|
const isDexRunning = botState?.dex?.status === 'RUNNING';
|
|
const isPolymarketRunning = botState?.polymarket?.status === 'RUNNING';
|
|
const isAnyRunning = isDexRunning || isPolymarketRunning;
|
|
|
|
return {
|
|
botState,
|
|
loading,
|
|
error,
|
|
starting,
|
|
stopping,
|
|
isDexRunning,
|
|
isPolymarketRunning,
|
|
isAnyRunning,
|
|
wsConnected,
|
|
startBot,
|
|
stopBot,
|
|
refresh: fetchStatus,
|
|
};
|
|
}
|
|
|
|
export default useBot;
|