i have this code: // src/app/api/trades/route.ts import { NextResponse } from…
- User
i have this code: // src/app/api/trades/route.ts import { NextResponse } from 'next/server' import { cookies } from 'next/headers' import prisma from '@/app/lib/prisma' import type { CreateTradeInput } from '@/types/trade'
export async function GET() { try { const cookieStore = cookies() const token = cookieStore.get('auth_token')
if (!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 }
const drawdown = ((peak - runningPnL) / peak) * 100 if (drawdown > maxDrawdown) { maxDrawdown = drawdown }})
return maxDrawdown.toFixed(1) }
export async function POST(req: Request) { try { const cookieStore = cookies() const token = cookieStore.get('auth_token')
if (!token) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const userId = parseInt(token.value) if (isNaN(userId)) { return NextResponse.json({ error: 'Invalid user ID' }, { status: 400 }) } const data: CreateTradeInput = await req.json() // Calculate PNL and PNL percentage only for closed trades const pnl = data.exit_price ? (data.exit_price - data.entry_price) * data.quantity * (data.type === 'SHORT' ? -1 : 1) : 0 const pnl_percent = data.exit_price ? ((data.exit_price - data.entry_price) / data.entry_price) * 100 * (data.type === 'SHORT' ? -1 : 1) : 0 // Handle dates properly const entryDate = new Date(data.entry_date) const exitDate = data.exit_date ? new Date(data.exit_date) : null // Calculate hold_duration only for closed trades or current duration for open trades const hold_duration = exitDate ? Math.floor((exitDate.getTime() - entryDate.getTime()) / 1000) : data.status === 'open' ? Math.floor((new Date().getTime() - entryDate.getTime()) / 1000) : null const trade = await prisma.trade.create({ data: { userId, symbol: data.symbol.toUpperCase(), type: data.type, entry_price: data.entry_price, exit_price: data.exit_price || null, // Explicitly set null if no exit price quantity: data.quantity, entry_date: entryDate, exit_date: exitDate, // Will be null for open trades notes: data.notes || null, pnl, pnl_percent, hold_duration, status: exitDate ? 'closed' : 'open' } }) return NextResponse.json(trade, { status: 201 }) - Assistant