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:
co-authored by
Claude Sonnet 4.6
parent
532c2e2279
commit
b2a1bdd1c3
@@ -0,0 +1,271 @@
|
||||
/**
|
||||
* Auto-trade scheduler
|
||||
*
|
||||
* When a trade is triggered (POST /api/trade), the scheduler stores the
|
||||
* action + symbol and fires the same trade logic every 60 seconds to pick
|
||||
* up accounts that were busy (in a position) at the time of the original
|
||||
* signal but have since exited and are now eligible.
|
||||
*/
|
||||
|
||||
import { getFirms } from './db';
|
||||
import { getClients } from './clients';
|
||||
import { computeDailyTarget, POINT_VALUES } from './trading-logic';
|
||||
import { getSetting } from './db';
|
||||
import type { FirmConfig, AccountConfig } from '@/types';
|
||||
import type { FirmWithAccounts } from './db';
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function isAccountDead(amount: number, autoLiqThreshold: number): boolean {
|
||||
return autoLiqThreshold > 0 && amount <= autoLiqThreshold;
|
||||
}
|
||||
|
||||
function getAccountConfig(name: string, firm: FirmConfig): AccountConfig | undefined {
|
||||
return [...firm.accounts]
|
||||
.sort((a, b) => b.prefix.length - a.prefix.length)
|
||||
.find((a) => name.startsWith(a.prefix));
|
||||
}
|
||||
|
||||
/** Map DB row (snake_case) → FirmConfig (camelCase) to fix field-name mismatch. */
|
||||
function mapFirmConfig(firm: FirmWithAccounts): FirmConfig {
|
||||
return {
|
||||
id: firm.id,
|
||||
firm: firm.name,
|
||||
username: firm.username,
|
||||
password: firm.password,
|
||||
accounts: firm.accounts.map((a) => ({
|
||||
prefix: a.prefix,
|
||||
profitTarget: a.profit_target,
|
||||
consistency: a.consistency,
|
||||
minDayPnL: a.min_day_pnl,
|
||||
minTradingDays: a.min_trading_days,
|
||||
accountSize: a.account_size,
|
||||
maxLoss: a.max_loss,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ── core trade logic ──────────────────────────────────────────────────────────
|
||||
|
||||
export async function runTrade(action: 'Buy' | 'Sell', symbol: string) {
|
||||
const pointValue = POINT_VALUES[symbol];
|
||||
if (!pointValue) throw new Error(`Unknown symbol: ${symbol}`);
|
||||
|
||||
const maxConcurrent = parseInt(getSetting('max_concurrent_accounts') ?? '5', 10);
|
||||
const firms = getFirms();
|
||||
const clients = getClients();
|
||||
|
||||
// ── Phase 1: collect ALL eligible accounts across ALL firms in parallel ──
|
||||
type EligibleItem = {
|
||||
firmName: string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
client: any;
|
||||
acc: { id: number; name: string; active: boolean };
|
||||
contract: { name: string; tickSize: number };
|
||||
firmConfig: FirmConfig;
|
||||
cash: { amount: number; realizedPnL: number };
|
||||
dailyPnL: { date: string; pnl: number }[];
|
||||
daysTraded: number;
|
||||
};
|
||||
|
||||
const allEligible: EligibleItem[] = [];
|
||||
|
||||
await Promise.all(firms.map(async (firm) => {
|
||||
const client = clients.get(firm.id);
|
||||
if (!client || client.accountList.length === 0) return;
|
||||
|
||||
const firmConfig = mapFirmConfig(firm);
|
||||
|
||||
const contract = await client.findFrontMonthContract(symbol);
|
||||
if (!contract) return;
|
||||
|
||||
for (const acc of client.accountList) {
|
||||
const cash = client.accountCashBalances[acc.id] ?? { amount: 0, realizedPnL: 0 };
|
||||
const autoLiqThreshold = client.autoLiqThresholds[acc.id] ?? 0;
|
||||
const dailyPnL: { date: string; pnl: number }[] = client.dailyPnL[acc.id] ?? [];
|
||||
const daysTraded: number = client.daysTraded[acc.id] ?? 0;
|
||||
|
||||
if (isAccountDead(cash.amount, autoLiqThreshold)) continue;
|
||||
if (!acc.active) continue;
|
||||
if (client.positions[acc.id]) continue;
|
||||
|
||||
const cfg = getAccountConfig(acc.name, firmConfig);
|
||||
if (!cfg) continue;
|
||||
|
||||
const totalProfit = dailyPnL.reduce((sum, d) => sum + d.pnl, 0);
|
||||
|
||||
// Only trade accounts that haven't traded yet today
|
||||
if (cash.realizedPnL !== 0) continue;
|
||||
|
||||
// Use the same target formula as the dashboard — skip if $0 (challenge complete)
|
||||
const target = computeDailyTarget(cfg.profitTarget, cfg.consistency, totalProfit, dailyPnL);
|
||||
if (target.amount <= 0) continue;
|
||||
|
||||
allEligible.push({ firmName: firm.name, client, acc, contract, firmConfig, cash, dailyPnL, daysTraded });
|
||||
}
|
||||
}));
|
||||
|
||||
if (allEligible.length === 0) {
|
||||
console.log('[auto-trade] no eligible accounts found');
|
||||
return [];
|
||||
}
|
||||
|
||||
// Take only the first batch — all fired simultaneously, no rolling pool.
|
||||
// Remaining accounts wait for the next tick (which only fires once all positions are flat).
|
||||
const batch = allEligible.slice(0, maxConcurrent);
|
||||
console.log(`[auto-trade] ${allEligible.length} eligible account(s) — firing batch of ${batch.length}`);
|
||||
|
||||
// ── Phase 2: fire the batch simultaneously ──
|
||||
const tradeResults = await Promise.allSettled(batch.map(async (item) => {
|
||||
const { client, acc, contract, firmConfig, cash, dailyPnL, daysTraded } = item;
|
||||
const cfg = getAccountConfig(acc.name, firmConfig)!;
|
||||
const totalProfit = dailyPnL.reduce((sum, d) => sum + d.pnl, 0);
|
||||
const target = computeDailyTarget(cfg.profitTarget, cfg.consistency, totalProfit, dailyPnL);
|
||||
|
||||
const contracts = Math.max(1, Math.ceil(target.amount / 1000));
|
||||
const fill = await client.sendOrder(acc.id, contract.name, contracts, action, 'Market');
|
||||
|
||||
// Wait briefly for the cash balance WebSocket update to reflect entry commission
|
||||
await new Promise(r => setTimeout(r, 1000));
|
||||
const updatedCash = client.accountCashBalances[acc.id] ?? { amount: 0, realizedPnL: 0 };
|
||||
// After entry, realizedPnL = -entryCommission (was 0 before), so abs = entry fee paid.
|
||||
// Fall back to $2.50/contract if the WS hasn't updated yet (guarantees at least 1 extra tick).
|
||||
const entryCommission = Math.abs(updatedCash.realizedPnL) || (2.5 * contracts);
|
||||
const totalCommission = entryCommission * 2; // entry + exit round-trip
|
||||
const grossTarget = target.amount + totalCommission;
|
||||
|
||||
const targetPoints = grossTarget / (pointValue * contracts);
|
||||
const ticks = Math.ceil(targetPoints / contract.tickSize);
|
||||
const exitPrice = action === 'Buy'
|
||||
? fill.price + (ticks * contract.tickSize)
|
||||
: fill.price - (ticks * contract.tickSize);
|
||||
|
||||
const exitAction: 'Buy' | 'Sell' = action === 'Buy' ? 'Sell' : 'Buy';
|
||||
const exitOrder = await client.placeOrderNoWait(acc.id, contract.name, contracts, exitAction, 'Limit', exitPrice);
|
||||
|
||||
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 {
|
||||
account: acc.name,
|
||||
firm: item.firmName,
|
||||
status: 'filled',
|
||||
contracts,
|
||||
target: target.amount,
|
||||
grossTarget,
|
||||
totalCommission,
|
||||
targetPath: target.path,
|
||||
entryPrice: fill.price,
|
||||
exitPrice,
|
||||
commission: entryCommission,
|
||||
};
|
||||
}));
|
||||
|
||||
// Group results by firm for the response
|
||||
const firmResultsMap = new Map<string, unknown[]>();
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const firmName = batch[i].firmName;
|
||||
if (!firmResultsMap.has(firmName)) firmResultsMap.set(firmName, []);
|
||||
const r = tradeResults[i];
|
||||
firmResultsMap.get(firmName)!.push(
|
||||
r.status === 'fulfilled'
|
||||
? r.value
|
||||
: { status: 'error', reason: (r.reason as any)?.message ?? String(r.reason) }
|
||||
);
|
||||
}
|
||||
|
||||
return Array.from(firmResultsMap.entries()).map(([firm, results]) => ({ firm, results }));
|
||||
}
|
||||
|
||||
// ── scheduler ─────────────────────────────────────────────────────────────────
|
||||
|
||||
interface SchedulerState {
|
||||
action: 'Buy' | 'Sell';
|
||||
symbol: string;
|
||||
intervalId: ReturnType<typeof setInterval> | null;
|
||||
lastRun: Date | null;
|
||||
running: boolean;
|
||||
}
|
||||
|
||||
// Global singleton (survives HMR in dev via module cache)
|
||||
const _global = globalThis as typeof globalThis & { __autoTrader?: SchedulerState };
|
||||
|
||||
function getState(): SchedulerState {
|
||||
if (!_global.__autoTrader) {
|
||||
_global.__autoTrader = { action: 'Buy', symbol: 'NQ', intervalId: null, lastRun: null, running: false };
|
||||
}
|
||||
return _global.__autoTrader;
|
||||
}
|
||||
|
||||
export function startScheduler(action: 'Buy' | 'Sell', symbol: string) {
|
||||
const state = getState();
|
||||
|
||||
// Clear any existing interval
|
||||
if (state.intervalId !== null) {
|
||||
clearInterval(state.intervalId);
|
||||
}
|
||||
|
||||
state.action = action;
|
||||
state.symbol = symbol;
|
||||
state.running = true;
|
||||
|
||||
const tick = async () => {
|
||||
if (!state.running) return;
|
||||
state.lastRun = new Date();
|
||||
|
||||
// Skip this tick until every client has completed its initial sync (positions are populated)
|
||||
const clients = getClients();
|
||||
const firms = getFirms();
|
||||
const notReady = firms.filter(f => {
|
||||
const c = clients.get(f.id);
|
||||
return c && !c.syncComplete;
|
||||
});
|
||||
if (notReady.length > 0) {
|
||||
console.log(`[scheduler] waiting for sync: ${notReady.map(f => f.name).join(', ')}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip this tick if any account still has an open position from the previous batch
|
||||
const openPositions = firms.reduce((count, firm) => {
|
||||
const client = clients.get(firm.id);
|
||||
if (!client) return count;
|
||||
return count + client.accountList.filter(acc => !!client.positions[acc.id]).length;
|
||||
}, 0);
|
||||
if (openPositions > 0) {
|
||||
console.log(`[scheduler] ${openPositions} position(s) still open — skipping tick`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const results = await runTrade(state.action, state.symbol);
|
||||
const filled = results.flatMap((r: any) => r.results ?? []).filter((r: any) => r.status === 'filled').length;
|
||||
if (filled > 0) console.log(`[scheduler] tick: ${filled} account(s) filled`);
|
||||
} catch (err) {
|
||||
console.error('[scheduler] tick error:', err);
|
||||
}
|
||||
};
|
||||
|
||||
state.intervalId = setInterval(tick, 60_000);
|
||||
console.log(`[scheduler] started — ${action} ${symbol} every 60s`);
|
||||
}
|
||||
|
||||
export function stopScheduler() {
|
||||
const state = getState();
|
||||
if (state.intervalId !== null) {
|
||||
clearInterval(state.intervalId);
|
||||
state.intervalId = null;
|
||||
}
|
||||
state.running = false;
|
||||
console.log('[scheduler] stopped');
|
||||
}
|
||||
|
||||
export function getSchedulerStatus() {
|
||||
const state = getState();
|
||||
return {
|
||||
running: state.running,
|
||||
action: state.action,
|
||||
symbol: state.symbol,
|
||||
lastRun: state.lastRun,
|
||||
};
|
||||
}
|
||||
+16
-18
@@ -1,7 +1,5 @@
|
||||
import { TradovateClient } from './tradovate-class';
|
||||
import { getFirms, upsertFirmFee } from './db';
|
||||
|
||||
const SYMBOLS = ['NQ', 'MNQ', 'ES', 'MES', 'YM', 'MYM', 'RTY', 'M2K', 'GC', 'MGC', 'SI', 'CL', 'MCL', 'NG', 'ZB', 'ZN', 'ZF', '6E', '6J', '6B'];
|
||||
import { getFirms } from './db';
|
||||
|
||||
// Use global to persist the client pool across HMR reloads in dev mode
|
||||
const g = global as typeof globalThis & {
|
||||
@@ -18,31 +16,31 @@ function ensureMap(): Map<number, TradovateClient> {
|
||||
|
||||
export function initClient(id: number, username: string, password: string, firmName: string): TradovateClient {
|
||||
const map = ensureMap();
|
||||
let feesInitialized = false;
|
||||
const client = new TradovateClient(username, password, async () => {
|
||||
const client = new TradovateClient(username, password, () => {
|
||||
console.log(`[${firmName}] sync complete — ${client.accountList.length} account(s)`);
|
||||
if (!feesInitialized) {
|
||||
feesInitialized = true;
|
||||
try {
|
||||
const fees = await client.fetchInstrumentFees(SYMBOLS);
|
||||
for (const [symbol, fee] of Object.entries(fees)) {
|
||||
upsertFirmFee(id, symbol, fee, parseFloat((fee * 2).toFixed(4)));
|
||||
}
|
||||
const count = Object.keys(fees).length;
|
||||
if (count > 0) console.log(`[${firmName}] Auto-fetched fees for ${count} symbol(s)`);
|
||||
} catch (err) {
|
||||
console.error(`[${firmName}] Failed to auto-fetch fees`, err);
|
||||
}
|
||||
}
|
||||
});
|
||||
map.set(id, client);
|
||||
return client;
|
||||
}
|
||||
|
||||
export function removeClient(id: number): void {
|
||||
const client = ensureMap().get(id);
|
||||
client?.disconnect();
|
||||
ensureMap().delete(id);
|
||||
}
|
||||
|
||||
/** Disconnect all clients and clear the pool so they are recreated on next getClients() call. */
|
||||
export function resetClients(): void {
|
||||
const map = g.__tradovateClients;
|
||||
if (map) {
|
||||
for (const client of map.values()) {
|
||||
try { client.disconnect(); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
g.__tradovateClients = undefined;
|
||||
g.__tradovateClientsInitialized = false;
|
||||
}
|
||||
|
||||
export function getClients(): Map<number, TradovateClient> {
|
||||
const map = ensureMap();
|
||||
if (!g.__tradovateClientsInitialized) {
|
||||
|
||||
@@ -23,14 +23,6 @@ db.exec(`
|
||||
min_trading_days INTEGER NOT NULL DEFAULT 5
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS firm_fees (
|
||||
firm_id INTEGER NOT NULL REFERENCES firms(id) ON DELETE CASCADE,
|
||||
symbol TEXT NOT NULL,
|
||||
allin_fee REAL NOT NULL DEFAULT 0,
|
||||
roundtrip_fee REAL NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (firm_id, symbol)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS instruments (
|
||||
symbol TEXT PRIMARY KEY,
|
||||
enabled INTEGER NOT NULL DEFAULT 1
|
||||
@@ -98,13 +90,6 @@ export interface FirmWithAccounts extends FirmRow {
|
||||
accounts: AccountConfigRow[];
|
||||
}
|
||||
|
||||
export interface FirmFee {
|
||||
firmId: number;
|
||||
symbol: string;
|
||||
allinFee: number;
|
||||
roundtripFee: number;
|
||||
}
|
||||
|
||||
// ── Firms ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function getFirms(): FirmWithAccounts[] {
|
||||
@@ -174,30 +159,26 @@ export function updateAccountConfig(id: number, data: {
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
// ── Firm Fees ────────────────────────────────────────────────────────────────
|
||||
// ── Settings ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function getFirmFees(firmId: number): FirmFee[] {
|
||||
return (db.prepare('SELECT firm_id, symbol, allin_fee, roundtrip_fee FROM firm_fees WHERE firm_id = ? ORDER BY symbol').all(firmId) as {
|
||||
firm_id: number;
|
||||
symbol: string;
|
||||
allin_fee: number;
|
||||
roundtrip_fee: number;
|
||||
}[]).map((r) => ({
|
||||
firmId: r.firm_id,
|
||||
symbol: r.symbol,
|
||||
allinFee: r.allin_fee,
|
||||
roundtripFee: r.roundtrip_fee,
|
||||
}));
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
`);
|
||||
|
||||
// Seed defaults if missing
|
||||
const seedSetting = db.prepare(`INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)`);
|
||||
seedSetting.run('max_concurrent_accounts', '5');
|
||||
|
||||
export function getSetting(key: string): string | null {
|
||||
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as { value: string } | undefined;
|
||||
return row?.value ?? null;
|
||||
}
|
||||
|
||||
export function upsertFirmFee(firmId: number, symbol: string, allinFee: number, roundtripFee: number): void {
|
||||
db.prepare(`
|
||||
INSERT INTO firm_fees (firm_id, symbol, allin_fee, roundtrip_fee)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(firm_id, symbol) DO UPDATE SET
|
||||
allin_fee = excluded.allin_fee,
|
||||
roundtrip_fee = excluded.roundtrip_fee
|
||||
`).run(firmId, symbol, allinFee, roundtripFee);
|
||||
export function setSetting(key: string, value: string): void {
|
||||
db.prepare(`INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(key, value);
|
||||
}
|
||||
|
||||
// ── Instruments ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
/** Dollar-per-point value for common futures products. */
|
||||
export const POINT_VALUES: { [symbol: string]: number } = {
|
||||
NQ: 20, MNQ: 2, ES: 50, MES: 5,
|
||||
YM: 5, MYM: 0.5, RTY: 50, M2K: 10,
|
||||
GC: 100, MGC: 10, SI: 50, CL: 1000,
|
||||
MCL: 100, NG: 10000, ZB: 1000, ZN: 1000,
|
||||
ZF: 1000, '6E': 125000, '6J': 12500000, '6B': 62500,
|
||||
};
|
||||
|
||||
/**
|
||||
* Compute the next trading day's profit target for an account.
|
||||
*
|
||||
|
||||
+181
-43
@@ -3,6 +3,7 @@
|
||||
import axios from 'axios';
|
||||
import type { AccountItem, AuthLoginResponse, Contract } from './tradovate-helpers';
|
||||
import { computeSec, randomUUIDV4 } from './tradovate-helpers';
|
||||
import { POINT_VALUES } from './trading-logic';
|
||||
|
||||
export class TradovateClient {
|
||||
private name: string;
|
||||
@@ -31,11 +32,30 @@ export class TradovateClient {
|
||||
/** Balance floor set by the prop firm — account is blown when amount <= this value (0 = not set) */
|
||||
public autoLiqThresholds: { [accountId: number]: number } = {};
|
||||
|
||||
/** True once fetchDaysTraded() has finished its last full run */
|
||||
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 */
|
||||
public lastFetchRaw: Record<string, string> = {};
|
||||
|
||||
public products: { id: number; name: string }[] = [];
|
||||
|
||||
|
||||
/** Rolling buffer of the last 50 raw entity events — useful for debugging */
|
||||
public recentEntityEvents: { entityType: string; eventType: string; entity: any; ts: number }[] = [];
|
||||
|
||||
/** True once the first requestSync has completed and positions/balances are populated. */
|
||||
public syncComplete = false;
|
||||
|
||||
|
||||
private ws: WebSocket;
|
||||
private callbackOnSyncRequest: () => Promise<void>;
|
||||
|
||||
/** Incrementing ID for outgoing WebSocket messages — ensures concurrent orders don't clobber each other's callbacks. */
|
||||
private nextMsgId = 100;
|
||||
private getMsgId(): number { return this.nextMsgId++; }
|
||||
|
||||
// Events that we sent out, and tradovate gives us a response for the id we sent out
|
||||
private directEventCallbacks: {
|
||||
[id: number]: (response: any) => void;
|
||||
@@ -48,7 +68,6 @@ export class TradovateClient {
|
||||
| 'command'
|
||||
| 'commandReport'
|
||||
| 'fill'
|
||||
| 'fillFee'
|
||||
| 'executionReport'
|
||||
| 'cashBalance';
|
||||
eventType: 'Created' | 'Updated';
|
||||
@@ -151,7 +170,39 @@ export class TradovateClient {
|
||||
}
|
||||
}
|
||||
|
||||
// console.log('No callback found', response.d);
|
||||
// Buffer recent entity events (last 50)
|
||||
if (response.d?.entityType) {
|
||||
this.recentEntityEvents.push({ entityType: response.d.entityType, eventType: response.d.eventType, entity: response.d.entity, ts: Date.now() });
|
||||
if (this.recentEntityEvents.length > 50) this.recentEntityEvents.shift();
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Update positions from WebSocket position events
|
||||
if (response.d?.entityType === 'position' && response.d?.entity) {
|
||||
const pos = response.d.entity;
|
||||
if (pos.netPos !== 0) {
|
||||
this.positions[pos.accountId] = {
|
||||
contractId: pos.contractId,
|
||||
netPos: pos.netPos,
|
||||
netPrice: pos.netPrice,
|
||||
timestamp: new Date(pos.timestamp),
|
||||
};
|
||||
} else {
|
||||
delete this.positions[pos.accountId];
|
||||
}
|
||||
}
|
||||
|
||||
// Update cash balances from WebSocket cashBalance events
|
||||
if (response.d?.entityType === 'cashBalance' && response.d?.entity) {
|
||||
const cb = response.d.entity;
|
||||
if (cb.accountId) {
|
||||
this.accountCashBalances[cb.accountId] = {
|
||||
amount: cb.amount,
|
||||
realizedPnL: cb.realizedPnL,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (event.data[0] === 'h') {
|
||||
@@ -238,6 +289,7 @@ export class TradovateClient {
|
||||
this.fetchDaysTraded();
|
||||
|
||||
if (this.products.length > 0) {
|
||||
this.syncComplete = true;
|
||||
this.callbackOnSyncRequest();
|
||||
return;
|
||||
}
|
||||
@@ -247,6 +299,7 @@ export class TradovateClient {
|
||||
this.products = products.map((p: any) => ({ id: p.id, name: p.name }));
|
||||
console.log(`Loaded ${this.products.length} products`);
|
||||
}
|
||||
this.syncComplete = true;
|
||||
this.callbackOnSyncRequest();
|
||||
};
|
||||
this.ws.send('product/list\n30\n\n');
|
||||
@@ -260,6 +313,7 @@ export class TradovateClient {
|
||||
|
||||
private async fetchDaysTraded(): Promise<void> {
|
||||
if (!this.accessInfo?.accessToken) return;
|
||||
this.fetchDaysComplete = false;
|
||||
|
||||
const now = new Date();
|
||||
const start = new Date();
|
||||
@@ -273,7 +327,10 @@ export class TradovateClient {
|
||||
|
||||
for (const account of this.accountList) {
|
||||
try {
|
||||
const res = await axios.post(
|
||||
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',
|
||||
@@ -287,11 +344,29 @@ export class TradovateClient {
|
||||
representationType: 'json',
|
||||
timezone: 0,
|
||||
},
|
||||
{ headers: { Authorization: `Bearer ${this.accessInfo.accessToken}` } }
|
||||
);
|
||||
{ headers: authHeaders }
|
||||
)).data;
|
||||
|
||||
// Step 2 — if the report is queued, poll until it's ready
|
||||
let pollAttempts = 0;
|
||||
while (reportData?.['p-ticket'] && pollAttempts < 30) {
|
||||
const pTicket: string = reportData['p-ticket'];
|
||||
const pTime: number = Math.max(1, reportData['p-time'] ?? 1);
|
||||
await new Promise((r) => setTimeout(r, pTime * 1000));
|
||||
reportData = (await axios.get(
|
||||
'https://rpt-demo.tradovateapi.com/v1/reports/getreport',
|
||||
{ params: { 'p-ticket': pTicket }, headers: authHeaders }
|
||||
)).data;
|
||||
pollAttempts++;
|
||||
}
|
||||
|
||||
if (!this.lastFetchRaw) this.lastFetchRaw = {};
|
||||
this.lastFetchRaw[account.name] = JSON.stringify(reportData).slice(0, 500);
|
||||
|
||||
// _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 raw: string = (res.data?.data ?? '[]')
|
||||
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;
|
||||
@@ -306,14 +381,7 @@ export class TradovateClient {
|
||||
const uniqueDays = new Set(fills.map(f => f._tradeDate));
|
||||
this.daysTraded[account.id] = uniqueDays.size;
|
||||
|
||||
// Dollar-per-point map for common futures products
|
||||
const POINT_VALUES: { [product: string]: number } = {
|
||||
NQ: 20, MNQ: 2, ES: 50, MES: 5,
|
||||
YM: 5, MYM: 0.5, RTY: 50, M2K: 10,
|
||||
GC: 100, MGC: 10, SI: 50, CL: 1000,
|
||||
MCL: 100, NG: 10000, ZB: 1000, ZN: 1000,
|
||||
ZF: 1000, '6E': 125000, '6J': 12500000, '6B': 62500,
|
||||
};
|
||||
// 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.
|
||||
@@ -364,10 +432,14 @@ export class TradovateClient {
|
||||
.map(([date, pnl]) => ({ date, pnl: Math.round(pnl * 100) / 100 }))
|
||||
.sort((a, b) => a.date.localeCompare(b.date));
|
||||
} catch (err) {
|
||||
console.error(`[fetchDaysTraded] ${account.name}`, err);
|
||||
const msg = err instanceof Error ? `${err.message}` : String(err);
|
||||
console.error(`[fetchDaysTraded] ${account.name}:`, msg);
|
||||
if (!this.lastFetchErrors) this.lastFetchErrors = {};
|
||||
this.lastFetchErrors[account.name] = msg;
|
||||
this.daysTraded[account.id] ??= 0;
|
||||
}
|
||||
}
|
||||
this.fetchDaysComplete = true;
|
||||
}
|
||||
|
||||
private async login(): Promise<AuthLoginResponse> {
|
||||
@@ -431,6 +503,19 @@ export class TradovateClient {
|
||||
return res.data;
|
||||
}
|
||||
|
||||
async findFrontMonthContract(productName: string): Promise<{ id: number; name: string; tickSize: number } | null> {
|
||||
if (!this.accessInfo?.accessToken) return null;
|
||||
const res = await axios.get(
|
||||
`https://demo.tradovateapi.com/v1/contract/suggest?t=${encodeURIComponent(productName)}&l=20`,
|
||||
{ headers: { Authorization: `Bearer ${this.accessInfo.accessToken}` } }
|
||||
);
|
||||
const contracts: Array<{ id: number; name: string; status: string; providerTickSize: number }> = res.data ?? [];
|
||||
// Front-month = first contract whose name starts with the product symbol (results are ordered front→back)
|
||||
const match = contracts.find((c) => c.name.startsWith(productName));
|
||||
if (!match) return null;
|
||||
return { id: match.id, name: match.name, tickSize: match.providerTickSize ?? 0.25 };
|
||||
}
|
||||
|
||||
async fetchInstrumentFees(symbols: string[]): Promise<{ [symbol: string]: number }> {
|
||||
if (!this.accessInfo?.accessToken || this.products.length === 0) return {};
|
||||
|
||||
@@ -494,61 +579,114 @@ export class TradovateClient {
|
||||
|
||||
async sendOrder(
|
||||
accountId: number,
|
||||
contractId: number,
|
||||
contractSymbol: string, // e.g. "NQH6" — WebSocket placeorder requires "symbol"
|
||||
quantity: number,
|
||||
action: 'Buy' | 'Sell',
|
||||
orderType: 'Market' | 'Limit',
|
||||
price?: number
|
||||
): Promise<any> {
|
||||
if (!this.ws) {
|
||||
console.log('Websocket not connected');
|
||||
return;
|
||||
}
|
||||
): Promise<Record<string, any>> {
|
||||
if (!this.ws) throw new Error('WebSocket not connected');
|
||||
|
||||
this.ws.send(
|
||||
`user/registeraudituseraction\n25\n\n${JSON.stringify({
|
||||
accountId: accountId,
|
||||
accountId,
|
||||
actionType: action + orderType,
|
||||
details: `DOM MESZ5: Buy ${orderType}, Buy ${quantity} ${orderType}${
|
||||
price ? ` ${price}` : ''
|
||||
}, TIF Day`,
|
||||
details: `${action} ${quantity} ${contractSymbol} ${orderType}${price ? ` @ ${price}` : ''}, TIF Day`,
|
||||
})}`
|
||||
);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.directEventCallbacks[26] = (response: any) => {
|
||||
// console.log('Order id', response?.orderId);
|
||||
console.log('Order placed, order id: ', response);
|
||||
const msgId = this.getMsgId();
|
||||
this.directEventCallbacks[msgId] = (response: any) => {
|
||||
console.log(`[sendOrder] raw ack:`, JSON.stringify(response));
|
||||
if (typeof response === 'string' || !response) {
|
||||
reject(new Error(typeof response === 'string' ? response : 'Empty response from order/placeorder'));
|
||||
return;
|
||||
}
|
||||
// Tradovate returns the command object: { id, commandStatus, orderId, ... }
|
||||
const orderId = response.orderId ?? response.id;
|
||||
console.log(`[sendOrder] orderId=${orderId} status=${response.commandStatus}`);
|
||||
|
||||
// TODO: Implement for limit orders and rejected market orders
|
||||
|
||||
// If we don't get a response within 5 seconds, reject the promise
|
||||
setTimeout(() => {
|
||||
reject(new Error('No response from order placement'));
|
||||
}, 5000);
|
||||
// Wait for the fill event — it carries the real execution price
|
||||
const timeout = setTimeout(() => {
|
||||
reject(new Error(`Order ${orderId} acknowledged but no fill within 30s (market may be closed)`));
|
||||
}, 30000);
|
||||
|
||||
this.indirectEventCallbacks.push({
|
||||
entityType: 'fill',
|
||||
eventType: 'Created',
|
||||
validator: (item: any) => item?.orderId === response?.orderId,
|
||||
callback: (response: any) => {
|
||||
resolve(response);
|
||||
validator: (item: any) => item?.orderId === orderId,
|
||||
callback: (fill: any) => {
|
||||
clearTimeout(timeout);
|
||||
console.log(`[sendOrder] fill:`, JSON.stringify(fill));
|
||||
resolve(fill);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
this.ws.send(
|
||||
`order/placeorder\n26\n\n${JSON.stringify({
|
||||
accountId: accountId,
|
||||
action: action,
|
||||
symbol: contractId,
|
||||
`order/placeorder\n${msgId}\n\n${JSON.stringify({
|
||||
accountId,
|
||||
action,
|
||||
symbol: contractSymbol,
|
||||
orderQty: quantity,
|
||||
orderType: orderType,
|
||||
price: price,
|
||||
orderType,
|
||||
price,
|
||||
timeInForce: 'Day',
|
||||
text: 'DOM',
|
||||
})}`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Place an order and resolve as soon as the command is acknowledged (does not wait for fill). */
|
||||
async placeOrderNoWait(
|
||||
accountId: number,
|
||||
contractSymbol: string,
|
||||
quantity: number,
|
||||
action: 'Buy' | 'Sell',
|
||||
orderType: 'Market' | 'Limit',
|
||||
price?: number
|
||||
): Promise<{ orderId?: number }> {
|
||||
if (!this.ws) throw new Error('WebSocket not connected');
|
||||
|
||||
const msgId = this.getMsgId();
|
||||
return new Promise((resolve, reject) => {
|
||||
this.directEventCallbacks[msgId] = (response: any) => {
|
||||
if (typeof response === 'string') {
|
||||
reject(new Error(response));
|
||||
return;
|
||||
}
|
||||
resolve({ orderId: response?.orderId ?? response?.id });
|
||||
};
|
||||
|
||||
this.ws.send(
|
||||
`order/placeorder\n${msgId}\n\n${JSON.stringify({
|
||||
accountId,
|
||||
action,
|
||||
symbol: contractSymbol,
|
||||
orderQty: quantity,
|
||||
orderType,
|
||||
price,
|
||||
timeInForce: 'Day',
|
||||
text: 'DOM',
|
||||
})}`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Close the WebSocket connection and stop all intervals. Call before discarding the instance. */
|
||||
public disconnect(): void {
|
||||
try { this.ws?.close(); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
/** Register a one-time callback for when a fill arrives for a given orderId. */
|
||||
onFill(orderId: number, callback: (fill: any) => void): void {
|
||||
this.indirectEventCallbacks.push({
|
||||
entityType: 'fill',
|
||||
eventType: 'Created',
|
||||
validator: (item: any) => item?.orderId === orderId,
|
||||
callback,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user