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
@@ -163,6 +163,11 @@ export async function runTrade(action: 'Buy' | 'Sell', symbol: string) {
|
||||
const exitAction: 'Buy' | 'Sell' = action === 'Buy' ? 'Sell' : 'Buy';
|
||||
const exitFill = await client.sendOrder(acc.id, mnqContract.name, 1, exitAction, 'Market');
|
||||
|
||||
// Refresh daily P&L immediately after the extra-day round-trip completes
|
||||
client.fetchDaysTraded().catch((err) =>
|
||||
console.error('[auto-trade] post-fill fetchDaysTraded error:', err)
|
||||
);
|
||||
|
||||
console.log(`[auto-trade] ${acc.name} (${item.firmName}) extra-day: ${action} 1xMNQ @ ${fill.price} | exited @ ${exitFill.price} (market)`);
|
||||
|
||||
return {
|
||||
@@ -204,6 +209,15 @@ export async function runTrade(action: 'Buy' | 'Sell', symbol: string) {
|
||||
const exitAction: 'Buy' | 'Sell' = action === 'Buy' ? 'Sell' : 'Buy';
|
||||
const exitOrder = await client.placeOrderNoWait(acc.id, contract.name, contracts, exitAction, 'Limit', exitPrice);
|
||||
|
||||
// Refresh daily P&L as soon as the exit limit order fills
|
||||
if (exitOrder.orderId != null) {
|
||||
client.onFill(exitOrder.orderId, () => {
|
||||
client.fetchDaysTraded().catch((err) =>
|
||||
console.error('[auto-trade] post-fill fetchDaysTraded error:', err)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`[auto-trade] ${acc.name} (${item.firmName}) ${action} ${contracts}x${symbol} @ ${fill.price} | target $${target.amount} [${target.path}] (+$${totalCommission.toFixed(2)} comm) | exit @ ${exitPrice} (orderId=${exitOrder.orderId})`);
|
||||
|
||||
return {
|
||||
|
||||
@@ -35,8 +35,8 @@ export function computeDailyTarget(
|
||||
minDayPnL: number = 0, // -999 or 0 = no minimum per day
|
||||
minTradingDays: number = 0 // 0 = no minimum trading days
|
||||
): { amount: number; path: 'first_day' | 'normal_day' | 'reduced_day' } {
|
||||
const positiveDays = dailyPnL.filter((d) => d.pnl > 0);
|
||||
const daysTraded = positiveDays.length;
|
||||
const qualifyingDays = minDayPnL === 0 ? dailyPnL : dailyPnL.filter((d) => d.pnl >= minDayPnL);
|
||||
const daysTraded = qualifyingDays.length;
|
||||
|
||||
// --- Base target via consistency logic ---
|
||||
let baseAmount: number;
|
||||
@@ -45,8 +45,13 @@ export function computeDailyTarget(
|
||||
if (daysTraded === 0) {
|
||||
baseAmount = profitTarget * consistency;
|
||||
path = 'first_day';
|
||||
} else if (consistency === 0) {
|
||||
// 0% consistency means no consistency rule to satisfy — base amount is always $0.
|
||||
// The min-day reservation block below handles any mandatory-day targeting.
|
||||
baseAmount = 0;
|
||||
path = 'reduced_day';
|
||||
} else {
|
||||
const maxDay = Math.max(...positiveDays.map((d) => d.pnl));
|
||||
const maxDay = Math.max(...qualifyingDays.map((d) => d.pnl));
|
||||
const realTarget = maxDay / consistency;
|
||||
const needed = realTarget - totalProfit;
|
||||
|
||||
|
||||
+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