import { NextResponse } from 'next/server'; import { getFirms } from '@/lib/db'; import { getClients } from '@/lib/clients'; import { computeDailyTarget } from '@/lib/trading-logic'; import type { AccountConfigRow } from '@/lib/db'; function getAccountConfig(name: string, accounts: AccountConfigRow[]): AccountConfigRow | undefined { return [...accounts] .sort((a, b) => b.prefix.length - a.prefix.length) .find((a) => name.startsWith(a.prefix)); } export async function GET() { try { const firms = getFirms(); const clients = getClients(); const state = firms.map((f) => { const client = clients.get(f.id); if (!client || client.accountList.length === 0) { return { firm: f.name, connected: false, accounts: [] }; } const accounts = client.accountList.map((acc) => { const cash = client.accountCashBalances[acc.id] ?? { amount: 0, realizedPnL: 0 }; const dailyPnL: { date: string; pnl: number }[] = client.dailyPnL[acc.id] ?? []; const daysTraded: number = client.daysTraded[acc.id] ?? 0; const totalProfit = dailyPnL.reduce((sum, d) => sum + d.pnl, 0); // Determine if today's daily target was hit const cfg = getAccountConfig(acc.name, f.accounts); let targetHit = false; if (cfg) { const target = computeDailyTarget(cfg.profit_target, cfg.consistency, totalProfit, dailyPnL); // Condition 1: profit target already exceeded (target=0), still need days → any activity counts // Condition 2: target > 0 → must have made at least the computed daily target targetHit = // If we are just flipping take any activity as target hit (target.amount === 0 && Math.abs(cash.realizedPnL) > 0 && client.daysTraded[acc.id] <= cfg.min_trading_days) || (cash.realizedPnL >= target.amount); } return { id: acc.id, name: acc.name, active: acc.active, amount: cash.amount, realizedPnL: cash.realizedPnL, daysTraded, hasPosition: !!client.positions[acc.id], autoLiqThreshold: client.autoLiqThresholds[acc.id] ?? 0, totalProfit, targetHit, }; }); return { firm: f.name, connected: true, accounts, perContractFees: client.perContractFees }; }); return NextResponse.json(state); } catch (err) { console.error('[GET /api/state]', err); return NextResponse.json({ error: 'Failed to fetch state' }, { status: 500 }); } }