Files
autofirmer-expanded/app/api/state/route.ts
T
SenofyandClaude Sonnet 4.6 570a54fe60 Fix fetchDaysTraded to use reports API with bearer auth and correct daysTraded counting
- Replace fill/ldeps and fill/list approaches with Tradovate reports API
- Add bearer auth to getreport polling (root cause of prior 404s)
- Use endDate = tomorrow to ensure current-session fills are included
- Count all traded days when minDayPnL is 0, otherwise count days >= minDayPnL
- Add PATCH /api/debug endpoint for proxying raw Tradovate API calls

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-09 18:57:12 -05:00

70 lines
3.3 KiB
TypeScript

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);
// Compute daily target and targetHit in one place — the single source of truth.
const cfg = getAccountConfig(acc.name, f.accounts);
const autoLiqThreshold = client.autoLiqThresholds[acc.id] ?? 0;
const isDead = autoLiqThreshold > 0 && cash.amount <= autoLiqThreshold;
let targetHit = false;
let dailyTarget: { amount: number; path: 'first_day' | 'normal_day' | 'reduced_day' } | null = null;
if (cfg && !isDead) {
const target = computeDailyTarget(cfg.profit_target, cfg.consistency, totalProfit, dailyPnL, cfg.min_day_pnl, cfg.min_trading_days);
dailyTarget = target;
// 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,
totalProfit,
targetHit,
dailyTarget,
dailyPnL,
};
});
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 });
}
}