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>
118 lines
4.2 KiB
TypeScript
118 lines
4.2 KiB
TypeScript
/**
|
|
* Reporter module — pushes aggregated state to the master dashboard.
|
|
*
|
|
* Every 30 seconds, collects firm-level stats + scheduler state and sends them
|
|
* to the configured master_dashboard_url. Silently skips if not configured.
|
|
*
|
|
* Two transports, in that order of preference: the control WebSocket in
|
|
* `master-link.ts` when it is up, and the original POST /api/report when it is
|
|
* not. The socket already exists for commands, so reusing it saves a request
|
|
* per tick — but a master on an older build has no socket to offer, and the
|
|
* POST keeps those working unchanged.
|
|
*/
|
|
|
|
import { getSetting } from './db';
|
|
import { pushReport } from './master-link';
|
|
import { getFirms } from './db';
|
|
import { getClients } from './clients';
|
|
import { getSchedulerStatus } from './auto-trade';
|
|
import { computeDailyTarget } from './trading-logic';
|
|
import type { AccountConfigRow } from './db';
|
|
|
|
function getAccountConfig(name: string, accounts: AccountConfigRow[]): AccountConfigRow | undefined {
|
|
return [...accounts]
|
|
.sort((a, b) => b.prefix.length - a.prefix.length)
|
|
.find((a) => name.startsWith(a.prefix));
|
|
}
|
|
|
|
function collectFirmStats() {
|
|
const firms = getFirms();
|
|
const clients = getClients();
|
|
|
|
return firms.map((f) => {
|
|
const client = clients.get(f.id);
|
|
if (!client || client.accountList.length === 0) {
|
|
return { firm: f.name, totalAccounts: 0, accountsTraded: 0, inTrade: 0 };
|
|
}
|
|
|
|
let totalAccounts = 0;
|
|
let accountsTraded = 0;
|
|
let inTrade = 0;
|
|
|
|
for (const acc of client.accountList) {
|
|
const cash = client.accountCashBalances[acc.id] ?? { amount: 0, realizedPnL: 0 };
|
|
const autoLiqThreshold = client.autoLiqThresholds[acc.id] ?? 0;
|
|
const isDead = autoLiqThreshold > 0 && cash.amount <= autoLiqThreshold;
|
|
if (isDead) continue;
|
|
|
|
totalAccounts++;
|
|
|
|
if (client.positions[acc.id]) {
|
|
inTrade++;
|
|
accountsTraded++;
|
|
continue;
|
|
}
|
|
|
|
// Check if target was hit today
|
|
const cfg = getAccountConfig(acc.name, f.accounts);
|
|
if (cfg) {
|
|
const dailyPnL = client.dailyPnL[acc.id] ?? [];
|
|
const equityProfit = cash.amount - cfg.account_size;
|
|
const target = computeDailyTarget(cfg.profit_target, cfg.consistency, dailyPnL, cfg.min_day_pnl, cfg.min_trading_days, equityProfit);
|
|
const targetHit = !target ? false :
|
|
((target.amount === 0 && Math.abs(cash.realizedPnL) > 0 && (client.daysTraded[acc.id] ?? 0) <= cfg.min_trading_days) ||
|
|
(cash.realizedPnL >= target.amount));
|
|
|
|
if (targetHit || cash.realizedPnL !== 0) {
|
|
accountsTraded++;
|
|
}
|
|
}
|
|
}
|
|
|
|
return { firm: f.name, totalAccounts, accountsTraded, inTrade };
|
|
});
|
|
}
|
|
|
|
// HMR-safe global to avoid duplicate intervals
|
|
const _g = globalThis as typeof globalThis & { __reporterInterval?: ReturnType<typeof setInterval> };
|
|
|
|
/**
|
|
* Collect and send one report. Exported so the control link can fire an
|
|
* off-cycle one the moment a command has changed something — waiting up to 30s
|
|
* to see whether your own button worked is the wrong feedback loop.
|
|
*/
|
|
export async function sendReport(): Promise<void> {
|
|
const url = getSetting('master_dashboard_url');
|
|
const instanceName = getSetting('instance_name');
|
|
|
|
if (!url || !instanceName) return;
|
|
|
|
try {
|
|
const firms = collectFirmStats();
|
|
const scheduler = getSchedulerStatus();
|
|
|
|
if (pushReport(firms, scheduler)) return;
|
|
|
|
await fetch(`${url}/api/report`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ instance: instanceName, firms, scheduler }),
|
|
});
|
|
} catch {
|
|
// Master might be down — silently continue
|
|
}
|
|
}
|
|
|
|
export function startReporter() {
|
|
if (_g.__reporterInterval) {
|
|
clearInterval(_g.__reporterInterval);
|
|
}
|
|
|
|
_g.__reporterInterval = setInterval(sendReport, 30_000);
|
|
|
|
// Fire first report after a short delay to let clients sync
|
|
setTimeout(sendReport, 10_000);
|
|
|
|
console.log('[reporter] started — reporting every 30s');
|
|
}
|