DEV Community

mattleeee
mattleeee

Posted on Originally published at hkcode.dpdns.org

Shipping Quant Code to a Locked-Down Windows Server with robocopy and schtasks

Deploying code to a locked-down Windows server is mostly a problem of working with what is already there. On a typical quant box inside a corporate network you get no pip, no git, no CI agent, no outbound access to GitHub, a console that speaks GBK, and an endpoint security suite that treats every new process creation as a suspect. You cannot install a deployment tool, so you build the deployment out of two binaries that ship with Windows: robocopy and schtasks.

This is the recipe we use to push strategy code, launchers, and scheduled task definitions onto such a machine without ever touching the network path to the outside world.

The Shape of the Problem

The target machine runs paper-trade and live-adjacent jobs against a private Python runtime that sits under the user profile — something like C:\Users\quant\py311\python.exe. There is no system Python, no virtualenv tooling worth the name, and installing anything requires a change ticket. The workspace layout is fixed:

workspace/
  scripts/          # strategy and utility modules
  launcher/         # bat files that start jobs
  runtime-data/     # paper-trade state, logs, sqlite files
  update.bat        # the deploy entrypoint
Enter fullscreen mode Exit fullscreen mode

The critical constraint: runtime-data/ must never be overwritten by a code deployment. A paper-trade position file or a state sqlite that gets replaced by a stale copy from the dev machine is worse than a failed deploy, because it fails silently and corrupts the record. Everything below is organized around protecting that directory.

The workflow is deliberately boring. Develop and replay-test on the local machine. Copy changed files into a patch-package/ directory that mirrors the production layout exactly — scripts/, launcher/, the launcher bat. Carry the package to the target (a mapped share, a USB stick, whatever the security policy allows). Run update.bat on the target.

robocopy: Forcing the Overwrite

The naive robocopy invocation fails on these boxes for two reasons. First, clock skew: the target server's clock drifts against the dev machine, so /XO (exclude older) and the default timestamp comparison skip files that actually changed. Second, the runtime state directory gets swept up in a /E copy and clobbered.

The line we actually use:

robocopy "%~dp0patch-package" "%~dp0workspace" /E /IS /IT /XD "%~dp0workspace\runtime-data" /R:2 /W:2 /NP /LOG+:"%~dp0update.log"
Enter fullscreen mode Exit fullscreen mode

Walking through the flags:

  • /E copies subdirectories including empty ones.
  • /IS includes same files — overwrite even if source and destination look identical by size and timestamp.
  • /IT includes tweaked files — overwrite files whose attributes differ. Together with /IS this defeats clock skew entirely: the patch package is authoritative, and anything in it lands on the target regardless of what the timestamps claim.
  • /XD excludes the runtime-data directory by full path. This is the load-bearing flag. Exclusion by name alone (/XD runtime-data) is tempting but risky if a strategy subfolder ever happens to share the name; pin it to the absolute path.
  • /R:2 /W:2 bounds retries so a locked file does not hang the deploy for the default one million retries.
  • /NP suppresses per-file progress noise, which matters when the output is being captured by a scheduler and read by a human later.
  • /LOG+ appends to a log next to the script, so every deploy leaves an audit trail.

Handling robocopy's Exit Codes

robocopy returns bitmask exit codes, and this trips up every wrapper script written the first time. Codes 0 through 7 are success variants — 0 means no files copied, 1 means files copied, 2 means extra files present, 3 is 1+2, and so on. Only 8 and above indicate real failure (8 = some files could not be copied, 16 = fatal error). A batch file that checks if errorlevel 1 will abort on a perfectly healthy deploy.

In update.bat:

@echo off
setlocal
robocopy "%~dp0patch-package" "%~dp0workspace" /E /IS /IT /XD "%~dp0workspace\runtime-data" /R:2 /W:2 /NP /LOG+:"%~dp0update.log"
set RC=%ERRORLEVEL%
if %RC% GEQ 8 (
    echo UPDATE FAILED rc=%RC%
    exit /b %RC%
)
echo UPDATE OK rc=%RC%
exit /b 0
Enter fullscreen mode Exit fullscreen mode

