Add auto-trade scheduler with batch locking, commission gross-up, and sync gate

- Auto-trade scheduler fires every 60s; uses Promise.allSettled batch so no new trades fire while any position from the current batch is open
- Commission gross-up: read entryCommission from cash.realizedPnL after fill (fallback 2.5×contracts), grossTarget = target + 2×entryCommission
- Sync gate: TradovateClient.syncComplete flag; scheduler skips tick until every client finishes initial position/balance sync
- Contracts formula changed to Math.ceil so $1500 target = 2 contracts
- Removed all fee caching (perContractFees, recentFills, fillFee handler) from tradovate-class.ts
- Removed firm_fees table, getFirmFees, upsertFirmFee from db.ts
- Deleted instrument-configs API routes; removed Fees UI from firm settings page
- /api/instruments returns full {symbol, enabled}[] objects; dashboard filters to enabled-only for trade selector
- Added auto-trade, debug, orders, settings, and trade API routes
- Instrument selector on dashboard now driven by enabled instruments from DB

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Senofy
2026-03-09 03:31:47 -05:00
co-authored by Claude Sonnet 4.6
parent 532c2e2279
commit b2a1bdd1c3
19 changed files with 1050 additions and 218 deletions
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from 'next/server';
import { stopScheduler, getSchedulerStatus } from '@/lib/auto-trade';
/** GET /api/auto-trade — return current scheduler status */
export async function GET() {
return NextResponse.json(getSchedulerStatus());
}
/** DELETE /api/auto-trade — stop the scheduler */
export async function DELETE() {
stopScheduler();
return NextResponse.json({ ok: true });
}
+110
View File
@@ -0,0 +1,110 @@
import { NextResponse } from 'next/server';
import { getClients, resetClients } from '@/lib/clients';
import { getFirms } from '@/lib/db';
export async function GET() {
try {
const clients = getClients();
const firms = getFirms();
const debug = firms.map((firm) => {
const client = clients.get(firm.id);
if (!client) return { firmId: firm.id, firmName: firm.name, status: 'no_client' };
return {
firmId: firm.id,
firmName: firm.name,
status: 'connected',
accountCount: client.accountList.length,
fetchDaysComplete: (client as any).fetchDaysComplete ?? 'n/a (old instance)',
lastFetchErrors: (client as any).lastFetchErrors ?? {},
lastFetchRaw: (client as any).lastFetchRaw ?? {},
accounts: client.accountList.map((acc) => ({
id: acc.id,
name: acc.name,
cash: client.accountCashBalances[acc.id] ?? null,
daysTraded: client.daysTraded[acc.id] ?? '(not set)',
dailyPnLEntries: (client.dailyPnL[acc.id] ?? []).length,
dailyPnL: client.dailyPnL[acc.id] ?? [],
})),
recentEntityEvents: client.recentEntityEvents.slice(-3).map((e) => ({
ts: new Date(e.ts).toISOString(),
entityType: e.entityType,
eventType: e.eventType,
})),
};
});
return NextResponse.json({ ok: true, ts: new Date().toISOString(), firms: debug });
} catch (err) {
console.error('[GET /api/debug]', err);
return NextResponse.json({ error: String(err) }, { status: 500 });
}
}
/** POST /api/debug — manually trigger fetchDaysTraded on all clients and return results */
export async function POST() {
try {
const clients = getClients();
const firms = getFirms();
const results = await Promise.all(
firms.map(async (firm) => {
const client = clients.get(firm.id);
if (!client || client.accountList.length === 0) {
return { firmId: firm.id, firmName: firm.name, status: 'skipped' };
}
try {
await (client as any).fetchDaysTraded();
} catch (err) {
return { firmId: firm.id, firmName: firm.name, status: 'error', error: String(err) };
}
return {
firmId: firm.id,
firmName: firm.name,
status: 'done',
fetchDaysComplete: (client as any).fetchDaysComplete ?? 'n/a',
errors: (client as any).lastFetchErrors ?? {},
rawSamples: (client as any).lastFetchRaw ?? {},
daysTraded: client.daysTraded,
dailyPnLCounts: Object.fromEntries(
Object.entries(client.dailyPnL).map(([k, v]) => [k, (v as any[]).length])
),
};
})
);
return NextResponse.json({ ok: true, ts: new Date().toISOString(), results });
} catch (err) {
console.error('[POST /api/debug]', 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.
*/
export async function DELETE() {
try {
const g = global as any;
const oldCount = (g.__tradovateClients as Map<number, any> | undefined)?.size ?? 0;
// Disconnect all existing WebSocket connections before clearing
resetClients();
// Re-initialize immediately with fresh instances
getClients();
return NextResponse.json({
ok: true,
message: `Disconnected ${oldCount} old client(s) — fresh instances initializing`,
ts: new Date().toISOString(),
});
} catch (err) {
console.error('[DELETE /api/debug]', err);
return NextResponse.json({ error: String(err) }, { status: 500 });
}
}
@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from 'next/server';
import { getClients } from '@/lib/clients';
import axios from 'axios';
export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
const firmId = parseInt(id, 10);
const clients = getClients();
const client = clients.get(firmId) as any;
if (!client) return NextResponse.json({ error: 'Client not found' }, { status: 404 });
const symbol = req.nextUrl.searchParams.get('symbol') ?? 'NQ';
const accessToken = client.accessInfo?.accessToken;
if (!accessToken) return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
const res = await axios.get(
`https://demo.tradovateapi.com/v1/contract/suggest?t=${encodeURIComponent(symbol)}&l=20`,
{ headers: { Authorization: `Bearer ${accessToken}` } }
);
return NextResponse.json({
symbol,
contracts: res.data,
recentEntityEvents: client.recentEntityEvents ?? [],
});
} catch (err: any) {
return NextResponse.json({ error: err?.message }, { status: 500 });
}
}
@@ -1,41 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { upsertFirmInstrumentConfig } from '@/lib/db';
export async function PUT(
req: NextRequest,
{ params }: { params: Promise<{ id: string; instrumentId: string }> }
) {
const { id: idStr, instrumentId: instrIdStr } = await params;
const firmId = parseInt(idStr, 10);
const instrumentId = parseInt(instrIdStr, 10);
if (isNaN(firmId) || isNaN(instrumentId)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const body = await req.json() as {
allinFee?: number;
roundtripFee?: number;
banned?: boolean;
};
if (
typeof body.allinFee !== 'number' ||
typeof body.roundtripFee !== 'number' ||
typeof body.banned !== 'boolean'
) {
return NextResponse.json({ error: 'Invalid body' }, { status: 400 });
}
try {
upsertFirmInstrumentConfig(firmId, instrumentId, {
allinFee: body.allinFee,
roundtripFee: body.roundtripFee,
banned: body.banned,
});
return NextResponse.json({ success: true });
} catch (err) {
console.error('[PUT /api/firms/:id/instrument-configs/:instrumentId]', err);
return NextResponse.json({ error: 'Failed to save config' }, { status: 500 });
}
}
@@ -1,21 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { getFirmFees } from '@/lib/db';
export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id: idStr } = await params;
const firmId = parseInt(idStr, 10);
if (isNaN(firmId)) {
return NextResponse.json({ error: 'Invalid firm id' }, { status: 400 });
}
try {
return NextResponse.json(getFirmFees(firmId));
} catch (err) {
console.error('[GET /api/firms/:id/instrument-configs]', err);
return NextResponse.json({ error: 'Failed to fetch fees' }, { status: 500 });
}
}
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from 'next/server';
import { getClients } from '@/lib/clients';
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
const firmId = parseInt(id, 10);
if (isNaN(firmId)) return NextResponse.json({ error: 'Invalid firm ID' }, { status: 400 });
const body = await req.json() as {
accountId: number;
symbol: string; // product name, e.g. "NQ"
qty: number;
action: 'Buy' | 'Sell';
orderType?: 'Market' | 'Limit';
price?: number;
};
const { accountId, symbol, qty, action, orderType = 'Market', price } = body;
if (!accountId || !symbol || !qty || !action) {
return NextResponse.json({ error: 'Missing required fields: accountId, symbol, qty, action' }, { status: 400 });
}
const clients = getClients();
const client = clients.get(firmId);
if (!client) return NextResponse.json({ error: 'Client not found for firm' }, { status: 404 });
// 1. Find the front-month contract
const contract = await client.findFrontMonthContract(symbol);
if (!contract) {
return NextResponse.json({ error: `Could not find active front-month contract for ${symbol}` }, { status: 404 });
}
console.log(`[order] front-month: ${contract.name} (id=${contract.id})`);
// 2. Place the order — resolves with the fill event (includes commission/fees)
const fill = await client.sendOrder(accountId, contract.name, qty, action, orderType, price);
console.log(`[order] fill received: price=${fill.price} qty=${fill.qty} commission=$${fill.commission} perContract=$${fill.perContractFee}`);
return NextResponse.json({ contract: { id: contract.id, name: contract.name }, fill });
} catch (err: any) {
console.error('[POST /api/firms/[id]/orders]', err);
return NextResponse.json({ error: err?.message ?? 'Order failed' }, { status: 500 });
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { NextResponse } from 'next/server';
import { getInstruments } from '@/lib/db';
export function GET() {
export async function GET() {
return NextResponse.json(getInstruments());
}
+31
View File
@@ -0,0 +1,31 @@
import { NextRequest, NextResponse } from 'next/server';
import { getSetting, setSetting } from '@/lib/db';
const VALID_KEYS = ['max_concurrent_accounts'] as const;
type SettingKey = typeof VALID_KEYS[number];
export async function GET() {
const result: Record<string, string | null> = {};
for (const key of VALID_KEYS) {
result[key] = getSetting(key);
}
return NextResponse.json(result);
}
export async function PATCH(req: NextRequest) {
try {
const body = await req.json() as Partial<Record<SettingKey, string | number>>;
for (const key of VALID_KEYS) {
if (key in body) {
const raw = body[key];
if (raw === undefined || raw === null) continue;
setSetting(key, String(raw));
}
}
return NextResponse.json({ ok: true });
} catch (err: any) {
return NextResponse.json({ error: err?.message ?? 'Failed to save settings' }, { status: 500 });
}
}
+29 -2
View File
@@ -1,6 +1,14 @@
import { NextResponse } from 'next/server';
import { getFirms } from '@/lib/db';
import { getClients } from '@/lib/clients';
import { computeDailyTarget } from '@/lib/trading-logic';
import type { AccountConfigRow } from '@/lib/db';
function getAccountConfig(name: string, accounts: AccountConfigRow[]): AccountConfigRow | undefined {
return [...accounts]
.sort((a, b) => b.prefix.length - a.prefix.length)
.find((a) => name.startsWith(a.prefix));
}
export async function GET() {
try {
@@ -14,18 +22,37 @@ export async function GET() {
}
const accounts = client.accountList.map((acc) => {
const cash = client.accountCashBalances[acc.id] ?? { amount: 0, realizedPnL: 0 };
const dailyPnL: { date: string; pnl: number }[] = client.dailyPnL[acc.id] ?? [];
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
const cfg = getAccountConfig(acc.name, f.accounts);
let targetHit = false;
if (cfg) {
const target = computeDailyTarget(cfg.profit_target, cfg.consistency, totalProfit, dailyPnL);
// 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) ||
(cash.realizedPnL >= target.amount);
}
return {
id: acc.id,
name: acc.name,
active: acc.active,
amount: cash.amount,
realizedPnL: cash.realizedPnL,
daysTraded: client.daysTraded[acc.id] ?? 0,
daysTraded,
hasPosition: !!client.positions[acc.id],
autoLiqThreshold: client.autoLiqThresholds[acc.id] ?? 0,
totalProfit,
targetHit,
};
});
return { firm: f.name, connected: true, accounts };
return { firm: f.name, connected: true, accounts, perContractFees: client.perContractFees };
});
return NextResponse.json(state);
+29
View File
@@ -0,0 +1,29 @@
import { NextRequest, NextResponse } from 'next/server';
import { runTrade, startScheduler } from '@/lib/auto-trade';
import { POINT_VALUES } from '@/lib/trading-logic';
export async function POST(req: NextRequest) {
try {
const body = await req.json() as { action: 'Buy' | 'Sell'; symbol: string };
const { action, symbol } = body;
if (!action || !symbol) {
return NextResponse.json({ error: 'Missing required fields: action, symbol' }, { status: 400 });
}
if (!POINT_VALUES[symbol]) {
return NextResponse.json({ error: `Unknown symbol: ${symbol}` }, { status: 400 });
}
// Execute trade immediately for all eligible accounts
const results = await runTrade(action, symbol);
// (Re)start the 60-second scheduler with this action + symbol
startScheduler(action, symbol);
return NextResponse.json(results);
} catch (err: any) {
console.error('[POST /api/trade]', err);
return NextResponse.json({ error: err?.message ?? 'Trade failed' }, { status: 500 });
}
}