Files
autofirmer-expanded/lib/clients.ts
T
Brandon LiandClaude Opus 5 25289cb9b3 Let the master dashboard drive this instance; drop the AutoBuyer switch
Three changes that ride together because they touch the same surface.

A control link to the master. lib/master-link.ts dials out to
<master>/ws/instance and holds it open, so the dashboard can trigger a trade or
queue an AutoBuyer run here. Commands call the same functions the local pages
call — runTrade, startScheduler, queueRun — so nothing reaches the broker by a
path the UI does not also use. Reports prefer the socket and fall back to the
existing POST, which keeps older masters working unchanged.

startMasterLink is idempotent, and that matters more than it looks: getClients()
is lazy and starts the link, so the first command re-enters it from inside a
command the live socket is waiting to ack. Tearing the socket down there loses
the ack and reports a trade that actually executed as a failure — which invites
pressing the button twice.

queueRun is lifted out of the automations route so the socket and HTTP share one
copy of the input clamping that decides how many times a purchase fires.

Page capture loses its switch and gains a scope. It now runs every tick, but
only against the active tab of the last-focused window that matches
host_permissions — so it follows the page in front of you and stops when you
switch away, where before it would fall back to any firm tab left open in the
background.

autobuyer_enabled is gone entirely. The AutoBuyer is ready whenever the runner
is; a run happens because someone asked for one. That does mean a queued run
executes as soon as clicker/runner.py claims it, with no second gate — stopping
the runner is now the way to make a machine idle.

Extension to 0.10.0; it needs a manual reload at chrome://extensions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-30 22:31:31 -05:00

120 lines
4.5 KiB
TypeScript

import { TradovateClient } from './tradovate-class';
import { getFirms, getInstruments } from './db';
import { resolveContracts } from './contract-resolver';
import { startReporter, sendReport } from './reporter';
import { startMasterLink } from './master-link';
import { resumeSchedulerIfPersisted } from './auto-trade';
// Use global to persist the client pool across HMR reloads in dev mode
const g = global as typeof globalThis & {
__tradovateClients?: Map<number, TradovateClient>;
__tradovateClientsInitialized?: boolean;
__contractResolverTimer?: ReturnType<typeof setInterval>;
};
function ensureMap(): Map<number, TradovateClient> {
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, async () => {
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<number, TradovateClient> {
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)`);
// Auto-resolve contracts after clients have time to authenticate
setTimeout(() => triggerContractResolve(), 15_000);
// Schedule daily resolve at midnight
scheduleDailyResolve();
// Start master dashboard reporter
startReporter();
// ...and the socket it prefers to report over, which is also how
// the master triggers trades and AutoBuyer runs here.
startMasterLink(() => { void sendReport(); });
// Pick the auto-trade schedule back up if it was running before restart
resumeSchedulerIfPersisted();
} catch (err) {
console.error('[clients] Failed to initialize clients', err);
}
}
return map;
}
// ── Contract auto-resolve ────────────────────────────────────────────────────
function triggerContractResolve(): void {
const map = ensureMap();
// Find first client with a valid access token
let accessToken: string | null = null;
for (const [, c] of map) {
const token = (c as any).accessInfo?.accessToken;
if (token) { accessToken = token; break; }
}
if (!accessToken) {
console.log('[contract-resolver] No authenticated client yet — skipping resolve');
return;
}
const symbols = getInstruments().filter((i) => i.enabled).map((i) => i.symbol);
console.log(`[contract-resolver] Resolving ${symbols.length} instruments...`);
resolveContracts(symbols, accessToken)
.then((results) => {
const rolled = Object.entries(results).filter(([, v]) => v?.alternative);
console.log(`[contract-resolver] Done — ${rolled.length} contract(s) rolled via price match`);
})
.catch((err) => console.error('[contract-resolver] Resolve failed:', err));
}
function scheduleDailyResolve(): void {
// Clear any existing timer (HMR safety)
if (g.__contractResolverTimer) clearInterval(g.__contractResolverTimer);
// Check every minute if it's midnight (00:00)
g.__contractResolverTimer = setInterval(() => {
const now = new Date();
if (now.getHours() === 0 && now.getMinutes() === 0) {
console.log('[contract-resolver] Midnight resolve triggered');
triggerContractResolve();
}
}, 60_000);
}