Files
autofirmer-expanded/app/api/state/route.ts
T
Brandon LiandClaude Opus 4.6 670ee9fbeb Require equityProfit; return null when balance invalid
computeDailyTarget now requires equityProfit (amount - accountSize) and
returns null when it's undefined/null/NaN. 0 is still a valid value.

- Removed totalProfit parameter (was only used as fallback)
- Callers handle null by skipping the account (eligibility) or throwing
  (execution paths)
- State API sets dailyTarget to null when no valid balance, avoids
  incorrect targetHit computation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-21 20:00:52 -05:00

92 lines
4.6 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getFirms, loadDailyPnL } from '@/lib/db';
import { getClients } from '@/lib/clients';
import { computeDailyTarget, resolveEffectiveConfig } 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;
const allFundTxns = client.fundTransactions?.[acc.id] ?? [];
const priorProfit = client.priorProfit?.[acc.id] ?? 0;
// Hide initial funding (amount === accountSize) from display
const displayFundTxns = cfg
? allFundTxns.filter((f) => f.amount !== cfg.account_size)
: allFundTxns;
let targetHit = false;
let dailyTarget: { amount: number; path: 'first_day' | 'normal_day' | 'reduced_day' } | null = null;
if (cfg && !isDead) {
const withdrawalStages: { profit: number; consistency: number; minTradingDays: number }[] = (() => { try { return JSON.parse(cfg.withdrawal_stages ?? '[]'); } catch { return []; } })();
const effective = resolveEffectiveConfig(
cfg.profit_target,
cfg.consistency,
cfg.min_trading_days,
cfg.target_same_equity === 1,
withdrawalStages,
priorProfit,
allFundTxns
);
const equityProfit = cash.amount - cfg.account_size;
const target = computeDailyTarget(effective.profitTarget, effective.consistency, dailyPnL, cfg.min_day_pnl, effective.minTradingDays, equityProfit);
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
if (target) {
targetHit =
(target.amount === 0 && Math.abs(cash.realizedPnL) > 0 && client.daysTraded[acc.id] <= effective.minTradingDays) ||
(cash.realizedPnL >= target.amount);
}
}
return {
id: acc.id,
name: acc.name,
active: acc.active,
amount: cash.amount,
realizedPnL: cash.realizedPnL,
daysTraded,
positionDirection: client.positions[acc.id]
? (client.positions[acc.id].netPos > 0 ? 'long' as const : 'short' as const)
: null,
autoLiqThreshold,
totalProfit,
targetHit,
dailyTarget,
dailyPnL,
fullDailyPnL: client.fullDailyPnL?.[acc.id] ?? loadDailyPnL(acc.id),
fundTransactions: displayFundTxns,
};
});
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 });
}
}