Trader Workstation - Automatic Start (Paper Trading)
Oct 19, 2018

TWS automatically logs out after about 11:45 PM. They recently added an automatic restart feature to the beta release but I have yet to get it working.

Since I am just paper trading to test algorithms I found an AutoHotKey script that will start/reopen TWS and login when the process disappears. I decided to write my own using Powershell so it works on all Windows systems without needing to install something.

$sig = @"
	[DllImport("user32.dll", CharSet = CharSet.Unicode)]
	public static extern IntPtr FindWindow(String sClassName, String sAppName);

	[DllImport("user32.dll", CharSet = CharSet.Unicode)]
	public static extern int SetForegroundWindow(int hWnd);

	public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);

$fw = Add-Type -Namespace Win32 -Name Funcs -MemberDefinition $sig -PassThru

function Get-TWS {
	return Get-Process -Name "tws" -ErrorAction SilentlyContinue

function Start-TWS {
	$proc = "C:\Jts\tws.exe"
	$app = Get-TWS

	if(($app) -eq $null) {
		$app = Start-Process -PassThru $proc "username= password="

	return $app

if ((Get-TWS) -eq $null) {
	$app = Start-TWS
	Start-Sleep -s 60
	$next = Get-TWS

	if ($next.ID -ne $app.ID) {
		Stop-Process -Id $next.ID

	Start-Sleep -s 30

	$hwnd = $fw::FindWindow("SunAwtDialog", "Warning")
	if ($hwnd -ne 0) {
		$WM_KEYDOWN = 0x0100
		$VK_RETURN = 0x0D
		$fw::SendMessage($hwnd, $WM_KEYDOWN, $VK_RETURN, 0)

Use task scheduler to start this script when you want it to open. I then start my custom algorithm process about 10 minutes later.

Program/script: powershell.exe
Add arguments: -ExecutionPolicy Bypass <.ps1 script path>

Make sure the trading mode is set to paper inside C:\Jts\jts.ini.


FYI: IB provides standalone versions of TWS that do not automatically update. I recommend using that version if you want a more reliable way of autostarting TWS.