Trader Workstation - Automatic Start (Paper Trading)

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
$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);
[DllImport("user32.dll")]
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-TWS
}
Start-Sleep -s 30
$hwnd = $fw::FindWindow("SunAwtDialog", "Warning")
if ($hwnd -ne 0) {
$WM_KEYDOWN = 0x0100
$VK_RETURN = 0x0D
$fw::SetForegroundWindow($hwnd)
$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.

1
2
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.

1
tradingMode=p