);
}
function ObjRow({ passed, label, value }: { passed: boolean; label: ReactNode; value: string }) {
return (
{passed
? ✓
: !
}
{label}
{value}
);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function EquityTooltip({ active, payload, label }: any) {
if (!active || !payload?.length) return null;
// Always read from the raw data point so fill-only series don't interfere
const equity: number = payload[0].payload.equity;
const daily: number = payload[0].payload.pnl;
return (
);
}
export default function AccountPage() {
const { id } = useParams<{ id: string }>();
const accountId = Number(id);
const [account, setAccount] = useState(null);
const [cfg, setCfg] = useState(null);
const [firmName, setFirmName] = useState('');
const [firm, setFirm] = useState(null);
const load = useCallback(async () => {
const [stateRes, firmsRes] = await Promise.all([
fetch('/api/state'),
fetch('/api/firms'),
]);
const states: FirmState[] = await stateRes.json();
const firms: FirmConfig[] = await firmsRes.json();
for (const firmState of states) {
const acc = firmState.accounts.find((a) => a.id === accountId);
if (acc) {
// Join on the master's firm id — the name changes the
// moment someone renames a firm there.
const firmCfg = firms.find((f) => f.id === firmState.firmId);
setAccount(acc);
setFirmName(firmState.firm);
setFirm(firmCfg ?? null);
setCfg(acc.accountType);
break;
}
}
}, [accountId]);
useEffect(() => {
// The first load from a timer too, like the polls: not setState
// from the effect's own body.
const first = setTimeout(() => { void load(); }, 0);
const interval = setInterval(() => { void load(); }, 5000);
return () => { clearTimeout(first); clearInterval(interval); };
}, [load]);
if (!account) {
return (
← Back
Loading…
);
}
// dailyPnL = current cycle (for targets); fullDailyPnL = all history (for display)
const dailyPnL = account.dailyPnL;
const displayPnL = account.fullDailyPnL ?? account.dailyPnL;
const fundTransactions = account.fundTransactions ?? [];
const fundMap = new Map(fundTransactions.map((f) => [f.date, f.amount]));
// The firm's hard daily loss limit, and the least a day must make to count
// as a trading day — two different numbers; neither is set on every type.
// The limit and the min days are the current stage's, which may set its own.
const stageLossLimit = account.effectiveDailyLossLimit ?? cfg?.dailyLossLimit ?? 0;
const dailyLossLimit = stageLossLimit > 0 ? stageLossLimit : null;
const minDayPnL = (cfg?.minDayPnL ?? 0) > 0 ? cfg!.minDayPnL : null;
const minTradingDays = account.effectiveMinTradingDays ?? cfg?.minTradingDays ?? 0;
const daysPassed = cfg != null && account.daysTraded >= minTradingDays;
// Dead when balance hits the liquidation floor — Tradovate reports its
// (positive) floor; TopstepX floors are reconstructed MLLs, negative or
// +$0.01 once locked at breakeven. 0 = no floor known.
const isDead = account.autoLiqThreshold !== 0 && account.amount <= account.autoLiqThreshold;
const liqFloor = account.autoLiqThreshold !== 0 ? account.autoLiqThreshold : null;
// Ground-truth profit = balance minus funded account size.
// Falls back to FIFO total when accountSize is unavailable.
const fifoTotal = dailyPnL.reduce((s, d) => s + d.pnl, 0);
const totalProfit = cfg?.accountSize
? Math.round((account.amount - cfg.accountSize) * 100) / 100
: Math.round(fifoTotal * 100) / 100;
const profitPct = cfg?.accountSize ? (totalProfit / cfg.accountSize) * 100 : null;
const profitPassed = cfg != null && totalProfit >= (account.effectiveProfitTarget ?? cfg.profitTarget);
// dailyTarget is computed server-side in the state API — single source of truth.
const dailyTarget = account.dailyTarget ?? null;
// Consistency target: the total profit level at which the best day no longer
// violates the consistency ratio. Only meaningful once a positive day exists.
const maxDayPnL = displayPnL.length > 0 ? Math.max(...displayPnL.filter(d => d.pnl > 0).map(d => d.pnl)) : 0;
const consistencyTarget = cfg && cfg.consistency > 0 && cfg.consistency < 1 && maxDayPnL > 0
? Math.round(maxDayPnL / cfg.consistency * 100) / 100
: null;
// Build equity curve: FIFO daily increments + withdrawal step-downs, origin at $0
// Merge daily P&L and fund transactions into a single sorted timeline
type EquityEvent = { date: string; pnl?: number; fundAmt?: number };
const allDates = new Set([...displayPnL.map((d) => d.date), ...fundTransactions.map((f) => f.date)]);
const eventsByDate = new Map();
for (const d of displayPnL) eventsByDate.set(d.date, { date: d.date, pnl: d.pnl });
for (const f of fundTransactions) {
const existing = eventsByDate.get(f.date);
eventsByDate.set(f.date, { ...existing, date: f.date, fundAmt: f.amount });
}
const sortedEvents = [...allDates].sort().map((d) => eventsByDate.get(d)!);
// Running equity after each event, summed here rather than inside the
// map below: a render callback mustn't reassign an outer variable.
const runningAfter: number[] = [];
let running = 0;
for (const ev of sortedEvents) {
if (ev.fundAmt !== undefined) running += ev.fundAmt; // withdrawals reduce equity
if (ev.pnl !== undefined) running += ev.pnl;
runningAfter.push(running);
}
const equityData = [
{ label: '', equity: 0, pnl: 0, origin: true, pos: 0, neg: 0, isWithdrawal: false },
...sortedEvents.map((ev, i) => {
const equity = Math.round(runningAfter[i] * 100) / 100;
return {
label: fmtDate(ev.date),
equity,
pnl: ev.pnl ?? 0,
pos: Math.max(0, equity),
neg: Math.min(0, equity),
isWithdrawal: ev.fundAmt !== undefined,
fundAmt: ev.fundAmt,
date: ev.date,
};
}),
];
// Dates with fund transactions that appear in the chart (for vertical reference lines)
const withdrawalLabels = equityData.filter((d) => d.isWithdrawal).map((d) => d.label);
const isPositive = totalProfit >= 0;
// Equity range
const equityValues = equityData.map((d) => d.equity);
// Y-axis domain: include profit target so its reference line stays visible
const rawMin = Math.min(0, ...equityValues);
const rawMax = Math.max(0, ...equityValues, cfg?.profitTarget ?? 0, consistencyTarget ?? 0);
// Stroke gradient split: use only the actual equity range, NOT the profit target.
// The SVG gradient bounding box is the line's bbox, so inflating by profitTarget
// would shift the green→red transition away from y=0.
const gradMax = Math.max(0, ...equityValues);
const gradMin = rawMin; // rawMin never includes profitTarget
const gradRange = gradMax - gradMin;
const zeroFraction = gradRange > 0 ? gradMax / gradRange : 0.5;
const zeroPct = `${(Math.max(0, Math.min(1, zeroFraction)) * 100).toFixed(2)}%`;
const strokeGradId = 'equityStroke';
// Perfect-path projection: what the future looks like if every trading day
// books exactly its plan, cycles complete, and the configured withdrawal
// fires the day a cycle finishes. Same planner the trade path runs, so the
// numbers (bumps and drain amounts included) are what would actually be
// aimed for. Shown up to TWO payout days ahead.
const rawProjection = (cfg && !isDead) ? projectPerfectPath({
accountId: account.id,
cfg,
cycleDailyPnL: account.dailyPnL ?? [],
fundTransactions,
balance: account.amount,
realizedPnL: account.realizedPnL,
// The day the firm's numbers follow (Vest's, until 20:00 ET).
rawTradeDate: account.tradeDate,
// The state stage counts the payouts that pick it: today's for a type
// whose stages reset each day, else every one, each on its own.
stageInputs: cfg.stagesSameDay === true
? { stagesSameDay: true, sameDayWithdrawals: account.stage - 1 }
: { payouts: account.stage - 1 },
// Such a type pays out once per stage on each of those days.
maxWithdrawals: cfg.stagesSameDay === true ? 2 * (1 + cfg.withdrawalStages.length) : 2,
payout: {
withdrawalPct: cfg.withdrawalPct,
payoutCap: cfg.payoutCap,
profitSplit: cfg.profitSplit,
// Same default chain the reporter uses for reach probabilities.
drawdown: (cfg.trailingDrawdown ?? 0) > 0
? cfg.trailingDrawdown!
: Math.abs(cfg.maxLoss) > 0 ? Math.abs(cfg.maxLoss) : 2000,
// The platform's real liquidation floor, when one is known —
// reported by Tradovate, reconstructed for TopstepX.
startThreshold: account.autoLiqThreshold !== 0
? Math.round((account.autoLiqThreshold - cfg.accountSize) * 100) / 100
: undefined,
},
}) : [];
// Cut the projection after the second payout day — days beyond it are
// noise here. The path's dates never go back, and a payoutReady entry is
// always its last.
const payoutDays = [...new Set(rawProjection.filter((p) => p.withdrawal !== undefined || p.payoutReady).map((p) => p.date))];
const projection = payoutDays.length >= 2 ? rawProjection.filter((p) => p.date <= payoutDays[1]) : rawProjection;
// A payout day is the cycle's FINAL trading day — it can carry both the
// day's booked P&L and the withdrawal. A same-day type's day can hold
// several cycles: their P&L and withdrawals add up, and the day shows
// the last stage it traded.
const projPnlMap = new Map();
const projFundMap = new Map();
for (const p of projection) {
if (p.pnl !== 0) projPnlMap.set(p.date, Math.round(((projPnlMap.get(p.date) ?? 0) + p.pnl) * 100) / 100);
if (p.withdrawal !== undefined) projFundMap.set(p.date, Math.round(((projFundMap.get(p.date) ?? 0) + p.withdrawal) * 100) / 100);
}
const projStageMap = new Map(projection.map((p) => [p.date, p.stage]));
/** Cumulative probability of the perfect path surviving through each projected day. */
const projProbMap = new Map(projection.map((p) => [p.date, p.prob]));
const payoutDate = projection.find((p) => p.payoutReady)?.date;
// Build calendar data
const pnlMap = new Map(displayPnL.map((d) => [d.date, d.pnl]));
const allCalendarDates = [
...displayPnL.map((d) => d.date),
...fundTransactions.map((f) => f.date),
...projection.map((p) => p.date),
];
const calendarMonths = [...new Set(allCalendarDates.map((d) => d.slice(0, 7)))].sort();
// Build stage map: stage increments after each withdrawal (negative fund txn).
// A type whose stages reset each day starts every day on stage 1 and
// trades its next stage after a payout that day, as the projected days
// show — one fund row a day holds all of that day's payouts, so a day
// with one reads stage 2.
const sortedWithdrawalDates = fundTransactions
.filter((f) => f.amount < 0)
.map((f) => f.date)
.sort();
const stageMap = new Map();
for (const d of displayPnL) {
const stage = cfg?.stagesSameDay === true
? sortedWithdrawalDates.filter((wd) => wd === d.date).length + 1
: sortedWithdrawalDates.filter((wd) => wd < d.date).length + 1;
stageMap.set(d.date, stage);
}
return (
{projection.length > 0 && (
Dashed outlines: the perfect path, two payouts ahead — planned targets daily, the projected withdrawal on each cycle's final day, % = odds of reaching that day
)}