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 | const express = require('express'); const router = express.Router(); const { Portfolio, Trade, Transaction, FeeRecord } = require('../models'); const logger = require('../utils/logger'); const { Op } = require('sequelize'); // Get portfolio overview router.get('/', async (req, res) => { try { let portfolio = await Portfolio.findOne({ where: { userId: req.userId } }); if (!portfolio) { // Create portfolio if doesn't exist portfolio = await Portfolio.create({ userId: req.userId }); } res.json({ portfolio }); } catch (error) { logger.error('Get portfolio error:', error); res.status(500).json({ error: 'Failed to fetch portfolio' }); } }); // Get portfolio holdings router.get('/holdings', async (req, res) => { try { const portfolio = await Portfolio.findOne({ where: { userId: req.userId } }); if (!portfolio) { return res.json({ holdings: {} }); } res.json({ holdings: portfolio.holdings }); } catch (error) { logger.error('Get holdings error:', error); res.status(500).json({ error: 'Failed to fetch holdings' }); } }); // Get portfolio history router.get('/history', async (req, res) => { try { const { period = 'daily' } = req.query; const portfolio = await Portfolio.findOne({ where: { userId: req.userId } }); if (!portfolio) { return res.json({ history: [] }); } const history = portfolio.historicalData[period] || []; res.json({ history }); } catch (error) { logger.error('Get history error:', error); res.status(500).json({ error: 'Failed to fetch history' }); } }); // Get portfolio performance router.get('/performance', 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 } }); if (!portfolio) { return res.json({ performance: [] }); } // Get trades in period const trades = await Trade.findAll({ where: { userId: req.userId, status: 'completed', createdAt: { [Op.gte]: startDate } }, order: [['createdAt', 'ASC']] }); // Calculate daily performance const performanceData = {}; let runningValue = parseFloat(portfolio.totalDeposited); trades.forEach(trade => { const date = trade.createdAt.toISOString().split('T')[0]; if (!performanceData[date]) { performanceData[date] = { date, value: runningValue, trades: 0, profit: 0 }; } const profit = parseFloat(trade.profit); runningValue += profit; performanceData[date].value = runningValue; performanceData[date].trades++; performanceData[date].profit += profit; }); const performance = Object.values(performanceData); res.json({ performance, summary: { totalTrades: trades.length, totalProfit: trades.reduce((sum, t) => sum + parseFloat(t.profit), 0), avgProfit: trades.length > 0 ? trades.reduce((sum, t) => sum + parseFloat(t.profit), 0) / trades.length : 0, roi: portfolio.calculateROI() } }); } catch (error) { logger.error('Get performance error:', error); res.status(500).json({ error: 'Failed to fetch performance' }); } }); // Get fee breakdown router.get('/fees', async (req, res) => { try { const { days = 30 } = req.query; const startDate = new Date(); startDate.setDate(startDate.getDate() - parseInt(days)); const fees = await FeeRecord.findAll({ where: { userId: req.userId, createdAt: { [Op.gte]: startDate } }, order: [['createdAt', 'DESC']] }); // Group by fee type const breakdown = fees.reduce((acc, fee) => { if (!acc[fee.feeType]) { acc[fee.feeType] = 0; } acc[fee.feeType] += parseFloat(fee.amount); return acc; }, {}); const total = Object.values(breakdown).reduce((sum, val) => sum + val, 0); res.json({ breakdown, total, fees: fees.slice(0, 50) // Return last 50 fees }); } catch (error) { logger.error('Get fees error:', error); res.status(500).json({ error: 'Failed to fetch fees' }); } }); // Update portfolio settings router.put('/settings', async (req, res) => { try { const { activeStrategies, metadata } = req.body; const portfolio = await Portfolio.findOne({ where: { userId: req.userId } }); if (!portfolio) { return res.status(404).json({ error: 'Portfolio not found' }); } if (activeStrategies) portfolio.activeStrategies = activeStrategies; if (metadata) portfolio.metadata = { ...portfolio.metadata, ...metadata }; await portfolio.save(); res.json({ portfolio, message: 'Settings updated successfully' }); } catch (error) { logger.error('Update settings error:', error); res.status(500).json({ error: 'Failed to update settings' }); } }); module.exports = router; |