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>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
95e7433941
commit
570a54fe60
@@ -15,12 +15,6 @@ import {
|
||||
Dot,
|
||||
} from 'recharts';
|
||||
import type { FirmConfig, FirmState, AccountState, AccountConfig } from '@/types';
|
||||
import { computeDailyTarget } from '@/lib/trading-logic';
|
||||
|
||||
interface DailyPnL {
|
||||
date: string;
|
||||
pnl: number;
|
||||
}
|
||||
|
||||
function getAccountConfig(name: string, firm: FirmConfig): AccountConfig | undefined {
|
||||
return [...firm.accounts]
|
||||
@@ -178,20 +172,15 @@ export default function AccountPage() {
|
||||
const [account, setAccount] = useState<AccountState | null>(null);
|
||||
const [cfg, setCfg] = useState<AccountConfig | null>(null);
|
||||
const [firmName, setFirmName] = useState('');
|
||||
const [dailyPnL, setDailyPnL] = useState<DailyPnL[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
const [stateRes, firmsRes, dailyRes] = await Promise.all([
|
||||
const [stateRes, firmsRes] = await Promise.all([
|
||||
fetch('/api/state'),
|
||||
fetch('/api/firms'),
|
||||
fetch(`/api/accounts/${accountId}/daily-pnl`),
|
||||
]);
|
||||
const states: FirmState[] = await stateRes.json();
|
||||
const firms: FirmConfig[] = await firmsRes.json();
|
||||
const daily: DailyPnL[] = await dailyRes.json();
|
||||
|
||||
setDailyPnL(daily);
|
||||
|
||||
for (const firmState of states) {
|
||||
const acc = firmState.accounts.find((a) => a.id === accountId);
|
||||
@@ -223,6 +212,9 @@ export default function AccountPage() {
|
||||
);
|
||||
}
|
||||
|
||||
// dailyPnL comes from state — same source as dailyTarget, no separate fetch needed.
|
||||
const dailyPnL = account.dailyPnL;
|
||||
|
||||
const hasLossLimit = cfg != null && cfg.minDayPnL !== -999;
|
||||
const daysPassed = cfg != null && account.daysTraded >= cfg.minTradingDays;
|
||||
// Dead when balance hits Tradovate's auto-liquidation floor
|
||||
@@ -237,15 +229,14 @@ export default function AccountPage() {
|
||||
: Math.round(fifoTotal * 100) / 100;
|
||||
const profitPct = cfg?.accountSize ? (totalProfit / cfg.accountSize) * 100 : null;
|
||||
const profitPassed = cfg != null && totalProfit >= cfg.profitTarget;
|
||||
const dailyTarget = cfg && !isDead
|
||||
? computeDailyTarget(cfg.profitTarget, cfg.consistency, totalProfit, dailyPnL)
|
||||
: null;
|
||||
// dailyTarget is computed server-side in the state API — single source of truth.
|
||||
const dailyTarget = account.dailyTarget ?? null;
|
||||
const lossPassed = !hasLossLimit || (cfg != null && totalProfit >= cfg.minDayPnL);
|
||||
|
||||
// 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 && maxDayPnL > 0
|
||||
const consistencyTarget = cfg && cfg.consistency > 0 && maxDayPnL > 0
|
||||
? Math.round(maxDayPnL / cfg.consistency * 100) / 100
|
||||
: null;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getClients, resetClients } from '@/lib/clients';
|
||||
import { getFirms } from '@/lib/db';
|
||||
import axios from 'axios';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
@@ -83,6 +84,96 @@ export async function POST() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/debug — probe Tradovate APIs using a firm's access token.
|
||||
*
|
||||
* Generic proxy: { firmId, path?, url?, method?, body? }
|
||||
* Full report run: { firmId, action: 'report', account, startDate, endDate }
|
||||
* → does requestreport + getreport polling in one server-side call, returns raw data string
|
||||
*/
|
||||
export async function PATCH(req: Request) {
|
||||
try {
|
||||
const payload = await req.json();
|
||||
const { firmId } = payload;
|
||||
const client = getClients().get(firmId) as any;
|
||||
if (!client?.accessInfo?.accessToken) {
|
||||
return NextResponse.json({ error: 'no token for firmId ' + firmId }, { status: 400 });
|
||||
}
|
||||
const headers = { Authorization: `Bearer ${client.accessInfo.accessToken}` };
|
||||
|
||||
// Full report cycle
|
||||
if (payload.action === 'report') {
|
||||
const { account, startDate, endDate } = payload;
|
||||
try {
|
||||
let reportData = (await axios.post(
|
||||
'https://rpt-demo.tradovateapi.com/v1/reports/requestreport',
|
||||
{
|
||||
name: 'Fills', representationType: 'json', timezone: -300,
|
||||
params: [
|
||||
{ name: 'startDate', value: startDate },
|
||||
{ name: 'endDate', value: endDate },
|
||||
{ name: 'startTime', value: '00:00:00' },
|
||||
{ name: 'endTime', value: '00:00:00' },
|
||||
...(account ? [{ name: 'account', value: account }] : []),
|
||||
],
|
||||
},
|
||||
{ headers }
|
||||
)).data;
|
||||
|
||||
let attempts = 0;
|
||||
while (reportData?.['p-ticket'] && attempts < 30) {
|
||||
const ticket: string = reportData['p-ticket'];
|
||||
const wait: number = Math.max(1, reportData['p-time'] ?? 1);
|
||||
await new Promise((r) => setTimeout(r, wait * 1000));
|
||||
reportData = (await axios.get(
|
||||
'https://rpt-demo.tradovateapi.com/v1/reports/getreport',
|
||||
{ params: { 'p-ticket': ticket }, headers }
|
||||
)).data;
|
||||
attempts++;
|
||||
}
|
||||
|
||||
const raw: string = typeof reportData?.data === 'string' ? reportData.data : JSON.stringify(reportData);
|
||||
// Parse to count fills and unique tradeDates
|
||||
let fillCount = 0;
|
||||
let uniqueDates: string[] = [];
|
||||
try {
|
||||
const fixed = raw.replace(/"_tradeDate":\s*(\d{4}-\d{2}-\d{2})/g, '"_tradeDate": "$1"');
|
||||
const parsed: any[] = JSON.parse(fixed);
|
||||
fillCount = parsed.length;
|
||||
uniqueDates = [...new Set(parsed.map((f) => f._tradeDate as string))].sort();
|
||||
} catch { /* not parseable yet */ }
|
||||
return NextResponse.json({ ok: true, attempts, rawLen: raw.length, fillCount, uniqueDates, preview: raw.slice(0, 400) });
|
||||
} catch (err: any) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
status: err?.response?.status,
|
||||
data: err?.response?.data,
|
||||
message: err?.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Generic proxy
|
||||
const { path, url: rawUrl, method = 'GET', body: reqBody } = payload;
|
||||
const url = rawUrl ?? `https://demo.tradovateapi.com/v1/${path}`;
|
||||
try {
|
||||
const res = method === 'POST'
|
||||
? await axios.post(url, reqBody, { headers })
|
||||
: await axios.get(url, { headers });
|
||||
return NextResponse.json({ ok: true, status: res.status, data: res.data });
|
||||
} catch (err: any) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
status: err?.response?.status,
|
||||
data: err?.response?.data,
|
||||
message: err?.message,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: String(err) }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/debug — force-reinitialize all Tradovate clients with fresh instances
|
||||
* Clears the global pool so getClients() recreates everything from DB on next call.
|
||||
|
||||
+10
-4
@@ -26,11 +26,15 @@ export async function GET() {
|
||||
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
|
||||
// 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;
|
||||
if (cfg) {
|
||||
const target = computeDailyTarget(cfg.profit_target, cfg.consistency, totalProfit, dailyPnL);
|
||||
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 =
|
||||
@@ -47,9 +51,11 @@ export async function GET() {
|
||||
realizedPnL: cash.realizedPnL,
|
||||
daysTraded,
|
||||
hasPosition: !!client.positions[acc.id],
|
||||
autoLiqThreshold: client.autoLiqThresholds[acc.id] ?? 0,
|
||||
autoLiqThreshold,
|
||||
totalProfit,
|
||||
targetHit,
|
||||
dailyTarget,
|
||||
dailyPnL,
|
||||
};
|
||||
});
|
||||
return { firm: f.name, connected: true, accounts, perContractFees: client.perContractFees };
|
||||
|
||||
Reference in New Issue
Block a user