Add per-stage withdrawal targets with consistency and min trading days

- Add withdrawal stage system: each stage defines profit target, consistency,
  and min trading days for post-withdrawal challenge cycles
- Target Same Equity mode accounts for withdrawn amounts when computing
  effective profit target (profitTarget - remainingProfit)
- Store fund transaction timestamps for time-aware cycle filtering
  (withdrawals before 9 AM CT include that day in new cycle)
- Expose full P&L history (fullDailyPnL) for calendar/equity curve display
  across all cycles, with DB fallback for pre-restart data
- Show stage number (#1, #2, etc.) on calendar cells
- Hide consistency reference line when consistency is 0% or 100%
- Settings UI: "After First W/D" column with same-equity checkbox,
  expandable stage sub-rows with profit/consistency/days inputs
- Default target_same_equity to 1 for new and existing account configs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Brandon Li
2026-03-21 05:27:13 -05:00
co-authored by Claude Opus 4.6
parent c54073e4b8
commit 70b1362d3e
11 changed files with 384 additions and 48 deletions
+40 -20
View File
@@ -86,7 +86,7 @@ const MONTH_NAMES = [
];
const DOW_LABELS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
function CalendarMonth({ year, month, pnlMap, fundMap }: { year: number; month: number; pnlMap: Map<string, number>; fundMap: Map<string, number> }) {
function CalendarMonth({ year, month, pnlMap, fundMap, stageMap }: { year: number; month: number; pnlMap: Map<string, number>; fundMap: Map<string, number>; stageMap: Map<string, number> }) {
const daysInMonth = new Date(year, month, 0).getDate();
const firstDow = new Date(year, month - 1, 1).getDay(); // 0 = Sunday
@@ -133,12 +133,13 @@ function CalendarMonth({ year, month, pnlMap, fundMap }: { year: number; month:
const key = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
const pnl = pnlMap.get(key);
const fundAmt = fundMap.get(key);
const stage = stageMap.get(key);
const hasData = pnl !== undefined;
const positive = hasData && pnl! >= 0;
return (
<div
key={key}
className={`rounded-lg px-1.5 pt-1.5 pb-2 min-h-14 flex flex-col ${
className={`rounded-lg px-1.5 pt-1.5 pb-2 min-h-14 flex flex-col relative ${
hasData
? positive
? 'bg-green-50 border border-green-100'
@@ -148,11 +149,18 @@ function CalendarMonth({ year, month, pnlMap, fundMap }: { year: number; month:
: 'bg-slate-50 border border-transparent'
}`}
>
<span className={`text-[11px] font-medium leading-none mb-1.5 ${
hasData ? (positive ? 'text-green-700' : 'text-red-600') : fundAmt !== undefined ? 'text-amber-700' : 'text-slate-400'
}`}>
{day}
</span>
<div className="flex items-start justify-between">
<span className={`text-[11px] font-medium leading-none ${
hasData ? (positive ? 'text-green-700' : 'text-red-600') : fundAmt !== undefined ? 'text-amber-700' : 'text-slate-400'
}`}>
{day}
</span>
{stage !== undefined && (
<span className="text-[8px] font-semibold text-slate-400 leading-none">
#{stage}
</span>
)}
</div>
{hasData && (
<span className={`text-[11px] font-bold tabular-nums leading-tight ${
positive ? 'text-green-700' : 'text-red-600'
@@ -220,8 +228,9 @@ export default function AccountPage() {
);
}
// dailyPnL comes from state — same source as dailyTarget, no separate fetch needed.
// 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]));
@@ -245,17 +254,17 @@ export default function AccountPage() {
// 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 = dailyPnL.length > 0 ? Math.max(...dailyPnL.filter(d => d.pnl > 0).map(d => d.pnl)) : 0;
const consistencyTarget = cfg && cfg.consistency > 0 && maxDayPnL > 0
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([...dailyPnL.map((d) => d.date), ...fundTransactions.map((f) => f.date)]);
const allDates = new Set([...displayPnL.map((d) => d.date), ...fundTransactions.map((f) => f.date)]);
const eventsByDate = new Map<string, EquityEvent>();
for (const d of dailyPnL) eventsByDate.set(d.date, { date: d.date, pnl: d.pnl });
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 });
@@ -304,10 +313,21 @@ export default function AccountPage() {
const strokeGradId = 'equityStroke';
// Build calendar data
const pnlMap = new Map(dailyPnL.map((d) => [d.date, d.pnl]));
const allCalendarDates = [...dailyPnL.map((d) => d.date), ...fundTransactions.map((f) => f.date)];
const pnlMap = new Map(displayPnL.map((d) => [d.date, d.pnl]));
const allCalendarDates = [...displayPnL.map((d) => d.date), ...fundTransactions.map((f) => f.date)];
const calendarMonths = [...new Set(allCalendarDates.map((d) => d.slice(0, 7)))].sort();
// Build stage map: stage increments after each withdrawal (negative fund txn)
const sortedWithdrawalDates = fundTransactions
.filter((f) => f.amount < 0)
.map((f) => f.date)
.sort();
const stageMap = new Map<string, number>();
for (const d of displayPnL) {
const stage = sortedWithdrawalDates.filter((wd) => wd < d.date).length + 1;
stageMap.set(d.date, stage);
}
return (
<div className="min-h-screen bg-slate-50 p-8">
<div className="max-w-7xl mx-auto">
@@ -388,13 +408,13 @@ export default function AccountPage() {
<div className="bg-white border border-slate-200 rounded-xl shadow-sm p-6 mb-5">
<div className="flex items-center justify-between mb-4">
<h2 className="text-slate-900 font-bold text-base">Equity Curve</h2>
{dailyPnL.length > 0 && (
{displayPnL.length > 0 && (
<span className={`text-sm font-bold tabular-nums ${isPositive ? 'text-green-600' : 'text-red-500'}`}>
{isPositive ? '+' : ''}${fmt(totalProfit)}
</span>
)}
</div>
{dailyPnL.length === 0 ? (
{displayPnL.length === 0 ? (
<p className="text-slate-400 italic text-sm text-center py-8">No trading history available</p>
) : (
<ResponsiveContainer width="100%" height={260}>
@@ -485,7 +505,7 @@ export default function AccountPage() {
strokeDasharray="4 3"
label={{
value: 'W/D',
position: 'insideTopRight',
position: 'insideBottomRight',
fontSize: 10,
fontWeight: 700,
fill: '#d97706',
@@ -552,14 +572,14 @@ export default function AccountPage() {
<div className="grid grid-cols-1 gap-8" style={{ gridTemplateColumns: `repeat(${Math.min(calendarMonths.length, 3)}, minmax(0, 1fr))` }}>
{calendarMonths.map((ym) => {
const [y, m] = ym.split('-').map(Number);
return <CalendarMonth key={ym} year={y} month={m} pnlMap={pnlMap} fundMap={fundMap} />;
return <CalendarMonth key={ym} year={y} month={m} pnlMap={pnlMap} fundMap={fundMap} stageMap={stageMap} />;
})}
</div>
</div>
)}
{/* Cash History Table */}
{(dailyPnL.length > 0 || fundTransactions.length > 0) && (
{(displayPnL.length > 0 || fundTransactions.length > 0) && (
<div className="bg-white border border-slate-200 rounded-xl shadow-sm p-6 mt-5">
<h2 className="text-slate-900 font-bold text-base mb-4">Cash History</h2>
<div className="overflow-x-auto">
@@ -573,7 +593,7 @@ export default function AccountPage() {
</thead>
<tbody>
{[
...dailyPnL.map((d) => ({ date: d.date, type: 'Trade' as const, amount: d.pnl })),
...displayPnL.map((d) => ({ date: d.date, type: 'Trade' as const, amount: d.pnl })),
...fundTransactions.map((f) => ({ date: f.date, type: 'W/D' as const, amount: f.amount })),
]
.sort((a, b) => b.date.localeCompare(a.date))
+5 -1
View File
@@ -21,9 +21,11 @@ export async function PUT(
accountSize?: number;
maxLoss?: number;
maxPositionSize?: number;
targetSameEquity?: boolean;
withdrawalStages?: { profit: number; consistency: number; minTradingDays: number }[];
};
const { prefix, profitTarget, consistency, minDayPnL, minTradingDays, accountSize, maxLoss, maxPositionSize } = body;
const { prefix, profitTarget, consistency, minDayPnL, minTradingDays, accountSize, maxLoss, maxPositionSize, targetSameEquity, withdrawalStages } = body;
if (
typeof prefix !== 'string' || !prefix.trim() ||
@@ -46,6 +48,8 @@ export async function PUT(
accountSize,
maxLoss: maxLoss ?? 0,
maxPositionSize: maxPositionSize ?? 0,
targetSameEquity: targetSameEquity ?? false,
withdrawalStages: withdrawalStages ?? [],
});
if (!updated) {
+7 -1
View File
@@ -25,9 +25,11 @@ export async function POST(
accountSize?: number;
maxLoss?: number;
maxPositionSize?: number;
targetSameEquity?: boolean;
withdrawalStages?: { profit: number; consistency: number; minTradingDays: number }[];
};
const { prefix, profitTarget, consistency, minDayPnL, minTradingDays, accountSize, maxLoss, maxPositionSize } = body;
const { prefix, profitTarget, consistency, minDayPnL, minTradingDays, accountSize, maxLoss, maxPositionSize, targetSameEquity, withdrawalStages } = body;
if (
typeof prefix !== 'string' || !prefix.trim() ||
@@ -50,6 +52,8 @@ export async function POST(
accountSize,
maxLoss: maxLoss ?? 0,
maxPositionSize: maxPositionSize ?? 0,
targetSameEquity: targetSameEquity ?? false,
withdrawalStages: withdrawalStages ?? [],
});
return NextResponse.json({
@@ -62,6 +66,8 @@ export async function POST(
accountSize: row.account_size,
maxLoss: row.max_loss,
maxPositionSize: row.max_position_size,
targetSameEquity: row.target_same_equity === 1,
withdrawalStages: (() => { try { return JSON.parse(row.withdrawal_stages ?? '[]') as { profit: number; consistency: number; minTradingDays: number }[]; } catch { return []; } })(),
}, { status: 201 });
} catch (err) {
console.error('[POST /api/firms/:id/accounts]', err);
+2
View File
@@ -33,6 +33,8 @@ export async function GET(
accountSize: a.account_size,
maxLoss: a.max_loss,
maxPositionSize: a.max_position_size,
targetSameEquity: a.target_same_equity === 1,
withdrawalStages: (() => { try { return JSON.parse(a.withdrawal_stages ?? '[]') as { profit: number; consistency: number; minTradingDays: number }[]; } catch { return []; } })(),
})),
});
}
+22 -5
View File
@@ -1,7 +1,7 @@
import { NextResponse } from 'next/server';
import { getFirms } from '@/lib/db';
import { getFirms, loadDailyPnL } from '@/lib/db';
import { getClients } from '@/lib/clients';
import { computeDailyTarget } from '@/lib/trading-logic';
import { computeDailyTarget, resolveEffectiveConfig } from '@/lib/trading-logic';
import type { AccountConfigRow } from '@/lib/db';
function getAccountConfig(name: string, accounts: AccountConfigRow[]): AccountConfigRow | undefined {
@@ -30,16 +30,32 @@ export async function GET() {
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 target = computeDailyTarget(cfg.profit_target, cfg.consistency, totalProfit, dailyPnL, cfg.min_day_pnl, cfg.min_trading_days);
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 target = computeDailyTarget(effective.profitTarget, effective.consistency, totalProfit, dailyPnL, cfg.min_day_pnl, effective.minTradingDays);
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) ||
(target.amount === 0 && Math.abs(cash.realizedPnL) > 0 && client.daysTraded[acc.id] <= effective.minTradingDays) ||
(cash.realizedPnL >= target.amount);
}
@@ -56,7 +72,8 @@ export async function GET() {
targetHit,
dailyTarget,
dailyPnL,
fundTransactions: client.fundTransactions[acc.id] ?? [],
fullDailyPnL: client.fullDailyPnL?.[acc.id] ?? loadDailyPnL(acc.id),
fundTransactions: displayFundTxns,
};
});
return { firm: f.name, connected: true, accounts, perContractFees: client.perContractFees };
+130 -4
View File
@@ -1,6 +1,6 @@
'use client';
import { useEffect, useState } from 'react';
import React, { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
const SIZE_PRESETS = [5_000, 10_000, 25_000, 50_000, 75_000, 100_000, 150_000];
@@ -14,6 +14,8 @@ interface AccountConfig {
minTradingDays: number;
accountSize: number;
maxPositionSize: number;
targetSameEquity: boolean;
withdrawalStages: { profit: number; consistency: number; minTradingDays: number }[];
}
interface FirmConfig {
@@ -51,6 +53,8 @@ function newRow(): RowState {
minTradingDays: 5,
accountSize: 50_000,
maxPositionSize: 0,
targetSameEquity: true,
withdrawalStages: [],
dirty: true,
saving: false,
error: '',
@@ -148,6 +152,8 @@ export default function FirmSettingsPage() {
minTradingDays: row.minTradingDays,
accountSize: row.accountSize,
maxPositionSize: row.maxPositionSize,
targetSameEquity: row.targetSameEquity,
withdrawalStages: row.withdrawalStages,
};
if (row.id < 0) {
@@ -257,20 +263,22 @@ export default function FirmSettingsPage() {
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Min Day P&L</th>
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Min Trading Days</th>
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Max Contracts</th>
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">After First W/D</th>
<th className="px-3 py-3 w-32" />
</tr>
</thead>
<tbody>
{rows.length === 0 && firmName && (
<tr>
<td colSpan={8} className="px-4 py-6 text-center text-sm text-slate-400 italic">
<td colSpan={9} className="px-4 py-6 text-center text-sm text-slate-400 italic">
No account types yet
</td>
</tr>
)}
{rows.map((row) => (
<tr key={row.id} className="border-b border-slate-100 last:border-0">
<React.Fragment key={row.id}>
<tr className="border-b border-slate-100 last:border-0">
{/* Prefix */}
<td className="px-4 py-2.5">
@@ -405,6 +413,21 @@ export default function FirmSettingsPage() {
/>
</td>
{/* After Withdrawal */}
<td className="px-4 py-2.5">
<label className="flex items-center gap-1.5 cursor-pointer select-none">
<input
type="checkbox"
checked={row.targetSameEquity}
onChange={(e) =>
updateRow(row.id, { targetSameEquity: e.target.checked })
}
className="rounded border-slate-300 text-blue-500 focus:ring-blue-400"
/>
<span className="text-xs text-slate-600">Same equity</span>
</label>
</td>
{/* Actions */}
<td className="px-3 py-2.5">
<div className="flex items-center justify-end gap-1.5">
@@ -449,11 +472,114 @@ export default function FirmSettingsPage() {
</div>
</td>
</tr>
{/* Stage sub-rows — shown when targetSameEquity is OFF */}
{!row.targetSameEquity && (
<>
{row.withdrawalStages.map((stage, idx) => {
const isLast = idx === row.withdrawalStages.length - 1;
const showPlus = isLast && row.withdrawalStages.length > 1;
return (
<tr key={`${row.id}-stage-${idx}`} className="bg-slate-50/60 border-b border-slate-100 last:border-0">
<td colSpan={9} className="pl-10 pr-4 py-1.5">
<div className="flex items-center gap-3">
<span className="text-xs text-slate-400 w-16 shrink-0">
Stage {idx + 2}{showPlus ? '+' : ''}
</span>
<div className="relative flex items-center">
<span className="absolute left-2 text-slate-400 text-xs pointer-events-none">$</span>
<input
type="number"
className="border border-slate-200 rounded px-1.5 py-1 pl-4 text-xs text-slate-800 focus:outline-none focus:ring-1 focus:ring-blue-400 bg-white w-24"
value={stage.profit}
min={0}
step={100}
placeholder="Profit"
onChange={(e) => {
const next = row.withdrawalStages.map((s, i) =>
i === idx ? { ...s, profit: Number(e.target.value) } : s
);
updateRow(row.id, { withdrawalStages: next });
}}
/>
</div>
{row.consistency > 0 && (
<div className="relative flex items-center">
<input
type="number"
className="border border-slate-200 rounded px-1.5 py-1 pr-5 text-xs text-slate-800 focus:outline-none focus:ring-1 focus:ring-blue-400 bg-white w-20"
value={Math.round(stage.consistency * 100)}
min={0}
max={100}
step={1}
placeholder="Cons%"
onChange={(e) => {
const next = row.withdrawalStages.map((s, i) =>
i === idx ? { ...s, consistency: Number(e.target.value) / 100 } : s
);
updateRow(row.id, { withdrawalStages: next });
}}
/>
<span className="absolute right-1.5 text-slate-400 text-xs pointer-events-none">%</span>
</div>
)}
<div className="flex items-center gap-1">
<input
type="number"
className="border border-slate-200 rounded px-1.5 py-1 text-xs text-slate-800 focus:outline-none focus:ring-1 focus:ring-blue-400 bg-white w-12"
value={stage.minTradingDays}
min={0}
step={1}
placeholder="Days"
onChange={(e) => {
const next = row.withdrawalStages.map((s, i) =>
i === idx ? { ...s, minTradingDays: Number(e.target.value) } : s
);
updateRow(row.id, { withdrawalStages: next });
}}
/>
<span className="text-slate-400 text-[10px] shrink-0">days</span>
</div>
<button
onClick={() => {
const next = row.withdrawalStages.filter((_, i) => i !== idx);
updateRow(row.id, { withdrawalStages: next });
}}
className="text-slate-300 hover:text-red-400 text-sm leading-none"
title="Remove stage"
>
×
</button>
</div>
</td>
</tr>
);
})}
<tr className="bg-slate-50/60 border-b border-dashed border-slate-200">
<td colSpan={9} className="pl-10 pr-4 py-1">
<button
onClick={() =>
updateRow(row.id, {
withdrawalStages: [
...row.withdrawalStages,
{ profit: row.profitTarget, consistency: row.consistency, minTradingDays: row.minTradingDays },
],
})
}
className="text-xs text-blue-400 hover:text-blue-600"
>
+ Add stage
</button>
</td>
</tr>
</>
)}
</React.Fragment>
))}
{/* Add row */}
<tr className="border-t border-dashed border-slate-200">
<td colSpan={8} className="px-2 py-2">
<td colSpan={9} className="px-2 py-2">
<button
onClick={() => setRows((prev) => [...prev, newRow()])}
className="w-full py-1.5 text-sm text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-lg transition-colors"