If you drive the deploy from Python instead — useful when the patch package is assembled programmatically — mirror the same logic:

import subprocess
import sys
from pathlib import Path

def deploy(package_dir: Path, workspace: Path) -> int:
    runtime_data = workspace / "runtime-data"
    cmd = [
        "robocopy", str(package_dir), str(workspace),
        "/E", "/IS", "/IT",
        "/XD", str(runtime_data),
        "/R:2", "/W:2", "/NP",
        "/LOG+:" + str(package_dir.parent / "update.log"),
    ]
    proc = subprocess.run(cmd, capture_output=True)
    rc = proc.returncode
    if rc >= 8:
        print(f"UPDATE FAILED rc={rc}", file=sys.stderr)
        return rc
    print(f"UPDATE OK rc={rc}")
    return 0

if __name__ == "__main__":
    sys.exit(deploy(Path(r"C:\deploy\patch-package"), Path(r"C:\deploy\workspace")))
Enter fullscreen mode Exit fullscreen mode

The >= 8 check is the whole point. Everything below it is a successful copy with varying degrees of "there were extra files" or "nothing changed."

Self-Discovering Launchers

Absolute paths are a maintenance tax. The workspace moves once — a new user profile, a re-imaged box, a different drive letter — and every scheduled task and bat file breaks. The fix is to make the launcher find its own workspace at runtime.

A launcher bat that scans upward from its own location:

@echo off
setlocal enabledelayedexpansion
set "HERE=%~dp0"
set "WS="
for %%D in ("%HERE%.." "%HERE%..\.." "%HERE%..\..\..") do (
    if exist "%%~fD\scripts" if exist "%%~fD\launcher" (
        set "WS=%%~fD"
        goto :found
    )
)
echo WORKSPACE NOT FOUND
exit /b 1
:found
set "PY=%USERPROFILE%\py311\python.exe"
"%PY%" "%WS%\scripts\run_strategy.py" --config "%WS%\launcher\strategy.ini"
exit /b %ERRORLEVEL%
Enter fullscreen mode Exit fullscreen mode

The equivalent scan in Python, for cases where the launcher is itself Python:

from pathlib import Path

def find_workspace(start: Path) -> Path:
    for candidate in [start, *start.parents]:
        if (candidate / "scripts").is_dir() and (candidate / "launcher").is_dir():
            return candidate
    raise RuntimeError(f"workspace not found above {start}")

if __name__ == "__main__":
    ws = find_workspace(Path(__file__).resolve().parent)
    print(ws)
Enter fullscreen mode Exit fullscreen mode

Now the scheduled task only needs to point at the launcher bat, and the launcher resolves everything else. Moving the workspace is a file move, not a task-definition edit.

Registering Tasks with schtasks

New jobs get registered with schtasks /create. Minimal example, daily at 08:55, running under the current user, pointing at the self-discovering launcher:

schtasks /create /tn "Quant\PaperTrade-Open" /tr "\"C:\deploy\workspace\launcher\run_papertrade.bat\"" /sc daily /st 08:55 /ru "%USERNAME%" /f
Enter fullscreen mode Exit fullscreen mode

Notes that save time:

  • /f overwrites an existing task of the same name, which makes the registration step idempotent and safe to re-run as part of an update.
  • The /tr value needs inner quotes escaped when the path contains spaces. If you hit quoting trouble, wrap the whole thing in a small cmd /c call or register a VBS wrapper (below) instead of the bat directly.
  • /ru without /rp runs only when the user is logged on. On a locked-down box that is often exactly what you want — the job inherits the user's environment, including the private Python runtime, without storing a password anywhere.
  • Use a task folder prefix (Quant\) so the security suite's process-creation alerts and your own schtasks /query /fo LIST output stay readable.

Hard Timeouts and the Silent VBS Wrapper

Two problems remain. First, a hung strategy process can hold a scheduled task open indefinitely. Second, some endpoint security products flag cmd.exe spawning python.exe on a schedule as suspicious, and a visible console window on a server session is noise nobody wants.

