import { TradovateClient } from './tradovate-class'; import { getFirms } from './db'; // Use global to persist the client pool across HMR reloads in dev mode const g = global as typeof globalThis & { __tradovateClients?: Map; __tradovateClientsInitialized?: boolean; }; function ensureMap(): Map { if (!g.__tradovateClients) { g.__tradovateClients = new Map(); } return g.__tradovateClients; } export function initClient(id: number, username: string, password: string, firmName: string): TradovateClient { const map = ensureMap(); const client = new TradovateClient(username, password, () => { console.log(`[${firmName}] sync complete — ${client.accountList.length} account(s)`); }); 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 { const map = ensureMap(); if (!g.__tradovateClientsInitialized) { g.__tradovateClientsInitialized = true; try { const firms = getFirms(); for (const firm of firms) { initClient(firm.id, firm.username, firm.password, firm.name); } console.log(`[clients] Initialized ${firms.length} Tradovate client(s)`); } catch (err) { console.error('[clients] Failed to initialize clients', err); } } return map; }