All files / routes trade.js

0% Statements 0/99
0% Branches 0/39
0% Functions 0/14
0% Lines 0/92

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                                                                                                                                                                                                                                                                                                                                                                                                                                                 
const express = require('express');
const router = express.Router();
const { Trade, Portfolio, Strategy } = require('../models');
const TradingEngine = require('../services/TradingEngine');
const FeeEngine = require('../services/FeeEngine');
const logger = require('../utils/logger');
const { Op } = require('sequelize');
 
const tradingEngine = new TradingEngine();
const feeEngine = new FeeEngine();
 
// Get all trades
router.get('/', async (req, res) => {
  try {
    const { limit = 50, offset = 0, status, type } = req.query;
    
    const where = { userId: req.userId };
    if (status) where.status = status;
    if (type) where.type = type;
 
    const trades = await Trade.findAll({
      where,
      include: [{ model: Strategy, as: 'strategy' }],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });
 
    const total = await Trade.count({ where });
 
    res.json({
      trades,
      pagination: {
        total,
        limit: parseInt(limit),
        offset: parseInt(offset),
        hasMore: total > parseInt(offset) + parseInt(limit)
      }
    });
  } catch (error) {
    logger.error('Get trades error:', error);
    res.status(500).json({ error: 'Failed to fetch trades' });
  }
});
 
// Get trade by ID
router.get('/:id', async (req, res) => {
  try {
    const trade = await Trade.findOne({
      where: { id: req.params.id, userId: req.userId },
      include: [{ model: Strategy, as: 'strategy' }]
    });
 
    if (!trade) {
      return res.status(404).json({ error: 'Trade not found' });
    }
 
    res.json({ trade });
  } catch (error) {
    logger.error('Get trade error:', error);
    res.status(500).json({ error: 'Failed to fetch trade' });
  }
});
 
// Execute new trade
router.post('/execute', async (req, res) => {
  try {
    const { strategyType, params } = req.body;
 
    if (!strategyType || !params) {
      return res.status(400).json({ error: 'Strategy type and params required' });
    }
 
    // Verify user has sufficient balance
    const portfolio = await Portfolio.findOne({ where: { userId: req.userId } });
    
    if (!portfolio || parseFloat(portfolio.currentValue) < parseFloat(params.amount || 0)) {
      return res.status(400).json({ error: 'Insufficient balance' });
    }
 
    // Get strategy
    const strategy = await Strategy.findOne({ where: { slug: strategyType } });
    
    if (!strategy || !strategy.isActive) {
      return res.status(404).json({ error: 'Strategy not found or inactive' });
    }
 
    // Check minimum investment
    if (parseFloat(params.amount) < parseFloat(strategy.minInvestment)) {
      return res.status(400).json({ 
        error: `Minimum investment is ${strategy.minInvestment}` 
      });
    }
 
    // Create trade record
    const trade = await Trade.create({
      userId: req.userId,
      portfolioId: portfolio.id,
      strategyId: strategy.id,
      type: strategyType,
      status: 'pending',
      ...params
    });
 
    // Execute trade (asynchronous)
    tradingEngine.executeTrade(req.userId, strategyType, params)
      .then(async result => {
        trade.status = 'completed';
        trade.transactionHash = result.transactionHash;
        trade.profit = result.profit;
        trade.platformFee = result.platformFee;
        await trade.save();
      })
      .catch(async error => {
        logger.error('Trade execution failed:', error);
        trade.status = 'failed';
        trade.errorMessage = error.message;
        await trade.save();
      });
 
    res.json({ 
      trade,
      message: 'Trade submitted successfully' 
    });
  } catch (error) {
    logger.error('Execute trade error:', error);
    res.status(500).json({ error: 'Failed to execute trade' });
  }
});
 
// Estimate trade profit
router.post('/estimate', async (req, res) => {
  try {
    const { strategyType, params } = req.body;
 
    if (!strategyType || !params) {
      return res.status(400).json({ error: 'Strategy type and params required' });
    }
 
    const estimate = await tradingEngine.estimateProfit(strategyType, params);
 
    res.json({ estimate });
  } catch (error) {
    logger.error('Estimate trade error:', error);
    res.status(500).json({ error: 'Failed to estimate trade' });
  }
});
 
// Cancel pending trade
router.post('/:id/cancel', async (req, res) => {
  try {
    const trade = await Trade.findOne({
      where: { id: req.params.id, userId: req.userId }
    });
 
    if (!trade) {
      return res.status(404).json({ error: 'Trade not found' });
    }
 
    if (trade.status !== 'pending') {
      return res.status(400).json({ error: 'Only pending trades can be cancelled' });
    }
 
    trade.status = 'cancelled';
    await trade.save();
 
    res.json({ trade, message: 'Trade cancelled successfully' });
  } catch (error) {
    logger.error('Cancel trade error:', error);
    res.status(500).json({ error: 'Failed to cancel trade' });
  }
});
 
// Get trade statistics
router.get('/stats/summary', 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,
        createdAt: { [Op.gte]: startDate }
      }
    });
 
    const completed = trades.filter(t => t.status === 'completed');
    const failed = trades.filter(t => t.status === 'failed');
    const profitable = completed.filter(t => parseFloat(t.profit) > 0);
 
    const totalProfit = completed.reduce((sum, t) => sum + parseFloat(t.profit), 0);
    const totalFees = completed.reduce((sum, t) => sum + parseFloat(t.platformFee), 0);
 
    res.json({
      summary: {
        totalTrades: trades.length,
        completed: completed.length,
        failed: failed.length,
        pending: trades.filter(t => t.status === 'pending').length,
        successRate: trades.length > 0 ? (completed.length / trades.length) * 100 : 0,
        profitableRate: completed.length > 0 ? (profitable.length / completed.length) * 100 : 0,
        totalProfit,
        totalFees,
        netProfit: totalProfit - totalFees,
        averageProfit: completed.length > 0 ? totalProfit / completed.length : 0
      }
    });
  } catch (error) {
    logger.error('Get trade stats error:', error);
    res.status(500).json({ error: 'Failed to fetch trade statistics' });
  }
});
 
module.exports = router;