Files
autofirmer-expanded/app/api/firms/[id]/orders/route.ts
T
SenofyandClaude Sonnet 4.6 b2a1bdd1c3 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>
2026-03-09 03:31:47 -05:00

48 lines
2.1 KiB
TypeScript

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 });
}
}