Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | const express = require('express'); const router = express.Router(); const { Trade, Portfolio, FeeRecord, Transaction, Strategy } = require('../models'); const logger = require('../utils/logger'); const { Op } = require('sequelize'); // Get dashboard analytics router.get('/dashboard', async (req, res) => { try { const { days = 30 } = req.query; const startDate = new Date(); startDate.setDate(startDate.getDate() - parseInt(days)); // Portfolio overview const portfolio = await Portfolio.findOne({ where: { userId: req.userId } }); // Trades summary const trades = await Trade.findAll({ where: { userId: req.userId, createdAt: { [Op.gte]: startDate } } }); const completedTrades = trades.filter(t => t.status === 'completed'); const totalProfit = completedTrades.reduce((sum, t) => sum + parseFloat(t.profit), 0); const totalVolume = completedTrades.reduce((sum, t) => sum + parseFloat(t.fromAmount), 0); // Fee summary const fees = await FeeRecord.findAll({ where: { userId: req.userId, createdAt: { [Op.gte]: startDate } } }); const totalFees = fees.reduce((sum, f) => sum + parseFloat(f.amount), 0); // Strategy performance const strategyPerformance = {}; completedTrades.forEach(trade => { const strategyId = trade.strategyId; if (!strategyPerformance[strategyId]) { strategyPerformance[strategyId] = { trades: 0, profit: 0, volume: 0 }; } strategyPerformance[strategyId].trades++; strategyPerformance[strategyId].profit += parseFloat(trade.profit); strategyPerformance[strategyId].volume += parseFloat(trade.fromAmount); }); res.json({ portfolio: portfolio ? { totalDeposited: portfolio.totalDeposited, currentValue: portfolio.currentValue, totalProfits: portfolio.totalProfits, roi: portfolio.calculateROI() } : null, trades: { total: trades.length, completed: completedTrades.length, pending: trades.filter(t => t.status === 'pending').length, failed: trades.filter(t => t.status === 'failed').length, totalProfit, totalVolume, avgProfit: completedTrades.length > 0 ? totalProfit / completedTrades.length : 0 }, fees: { total: totalFees, count: fees.length, avgFee: fees.length > 0 ? totalFees / fees.length : 0 }, strategyPerformance }); } catch (error) { logger.error('Get dashboard analytics error:', error); res.status(500).json({ error: 'Failed to fetch analytics' }); } }); // Get profit/loss over time router.get('/profit-loss', async (req, res) => { try { const { days = 30, interval = 'daily' } = req.query; const startDate = new Date(); startDate.setDate(startDate.getDate() - parseInt(days)); const trades = await Trade.findAll({ where: { userId: req.userId, status: 'completed', createdAt: { [Op.gte]: startDate } }, order: [['createdAt', 'ASC']] }); const dataPoints = {}; let cumulativeProfit = 0; trades.forEach(trade => { const date = trade.createdAt.toISOString().split('T')[0]; const profit = parseFloat(trade.profit); if (!dataPoints[date]) { dataPoints[date] = { date, profit: 0, cumulativeProfit: 0, trades: 0, wins: 0, losses: 0 }; } dataPoints[date].profit += profit; cumulativeProfit += profit; dataPoints[date].cumulativeProfit = cumulativeProfit; dataPoints[date].trades++; if (profit > 0) { dataPoints[date].wins++; } else if (profit < 0) { dataPoints[date].losses++; } }); res.json({ data: Object.values(dataPoints), summary: { totalProfit: cumulativeProfit, totalTrades: trades.length, avgProfit: trades.length > 0 ? cumulativeProfit / trades.length : 0, winRate: trades.length > 0 ? (trades.filter(t => parseFloat(t.profit) > 0).length / trades.length) * 100 : 0 } }); } catch (error) { logger.error('Get profit/loss analytics error:', error); res.status(500).json({ error: 'Failed to fetch profit/loss data' }); } }); // Get portfolio allocation router.get('/allocation', async (req, res) => { try { const portfolio = await Portfolio.findOne({ where: { userId: req.userId } }); if (!portfolio || !portfolio.holdings) { return res.json({ allocation: [] }); } const holdings = portfolio.holdings; const totalValue = Object.values(holdings).reduce((sum, h) => sum + (h.value || 0), 0); const allocation = Object.entries(holdings).map(([token, data]) => ({ token, amount: data.amount || 0, value: data.value || 0, percentage: totalValue > 0 ? (data.value / totalValue) * 100 : 0 })); res.json({ allocation, totalValue }); } catch (error) { logger.error('Get allocation analytics error:', error); res.status(500).json({ error: 'Failed to fetch allocation data' }); } }); // Get strategy comparison router.get('/strategy-comparison', async (req, res) => { try { const { days = 30 } = req.query; const startDate = new Date(); startDate.setDate(startDate.getDate() - parseInt(days)); const trades = await Trade.findAll({ where: { userId: req.userId, status: 'completed', createdAt: { [Op.gte]: startDate } }, include: [{ model: Strategy, as: 'strategy' }] }); // Group by strategy const strategyStats = {}; trades.forEach(trade => { const strategyName = trade.strategy?.name || 'Unknown'; if (!strategyStats[strategyName]) { strategyStats[strategyName] = { name: strategyName, trades: 0, profit: 0, volume: 0, wins: 0, losses: 0 }; } strategyStats[strategyName].trades++; strategyStats[strategyName].volume += parseFloat(trade.fromAmount); const profit = parseFloat(trade.profit); strategyStats[strategyName].profit += profit; if (profit > 0) { strategyStats[strategyName].wins++; } else if (profit < 0) { strategyStats[strategyName].losses++; } }); // Calculate additional metrics const comparison = Object.values(strategyStats).map(stats => ({ ...stats, avgProfit: stats.trades > 0 ? stats.profit / stats.trades : 0, winRate: stats.trades > 0 ? (stats.wins / stats.trades) * 100 : 0, roi: stats.volume > 0 ? (stats.profit / stats.volume) * 100 : 0 })); res.json({ comparison }); } catch (error) { logger.error('Get strategy comparison error:', error); res.status(500).json({ error: 'Failed to fetch strategy comparison' }); } }); // Get risk metrics router.get('/risk', async (req, res) => { try { const { days = 30 } = req.query; const startDate = new Date(); startDate.setDate(startDate.getDate() - parseInt(days)); const portfolio = await Portfolio.findOne({ where: { userId: req.userId } }); const trades = await Trade.findAll({ where: { userId: req.userId, status: 'completed', createdAt: { [Op.gte]: startDate } }, order: [['createdAt', 'ASC']] }); // Calculate volatility const returns = []; for (let i = 1; i < trades.length; i++) { const previousValue = parseFloat(trades[i-1].toAmount); const currentValue = parseFloat(trades[i].toAmount); if (previousValue > 0) { returns.push((currentValue - previousValue) / previousValue); } } const avgReturn = returns.length > 0 ? returns.reduce((a, b) => a + b, 0) / returns.length : 0; const variance = returns.length > 0 ? returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / returns.length : 0; const volatility = Math.sqrt(variance); // Calculate max drawdown let peak = 0; let maxDrawdown = 0; let currentValue = parseFloat(portfolio?.currentValue || 0); trades.forEach(trade => { currentValue += parseFloat(trade.profit); if (currentValue > peak) { peak = currentValue; } const drawdown = (peak - currentValue) / peak; if (drawdown > maxDrawdown) { maxDrawdown = drawdown; } }); // Calculate Sharpe Ratio (simplified) const riskFreeRate = 0.02; // 2% annual const sharpeRatio = volatility > 0 ? (avgReturn - riskFreeRate / 365) / volatility : 0; res.json({ riskScore: portfolio?.riskScore || 50, volatility: volatility * 100, maxDrawdown: maxDrawdown * 100, sharpeRatio, exposure: { total: parseFloat(portfolio?.currentValue || 0), allocated: parseFloat(portfolio?.totalDeposited || 0), available: Math.max(0, parseFloat(portfolio?.currentValue || 0) - parseFloat(portfolio?.totalDeposited || 0)) } }); } catch (error) { logger.error('Get risk metrics error:', error); res.status(500).json({ error: 'Failed to fetch risk metrics' }); } }); // Get transaction history router.get('/transactions', async (req, res) => { try { const { limit = 50, offset = 0, type } = req.query; const where = { userId: req.userId }; if (type) where.type = type; const transactions = await Transaction.findAll({ where, limit: parseInt(limit), offset: parseInt(offset), order: [['createdAt', 'DESC']] }); const total = await Transaction.count({ where }); res.json({ transactions, pagination: { total, limit: parseInt(limit), offset: parseInt(offset), hasMore: total > parseInt(offset) + parseInt(limit) } }); } catch (error) { logger.error('Get transactions error:', error); res.status(500).json({ error: 'Failed to fetch transactions' }); } }); module.exports = router; |