Both are solved by launching through a VBS wrapper that runs the bat hidden and enforces a timeout:

' run_hidden.vbs — invoked by schtasks, runs the bat with no window
Dim shell, rc
Set shell = CreateObject("WScript.Shell")
rc = shell.Run("cmd /c ""C:\deploy\workspace\launcher\run_papertrade.bat""", 0, True)
WScript.Quit rc
Enter fullscreen mode Exit fullscreen mode

The 0 hides the window; True waits for completion so the exit code propagates to the scheduler. The hard timeout belongs inside the Python entrypoint, because the VBS layer cannot kill a child it is blocking on:

import signal
import sys

class Timeout(Exception):
    pass

def _alarm(signum, frame):
    raise Timeout("strategy exceeded time budget")

def main() -> int:
    signal.signal(signal.SIGALRM, _alarm)
    signal.alarm(45 * 60)  # hard 45-minute budget per run
    try:
        run_strategy()
    except Timeout:
        print("TIMEOUT: strategy aborted", file=sys.stderr)
        return 2
    finally:
        signal.alarm(0)
    return 0
Enter fullscreen mode Exit fullscreen mode

SIGALRM does not fire while the main thread is blocked in a C extension, so pair it with a watchdog thread that calls os._exit(3) after a slightly longer deadline if the alarm path itself hangs. Belt and braces, but on a box where you cannot attach a debugger, it is the difference between a stuck task and a clean failure.

The Gotcha Registry

Keep this list somewhere the next person will find it:

  1. Bat files must be ASCII with CRLF line endings. The console code page is GBK (936). UTF-8 bat files with non-ASCII comments render as mojibake at best and break parsing at worst. Write bat files in plain ASCII, save with CRLF, and keep comments in English. Python source can be UTF-8, but print statements should stick to ASCII or set PYTHONIOENCODING=gbk in the launcher.
  2. python.exe is a private runtime under the user profile. Never reference python from PATH in a scheduled task; the resolved binary may be a completely different interpreter or nothing at all. Always use %USERPROFILE%\py311\python.exe or the full path.
  3. robocopy exit codes 0–7 are success. Only abort on 8+. This is the single most common cause of "the deploy failed" tickets that turn out to be healthy copies.
  4. /IS /IT before you trust timestamps. Clock skew between dev and target is normal; treat the patch package as authoritative and force the overwrite.
  5. Exclude runtime-data by absolute path. Never let a code update touch paper-trade state.
  6. Every scheduled task gets a hard timeout. A hung process holding a task open blocks the next run and confuses the scheduler's history.
  7. Launch through the VBS wrapper. Hidden window, propagated exit code, fewer security-suite alerts on the cmd → python chain.
  8. Log the deploy. /LOG+ on robocopy, and have update.bat echo its final return code. When the security team asks what changed and when, the log answers.

Putting It Together

The full update cycle on the target is: copy patch-package/ next to the workspace, run update.bat, confirm UPDATE OK rc=N in the console and the appended log, then re-register any changed tasks with schtasks /create /f. The self-discovering launchers mean the task definitions never encode a path, and the VBS wrapper plus in-process timeout mean a runaway strategy fails cleanly instead of wedging the scheduler.

None of this is elegant. It is, however, entirely composed of binaries that are already on the box, which is the only kind of tooling that survives an airtight Windows server.

More notes like this ship every week on this site.


Daily Picks

The following pairs are selected from the multi-timeframe trend scanner (Gate.io futures) and are for technical-analysis study only — not investment advice.
Data updated: 2026-11-25 08:46:15

Long

Pair Signal Price Take Profit Stop Loss R/R
ON 短平快做多 $0.108 $0.1113 $0.1053 1:1.2

Short

Pair Signal Price Take Profit Stop Loss R/R
MAGMA 扫荡做空 $0.2587 $0.2479 $0.2678 1:1.2

2 picks selected. Scanner runs every 15 minutes.

Top comments (0)