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
+35
-43
@@ -36,7 +36,7 @@ export class TradovateClient {
|
||||
public fetchDaysComplete = false;
|
||||
/** Last error per account name from fetchDaysTraded() */
|
||||
public lastFetchErrors: Record<string, string> = {};
|
||||
/** Raw reports API response data per account (first 200 chars) for debugging */
|
||||
/** Raw reports API response sample per account (first 100 chars) for debugging */
|
||||
public lastFetchRaw: Record<string, string> = {};
|
||||
|
||||
public products: { id: number; name: string }[] = [];
|
||||
@@ -315,9 +315,12 @@ export class TradovateClient {
|
||||
if (!this.accessInfo?.accessToken) return;
|
||||
this.fetchDaysComplete = false;
|
||||
|
||||
const authHeaders = { Authorization: `Bearer ${this.accessInfo.accessToken}` };
|
||||
|
||||
const now = new Date();
|
||||
now.setDate(now.getDate() + 1); // endDate must be tomorrow — report server excludes today's fills when endDate=today
|
||||
const start = new Date();
|
||||
start.setDate(start.getDate() - 28);
|
||||
start.setDate(start.getDate() - 27); // keep total window ≤ 28 days
|
||||
|
||||
const fmtDate = (d: Date) => {
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
@@ -325,29 +328,36 @@ export class TradovateClient {
|
||||
return `${m}/${day}/${d.getFullYear()}`;
|
||||
};
|
||||
|
||||
type Fill = {
|
||||
_tradeDate: string;
|
||||
_timestamp: string;
|
||||
_action: number; // 0 = Buy, 1 = Sell
|
||||
_qty: number;
|
||||
_price: number;
|
||||
Product: string;
|
||||
commission: number;
|
||||
};
|
||||
|
||||
interface Lot { price: number; qty: number; commPerUnit: number }
|
||||
|
||||
for (const account of this.accountList) {
|
||||
try {
|
||||
const authHeaders = { Authorization: `Bearer ${this.accessInfo.accessToken}` };
|
||||
|
||||
// Step 1 — request the report
|
||||
let reportData = (await axios.post(
|
||||
'https://rpt-demo.tradovateapi.com/v1/reports/requestreport',
|
||||
{
|
||||
name: 'Fills',
|
||||
name: 'Fills', representationType: 'json', timezone: -300,
|
||||
params: [
|
||||
{ name: 'startDate', value: fmtDate(start) },
|
||||
{ name: 'endDate', value: fmtDate(now) },
|
||||
{ name: 'endDate', value: fmtDate(now) },
|
||||
{ name: 'startTime', value: '00:00:00' },
|
||||
{ name: 'endTime', value: '00:00:00' },
|
||||
{ name: 'account', value: account.name },
|
||||
{ name: 'endTime', value: '00:00:00' },
|
||||
{ name: 'account', value: account.name },
|
||||
],
|
||||
representationType: 'json',
|
||||
timezone: 0,
|
||||
},
|
||||
{ headers: authHeaders }
|
||||
)).data;
|
||||
|
||||
// Step 2 — if the report is queued, poll until it's ready
|
||||
// Poll if queued — getreport also requires the bearer token
|
||||
let pollAttempts = 0;
|
||||
while (reportData?.['p-ticket'] && pollAttempts < 30) {
|
||||
const pTicket: string = reportData['p-ticket'];
|
||||
@@ -361,30 +371,14 @@ export class TradovateClient {
|
||||
}
|
||||
|
||||
if (!this.lastFetchRaw) this.lastFetchRaw = {};
|
||||
this.lastFetchRaw[account.name] = JSON.stringify(reportData).slice(0, 500);
|
||||
const raw: string = typeof reportData?.data === 'string' ? reportData.data : '[]';
|
||||
this.lastFetchRaw[account.name] = raw.slice(0, 100);
|
||||
|
||||
// _tradeDate is unquoted in the response (invalid JSON), but the "Date" field
|
||||
// ("M/D/YY") is a valid quoted string that already reflects CME trade date.
|
||||
const rawResponse = reportData?.data ?? '[]';
|
||||
const raw: string = String(rawResponse)
|
||||
.replace(/"_tradeDate":\s*(\d{4}-\d{2}-\d{2})/g, '"_tradeDate": "$1"');
|
||||
type Fill = {
|
||||
_tradeDate: string;
|
||||
_timestamp: string;
|
||||
_action: number; // 0 = Buy, 1 = Sell
|
||||
_qty: number;
|
||||
_price: number;
|
||||
Product: string;
|
||||
commission: number;
|
||||
};
|
||||
const fills: Fill[] = JSON.parse(raw);
|
||||
// _tradeDate is unquoted in the response (invalid JSON) — fix before parsing
|
||||
const fixed = raw.replace(/"_tradeDate":\s*(\d{4}-\d{2}-\d{2})/g, '"_tradeDate": "$1"');
|
||||
const fills: Fill[] = JSON.parse(fixed);
|
||||
|
||||
// POINT_VALUES imported from trading-logic.ts
|
||||
|
||||
// FIFO P&L computation: match buy/sell fills into round-trips
|
||||
// Both the opening and closing commissions are deducted on close.
|
||||
const sorted = [...fills].sort((a, b) => a._timestamp.localeCompare(b._timestamp));
|
||||
interface Lot { price: number; qty: number; commPerUnit: number }
|
||||
const longBook: Lot[] = [];
|
||||
const shortBook: Lot[] = [];
|
||||
const dailyMap: { [date: string]: number } = {};
|
||||
@@ -396,13 +390,12 @@ export class TradovateClient {
|
||||
const commPerUnit = fill._qty > 0 ? fill.commission / fill._qty : 0;
|
||||
|
||||
if (isBuy) {
|
||||
// Close any short lots first (FIFO), then open long
|
||||
while (remaining > 0 && shortBook.length > 0) {
|
||||
const lot = shortBook[0];
|
||||
const closed = Math.min(lot.qty, remaining);
|
||||
const pnl = (lot.price - fill._price) * closed * pointValue
|
||||
- (commPerUnit * closed) // closing fill commission
|
||||
- (lot.commPerUnit * closed); // opening fill commission
|
||||
- (commPerUnit * closed)
|
||||
- (lot.commPerUnit * closed);
|
||||
dailyMap[fill._tradeDate] = (dailyMap[fill._tradeDate] ?? 0) + pnl;
|
||||
lot.qty -= closed;
|
||||
remaining -= closed;
|
||||
@@ -410,13 +403,12 @@ export class TradovateClient {
|
||||
}
|
||||
if (remaining > 0) longBook.push({ price: fill._price, qty: remaining, commPerUnit });
|
||||
} else {
|
||||
// Close any long lots first (FIFO), then open short
|
||||
while (remaining > 0 && longBook.length > 0) {
|
||||
const lot = longBook[0];
|
||||
const closed = Math.min(lot.qty, remaining);
|
||||
const pnl = (fill._price - lot.price) * closed * pointValue
|
||||
- (commPerUnit * closed) // closing fill commission
|
||||
- (lot.commPerUnit * closed); // opening fill commission
|
||||
- (commPerUnit * closed)
|
||||
- (lot.commPerUnit * closed);
|
||||
dailyMap[fill._tradeDate] = (dailyMap[fill._tradeDate] ?? 0) + pnl;
|
||||
lot.qty -= closed;
|
||||
remaining -= closed;
|
||||
@@ -431,13 +423,13 @@ export class TradovateClient {
|
||||
.sort((a, b) => a.date.localeCompare(b.date));
|
||||
|
||||
this.dailyPnL[account.id] = entries;
|
||||
// Count only positive-P&L days — consistent with computeDailyTarget's positiveDays
|
||||
this.daysTraded[account.id] = entries.filter(d => d.pnl > 0).length;
|
||||
this.daysTraded[account.id] = entries.filter((d) => d.pnl !== 0).length;
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? `${err.message}` : String(err);
|
||||
console.error(`[fetchDaysTraded] ${account.name}:`, msg);
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error(`[fetchDaysTraded] report error for ${account.name}:`, msg);
|
||||
if (!this.lastFetchErrors) this.lastFetchErrors = {};
|
||||
this.lastFetchErrors[account.name] = msg;
|
||||
this.dailyPnL[account.id] ??= [];
|
||||
this.daysTraded[account.id] ??= 0;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user