// src/app/api/trades/route.ts import { NextResponse } from 'next/server' import {…
- User
// src/app/api/trades/route.ts import { NextResponse } from 'next/server' import { cookies } from 'next/headers' import prisma from '@/app/lib/prisma' import type { TradeCreateInput } from '@/types/trade'
export async function GET() { try { const cookieStore = cookies() const token = cookieStore.get('auth_token')
codeif (!token) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } // Get user ID from token - adjust this based on your token structure const userId = parseInt(token.value) if (isNaN(userId)) { return NextResponse.json({ error: 'Invalid user ID' }, { status: 400 }) } const trades = await prisma.trade.findMany({ where: { userId }, orderBy: { created_at: 'desc' } }) // Calculate stats from trades const stats = { totalTrades: trades.length, winRate: calculateWinRate(trades), profitFactor: calculateProfitFactor(trades), maxDrawdown: calculateMaxDrawdown(trades) } return NextResponse.json({ trades, stats })} catch (error) { console.error('Error fetching trades:', error) return NextResponse.json( { error: 'Failed to fetch trades' }, { status: 500 } ) } }
// Helper functions to calculate stats function calculateWinRate(trades: any[]): string { if (trades.length === 0) return '0' const winningTrades = trades.filter(trade => trade.pnl > 0).length return ((winningTrades / trades.length) * 100).toFixed(1) }
function calculateProfitFactor(trades: any[]): string { const profits = trades.filter(trade => trade.pnl > 0).reduce((sum, trade) => sum + trade.pnl, 0) const losses = Math.abs(trades.filter(trade => trade.pnl < 0).reduce((sum, trade) => sum + trade.pnl, 0)) return losses === 0 ? '∞' : (profits / losses).toFixed(2) }
function calculateMaxDrawdown(trades: any[]): string { if (trades.length === 0) return '0'
let peak = 0 let maxDrawdown = 0 let runningPnL = 0
trades.forEach(trade => { runningPnL += trade.pnl if (runningPnL > peak) { peak = runningPnL }
codeconst drawdown = ((peak - runningPnL) / peak) * 100 if (drawdown > maxDrawdown) { maxDrawdown = drawdown }})
return maxDrawdown.toFixed(1) }
- Assistant