Files
autofirmer-expanded/app/api/state/route.ts
T
SenofyandClaude Sonnet 4.6 b2a1bdd1c3 Add auto-trade scheduler with batch locking, commission gross-up, and sync gate
- Auto-trade scheduler fires every 60s; uses Promise.allSettled batch so no new trades fire while any position from the current batch is open
- Commission gross-up: read entryCommission from cash.realizedPnL after fill (fallback 2.5×contracts), grossTarget = target + 2×entryCommission
- Sync gate: TradovateClient.syncComplete flag; scheduler skips tick until every client finishes initial position/balance sync
- Contracts formula changed to Math.ceil so $1500 target = 2 contracts
- Removed all fee caching (perContractFees, recentFills, fillFee handler) from tradovate-class.ts
- Removed firm_fees table, getFirmFees, upsertFirmFee from db.ts
- Deleted instrument-configs API routes; removed Fees UI from firm settings page
- /api/instruments returns full {symbol, enabled}[] objects; dashboard filters to enabled-only for trade selector
- Added auto-trade, debug, orders, settings, and trade API routes
- Instrument selector on dashboard now driven by enabled instruments from DB

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

64 lines
2.8 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);
// 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 });
}
}