Auto-start both processes at logon and self-update from master

Instances were started by hand and updated by hand, so they drifted behind
master silently. Now: PM2 supervises the dashboard and the clicker, a logon
task brings them up, and a 5-minute task pulls, rebuilds and restarts when
master moves.

Restarting on every push is only safe because the scheduler now survives it.
It was pure in-memory state (_global.__autoTrader), so any restart silently
stopped automated trading with the dashboard simply showing it as off. It now
mirrors running/action/symbol/stopAfterAll to the settings table, and
resumeSchedulerIfPersisted() picks it back up from the getClients() bootstrap.
No sync-wait was needed there: tick() already skips while a client reports
!syncComplete and while any account holds a position.

A failed build is never deployed — the build runs before anything restarts, so
a broken push leaves the previous build serving.

start-all and update-check both warm the app with a request afterwards. That is
load-bearing: getClients() is lazily bootstrapped, so until something makes an
HTTP request the Tradovate clients, the reporter and the resumed schedule never
start. That was already true of manual restarts.

Logic lives in Node so a macOS or Linux port only needs an equivalent of
install-autostart.ps1. Python deps are hash-guarded, so the common path is one
hash and one import with no network, and failure is non-fatal since only the
clicker needs them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Brandon Li
2026-08-30 17:36:25 -05:00
co-authored by Claude Opus 5
parent 7e7bd985c2
commit 4288d8c298
11 changed files with 593 additions and 44 deletions
+122
View File
@@ -0,0 +1,122 @@
<#
.SYNOPSIS
Register AutoFirmer to start at logon and keep itself updated.
.DESCRIPTION
The only Windows-specific piece of the setup. Everything it schedules is
plain Node, so porting to macOS or Linux means replacing this file alone.
Two scheduled tasks are created, both running as the current user with
LogonType Interactive. That is not incidental: the clicker drives real mouse
and keyboard input and must own a desktop, which a Windows service (session
0) does not have.
Idempotent - re-running replaces the tasks rather than duplicating them.
No elevation required.
.PARAMETER IntervalMinutes
How often to check master for updates. Default 5.
.PARAMETER SkipClicker
Register only the dashboard, leaving the clicker to be run by hand.
#>
[CmdletBinding()]
param(
[int]$IntervalMinutes = 5,
[switch]$SkipClicker
)
$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $PSScriptRoot
$StartTask = 'AutoFirmer Start'
$UpdateTask = 'AutoFirmer Update'
function Info($m) { Write-Host " $m" }
function Warn($m) { Write-Host " ! $m" -ForegroundColor Yellow }
Info "project root: $Root"
# ── PM2 ─────────────────────────────────────────────────────────────────────
if (-not (Get-Command pm2 -ErrorAction SilentlyContinue)) {
Info 'installing PM2 globally...'
npm install -g pm2
if ($LASTEXITCODE -ne 0) { throw 'npm install -g pm2 failed' }
# A fresh global install is not on this session's PATH yet.
$npmPrefix = (npm prefix -g).Trim()
$env:PATH = "$npmPrefix;$env:PATH"
if (-not (Get-Command pm2 -ErrorAction SilentlyContinue)) {
throw "PM2 installed but not found on PATH. Open a new terminal and re-run."
}
}
Info "pm2: $((Get-Command pm2).Source)"
Push-Location $Root
try {
# delete + recreate rather than reusing, so a changed path or interpreter
# actually takes effect
pm2 delete autofirmer 2>$null | Out-Null
pm2 start npm --name autofirmer -- start
if ($LASTEXITCODE -ne 0) { throw 'pm2 start autofirmer failed' }
Info 'pm2: autofirmer registered'
if (-not $SkipClicker) {
# pm2 --interpreter wants one executable, so resolve the real path
# rather than passing something like "py -3".
$pyCmdFile = Join-Path $Root 'scripts\.python-cmd'
$pyCmd = if (Test-Path $pyCmdFile) { (Get-Content $pyCmdFile -Raw).Trim() } else { 'python' }
$pyExe = $null
try { $pyExe = (& ([scriptblock]::Create("$pyCmd -c `"import sys;print(sys.executable)`""))).Trim() } catch { }
if ($pyExe -and (Test-Path $pyExe)) {
pm2 delete clicker 2>$null | Out-Null
pm2 start (Join-Path $Root 'clicker\runner.py') --name clicker --interpreter $pyExe
if ($LASTEXITCODE -eq 0) { Info "pm2: clicker registered ($pyExe)" }
else { Warn 'pm2 start clicker failed - the dashboard is unaffected' }
} else {
Warn 'python not found - skipping the clicker. Re-run setup once Python is installed.'
}
}
pm2 save | Out-Null
Info 'pm2: process list saved'
} finally {
Pop-Location
}
# ── Scheduled tasks ─────────────────────────────────────────────────────────
# LogonType Interactive is what grants the desktop the clicker needs.
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" `
-LogonType Interactive -RunLevel Limited
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries -StartWhenAvailable `
-MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Hours 1)
function Register-Task($Name, $Action, $Triggers, $Description) {
Unregister-ScheduledTask -TaskName $Name -Confirm:$false -ErrorAction SilentlyContinue
Register-ScheduledTask -TaskName $Name -Action $Action -Trigger $Triggers `
-Principal $principal -Settings $settings -Description $Description | Out-Null
Info "task registered: $Name"
}
Register-Task $StartTask `
(New-ScheduledTaskAction -Execute 'cmd.exe' `
-Argument "/c `"$(Join-Path $Root 'scripts\start-all.bat')`"" -WorkingDirectory $Root) `
(New-ScheduledTaskTrigger -AtLogOn) `
'Start AutoFirmer and the clicker at logon.'
# AtLogOn covers a reboot; the repeating Once trigger covers the rest of the day.
$repeat = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) `
-RepetitionInterval (New-TimeSpan -Minutes $IntervalMinutes) `
-RepetitionDuration (New-TimeSpan -Days 3650)
Register-Task $UpdateTask `
(New-ScheduledTaskAction -Execute 'node.exe' `
-Argument 'scripts\update-check.mjs' -WorkingDirectory $Root) `
@((New-ScheduledTaskTrigger -AtLogOn), $repeat) `
"Check master for updates every $IntervalMinutes minutes; rebuild and restart when it moves."
Write-Host ''
Info 'Done. Both processes are registered and will come back at logon.'
Info "Update checks run every $IntervalMinutes minutes; see scripts\update.log"
Info 'Useful: pm2 list | pm2 logs autofirmer | pm2 logs clicker'