## 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!
140 lines
3.5 KiB
TypeScript
140 lines
3.5 KiB
TypeScript
'use client';
|
|
|
|
import { useState, useEffect, useCallback } from 'react';
|
|
import { api } from '@/lib/apiClient';
|
|
import useWebSocket from '@/lib/useWebSocket';
|
|
|
|
interface Trade {
|
|
id: string;
|
|
timestamp: number;
|
|
type: 'BUY' | 'SELL';
|
|
chain: 'BNB' | 'POLYGON';
|
|
tokenIn: string;
|
|
tokenOut: string;
|
|
amountIn: string;
|
|
amountOut: string;
|
|
profit?: number;
|
|
status: 'SUCCESS' | 'FAILED' | 'PENDING';
|
|
profitLoss?: number;
|
|
outcome?: string;
|
|
}
|
|
|
|
interface TradeFilters {
|
|
limit?: number;
|
|
offset?: number;
|
|
filter?: 'all' | 'dex' | 'polymarket';
|
|
sort?: 'newest' | 'profit' | 'volume';
|
|
}
|
|
|
|
export function useTrades(initialFilters?: TradeFilters) {
|
|
const [trades, setTrades] = useState<Trade[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [filters, setFilters] = useState<TradeFilters>(
|
|
initialFilters || { limit: 20, offset: 0, filter: 'all', sort: 'newest' }
|
|
);
|
|
const [hasMore, setHasMore] = useState(true);
|
|
const [total, setTotal] = useState(0);
|
|
|
|
const { lastTrade, isConnected } = useWebSocket();
|
|
|
|
// Fetch trades
|
|
const fetchTrades = useCallback(async (append = false) => {
|
|
try {
|
|
setError(null);
|
|
if (!append) setLoading(true);
|
|
|
|
const data = await api.getTradeHistory(filters);
|
|
|
|
if (append) {
|
|
setTrades((prev) => [...prev, ...data.trades]);
|
|
} else {
|
|
setTrades(data.trades);
|
|
}
|
|
|
|
setTotal(data.total);
|
|
setHasMore(data.trades.length === filters.limit);
|
|
|
|
return data;
|
|
} catch (err: any) {
|
|
console.error('Failed to fetch trades:', err);
|
|
setError(err.message || 'Failed to load trades');
|
|
return null;
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [filters]);
|
|
|
|
// Auto-refresh
|
|
useEffect(() => {
|
|
fetchTrades();
|
|
}, [filters, fetchTrades]);
|
|
|
|
// Add new trade from WebSocket
|
|
useEffect(() => {
|
|
if (lastTrade && filters.filter === 'all') {
|
|
// Add to beginning of list
|
|
setTrades((prev) => {
|
|
// Avoid duplicates
|
|
if (prev.some((t) => t.id === lastTrade.id)) {
|
|
return prev;
|
|
}
|
|
return [lastTrade as any, ...prev].slice(0, filters.limit || 20);
|
|
});
|
|
setTotal((prev) => prev + 1);
|
|
}
|
|
}, [lastTrade, filters]);
|
|
|
|
// Update filter
|
|
const updateFilters = useCallback((newFilters: Partial<TradeFilters>) => {
|
|
setFilters((prev) => ({ ...prev, ...newFilters, offset: 0 }));
|
|
}, []);
|
|
|
|
// Load more
|
|
const loadMore = useCallback(async () => {
|
|
if (!hasMore || loading) return;
|
|
|
|
setFilters((prev) => ({
|
|
...prev,
|
|
offset: (prev.offset || 0) + (prev.limit || 20),
|
|
}));
|
|
|
|
return fetchTrades(true);
|
|
}, [hasMore, loading, fetchTrades]);
|
|
|
|
// Refresh
|
|
const refresh = useCallback(async () => {
|
|
setFilters((prev) => ({ ...prev, offset: 0 }));
|
|
return fetchTrades(false);
|
|
}, [fetchTrades]);
|
|
|
|
// Calculate statistics
|
|
const stats = {
|
|
totalTrades: trades.length,
|
|
profitableTrades: trades.filter((t) => (t.profitLoss || 0) > 0).length,
|
|
failedTrades: trades.filter((t) => t.status === 'FAILED').length,
|
|
pendingTrades: trades.filter((t) => t.status === 'PENDING').length,
|
|
totalProfit: trades.reduce((sum, t) => sum + (t.profitLoss || 0), 0),
|
|
avgProfit:
|
|
trades.length > 0
|
|
? trades.reduce((sum, t) => sum + (t.profitLoss || 0), 0) / trades.length
|
|
: 0,
|
|
};
|
|
|
|
return {
|
|
trades,
|
|
loading,
|
|
error,
|
|
filters,
|
|
hasMore,
|
|
total,
|
|
isConnected,
|
|
updateFilters,
|
|
loadMore,
|
|
refresh,
|
|
stats,
|
|
};
|
|
}
|
|
|
|
export default useTrades;
|