192 lines
7.6 KiB
TypeScript
192 lines
7.6 KiB
TypeScript
import { TradovateClient } from './tradovate-class';
|
|
import { getInstruments } from './db';
|
|
import { getTradableFirms, startCatalogSync } from './firm-catalog';
|
|
import { resolveFirmAssignments } from './account-type-resolver';
|
|
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.
|
|
// Keyed by the master's firm id, which is a uuid string.
|
|
const g = global as typeof globalThis & {
|
|
__tradovateClients?: Map<string, TradovateClient>;
|
|
__tradovateClientsInitialized?: boolean;
|
|
__tradovateClientCreds?: Map<string, string>;
|
|
__contractResolverTimer?: ReturnType<typeof setInterval>;
|
|
};
|
|
|
|
function ensureMap(): Map<string, TradovateClient> {
|
|
if (!g.__tradovateClients) {
|
|
g.__tradovateClients = new Map();
|
|
}
|
|
return g.__tradovateClients;
|
|
}
|
|
|
|
/** Tracks which credentials each live client was built with, so a password
|
|
* change can be noticed and the client rebuilt. */
|
|
function credsMap(): Map<string, string> {
|
|
if (!g.__tradovateClientCreds) g.__tradovateClientCreds = new Map();
|
|
return g.__tradovateClientCreds;
|
|
}
|
|
|
|
export function initClient(id: string, 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)`);
|
|
// Every sync is a chance to bind accounts whose funding history has
|
|
// finally arrived. The first pass can already resolve untraded accounts
|
|
// from their exact cash balance; traded ones wait for the separate
|
|
// reports fetch that produces fund transactions.
|
|
try {
|
|
const counts = resolveFirmAssignments(id, client);
|
|
console.log(
|
|
`[resolver] ${firmName}: ${counts.assigned} assigned, `
|
|
+ `${counts.unassigned} unassigned, ${counts.manual} manual`,
|
|
);
|
|
} catch (err) {
|
|
console.error(`[resolver] ${firmName} failed`, err);
|
|
}
|
|
});
|
|
map.set(id, client);
|
|
credsMap().set(id, `${username} |