-
Notifications
You must be signed in to change notification settings - Fork 37
/
IBAutomater.cs
1296 lines (1098 loc) · 51.9 KB
/
IBAutomater.cs
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* IBAutomater v1.0. Copyright 2019 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NodaTime;
namespace QuantConnect.IBAutomater
{
/// <summary>
/// The IB Automater is responsible for automating the configuration/logon process
/// to the IB Gateway application and for handling/dismissing its popup windows.
/// </summary>
public class IBAutomater : IDisposable
{
private readonly TimeSpan _initializationTimeout = TimeSpan.FromMinutes(15);
private readonly string _ibDirectory;
private readonly string _ibVersion;
private readonly string _userName;
private readonly string _password;
private readonly string _tradingMode;
private readonly int _portNumber;
private readonly bool _exportIbGatewayLogs;
private volatile bool _isDisposeCalled;
private readonly object _locker = new object();
private Process _process;
private StartResult _lastStartResult = StartResult.Success;
private readonly AutoResetEvent _ibAutomaterInitializeEvent = new AutoResetEvent(false);
private bool _isRestartInProgress;
private bool _isFirstStart = true;
private volatile bool _isAuthenticating;
private enum Region { America, Europe, Asia }
// Source: https://ibkr.info/article/2816
private readonly Dictionary<string, Region> _ibServerMap = new Dictionary<string, Region>
{
{ "gdc1.ibllc.com", Region.America },
{ "ndc1.ibllc.com", Region.America },
{ "ndc1_hb1.ibllc.com", Region.America },
{ "cdc1.ibllc.com", Region.America },
{ "cdc1_hb1.ibllc.com", Region.America },
{ "zdc1.ibllc.com", Region.Europe },
{ "zdc1_hb1.ibllc.com", Region.Europe },
{ "hdc1.ibllc.com", Region.Asia },
{ "hdc1_hb1.ibllc.com", Region.Asia },
{ "mcgw1.ibllc.com.cn", Region.Asia },
{ "mcgw1_hb1.ibllc.com.cn", Region.Asia }
};
private string _ibServerName;
private Region _ibServerRegion = Region.America;
private static readonly DateTimeZone TimeZoneNewYork = DateTimeZoneProviders.Tzdb["America/New_York"];
private static readonly DateTimeZone TimeZoneZurich = DateTimeZoneProviders.Tzdb["Europe/Zurich"];
private static readonly DateTimeZone TimeZoneHongKong = DateTimeZoneProviders.Tzdb["Asia/Hong_Kong"];
// used to limit logging
private bool _isWithinScheduledServerResetTimesLastValue;
private string _ibGatewayLogFileName;
private int _logLinesRead;
private readonly Timer _timerLogReader;
private readonly object _logLocker = new object();
private static readonly TimeSpan _maxExpectedGatewayRestartTime = TimeSpan.FromMinutes(10);
private int _gatewaySoftRestartCount;
private bool _gatewaySoftRestartTimedOut;
private CancellationTokenSource _gatewaySoftRestartTokenSource;
/// <summary>
/// Event fired when the process writes to the output stream
/// </summary>
public event EventHandler<OutputDataReceivedEventArgs> OutputDataReceived;
/// <summary>
/// Event fired when the process writes to the error stream
/// </summary>
public event EventHandler<ErrorDataReceivedEventArgs> ErrorDataReceived;
/// <summary>
/// Event fired when the process exits
/// </summary>
public event EventHandler<ExitedEventArgs> Exited;
/// <summary>
/// Event fired when the process exits
/// </summary>
public event EventHandler Restarted;
/// <summary>
/// Main program for testing and/or standalone execution
/// </summary>
public static void Main(string[] args)
{
var json = File.ReadAllText("config.json");
var config = JObject.Parse(json);
var ibDirectory = config["ib-tws-dir"].ToString();
var userName = config["ib-user-name"].ToString();
var password = config["ib-password"].ToString();
var tradingMode = config["ib-trading-mode"].ToString();
var portNumber = config["ib-port"].ToObject<int>();
var ibVersion = "974";
if (config["ib-version"] != null)
{
ibVersion = config["ib-version"].ToString();
}
var exportIbGatewayLogs = config["ib-export-ibgateway-logs"].ToObject<bool>();
// Create a new instance of the IBAutomater class
using var automater = new IBAutomater(ibDirectory, ibVersion, userName, password, tradingMode, portNumber, exportIbGatewayLogs);
// Attach the event handlers
automater.OutputDataReceived += (s, e) => Console.WriteLine($"{DateTime.UtcNow:O} {e.Data}");
automater.ErrorDataReceived += (s, e) => Console.WriteLine($"{DateTime.UtcNow:O} {e.Data}");
automater.Exited += (s, e) => Console.WriteLine($"{DateTime.UtcNow:O} IBAutomater exited [ExitCode:{e.ExitCode}]");
// Start the IBAutomater
Console.WriteLine("===> Starting IBAutomater");
var result = automater.Start(false);
if (result.HasError)
{
Console.WriteLine($"Failed to start IBAutomater - Code: {result.ErrorCode}, Message: {result.ErrorMessage}");
automater.Stop();
return;
}
// Restart the IBAutomater
Console.WriteLine("===> Restarting IBAutomater");
result = automater.Restart();
if (result.HasError)
{
Console.WriteLine($"Failed to restart IBAutomater - Code: {result.ErrorCode}, Message: {result.ErrorMessage}");
automater.Stop();
return;
}
// Stop the IBAutomater
Console.WriteLine("===> Stopping IBAutomater");
automater.Stop();
Console.WriteLine("IBAutomater stopped");
}
/// <summary>
/// Creates a new instance of the <see cref="IBAutomater"/> class
/// </summary>
/// <param name="ibDirectory">The root directory of IB Gateway</param>
/// <param name="ibVersion">The IB Gateway version to launch</param>
/// <param name="userName">The user name</param>
/// <param name="password">The password</param>
/// <param name="tradingMode">The trading mode ('paper' or 'live')</param>
/// <param name="portNumber">The API port number</param>
/// <param name="exportIbGatewayLogs">Export IB Gateway logs if true</param>
public IBAutomater(string ibDirectory, string ibVersion, string userName, string password, string tradingMode, int portNumber, bool exportIbGatewayLogs)
{
_ibDirectory = ibDirectory;
_ibVersion = ibVersion;
_userName = userName;
_password = password;
_tradingMode = tradingMode;
_portNumber = portNumber;
_exportIbGatewayLogs = exportIbGatewayLogs;
_timerLogReader = new Timer(LogReaderTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
Restarted += (sender, e) =>
{
StopGatewayRestartTimeoutMonitor();
};
StartGatewayRestartCountResetTask();
}
public void Dispose()
{
if (_isDisposeCalled)
{
return;
}
_isDisposeCalled = true;
StopGatewayRestartTimeoutMonitor();
// remove Java agent setting from IB configuration file
UpdateIbGatewayConfiguration(GetIbGatewayVersionPath(), false);
}
/// <summary>
/// Starts the IB Gateway
/// </summary>
/// <param name="waitForExit">true if it should wait for the IB Gateway process to exit</param>
/// <remarks>The IB Gateway application will be launched</remarks>
public StartResult Start(bool waitForExit)
{
lock (_locker)
{
if (_lastStartResult.HasError)
{
// IBAutomater errors are unrecoverable
return _lastStartResult;
}
if (IsRunning())
{
return StartResult.Success;
}
_process = null;
_ibAutomaterInitializeEvent.Reset();
if (IsLinux)
{
// need permission for execution
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs("Setting execute permissions on IBAutomater.sh"));
ExecuteProcessAndWaitForExit("chmod", "+x IBAutomater.sh");
}
var ibGatewayVersionPath = GetIbGatewayVersionPath();
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"Loading IBGateway - Version: {_ibVersion} - Path: {ibGatewayVersionPath} - User: {_userName}"));
if (!Directory.Exists(ibGatewayVersionPath))
{
return new StartResult(ErrorCode.IbGatewayVersionNotInstalled, $"Version: {_ibVersion} - Path: {ibGatewayVersionPath}");
}
var jreInstallPath = GetJreInstallPath(ibGatewayVersionPath);
if (string.IsNullOrWhiteSpace(jreInstallPath))
{
return new StartResult(ErrorCode.JavaNotFound);
}
UpdateIbGatewayIniFile();
var javaAgent = UpdateIbGatewayConfiguration(ibGatewayVersionPath, true);
_timerLogReader.Change(Timeout.Infinite, Timeout.Infinite);
_ibGatewayLogFileName = Path.Combine(ibGatewayVersionPath, "IBAutomater.log");
lock (_logLocker)
{
if (File.Exists(_ibGatewayLogFileName))
{
File.Delete(_ibGatewayLogFileName);
}
}
_timerLogReader.Change(TimeSpan.Zero, TimeSpan.FromSeconds(1));
string fileName;
string arguments;
if (IsWindows)
{
fileName = $"{ibGatewayVersionPath}/ibgateway.exe";
arguments = string.Empty;
}
else
{
fileName = "IBAutomater.sh";
arguments = $"{ibGatewayVersionPath} {javaAgent}";
}
var process = new Process
{
StartInfo = new ProcessStartInfo(fileName, arguments)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true
},
EnableRaisingEvents = true
};
process.OutputDataReceived += SendTraceLog;
process.ErrorDataReceived += SendErrorLog;
process.Exited += OnProcessExited;
try
{
var started = process.Start();
if (!started)
{
return new StartResult(ErrorCode.ProcessStartFailed);
}
}
catch (Exception exception)
{
return new StartResult(
ErrorCode.ProcessStartFailed,
exception.Message.Replace(_password, "***"));
}
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"IBAutomater process started - Id:{process.Id} - Name:{process.ProcessName} - InitializationTimeout:{_initializationTimeout}"));
_process = process;
process.BeginErrorReadLine();
process.BeginOutputReadLine();
if (waitForExit)
{
process.WaitForExit();
}
else
{
// wait for completion of IBGateway login and configuration
string message;
if (_ibAutomaterInitializeEvent.WaitOne(_initializationTimeout))
{
var processName = IsWindows ? "ibgateway" : "java";
var p = Process.GetProcessesByName(processName).FirstOrDefault();
OutputDataReceived?.Invoke(this,
p != null
? new OutputDataReceivedEventArgs($"IBGateway process found - Id:{p.Id} - Name:{p.ProcessName}")
: new OutputDataReceivedEventArgs($"IBGateway process not found: {processName}"));
message = "IB Automater initialized.";
}
else
{
TraceIbLauncherLogFile();
var additionalMessage = string.Empty;
if (_isFirstStart && _isAuthenticating)
{
// unable to complete logon because IB weekend server reset is in progress
additionalMessage = "The logon process could not be completed because the IB server is busy or being reset for the weekend, please try again later.";
}
_lastStartResult = new StartResult(ErrorCode.InitializationTimeout, additionalMessage);
message = "IB Automater initialization timeout. " + additionalMessage;
}
_isFirstStart = false;
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(message));
if (_lastStartResult.HasError)
{
message = $"IBAutomater error - Code: {_lastStartResult.ErrorCode} Message: {_lastStartResult.ErrorMessage}";
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(message));
return _lastStartResult;
}
}
}
return StartResult.Success;
}
private void LogReaderTimerCallback(object _)
{
try
{
lock (_logLocker)
{
if (string.IsNullOrWhiteSpace(_ibGatewayLogFileName) || !File.Exists(_ibGatewayLogFileName))
{
return;
}
using (var fileStream = new FileStream(_ibGatewayLogFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
fileStream.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(fileStream))
{
var lines = new List<string>();
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
var totalLines = lines.Count;
if (totalLines < _logLinesRead)
{
// log file was rewritten by a restart of IBGateway
_logLinesRead = 0;
}
var newLinesCount = totalLines - _logLinesRead;
var newLines = lines.Skip(_logLinesRead).Take(newLinesCount);
_logLinesRead = totalLines;
if (newLinesCount > 0)
{
foreach (var newLine in newLines)
{
OnProcessOutputDataReceived(newLine);
}
}
}
}
}
}
catch (Exception exception)
{
var message = $"IBAutomater error in timer - Message: {exception.Message}";
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(message));
}
}
private void OnProcessOutputDataReceived(string text)
{
if (text != null)
{
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(text));
// login failed
if (text.Contains("Login failed", StringComparison.InvariantCultureIgnoreCase))
{
if (text.Contains("invalid characters in credentials", StringComparison.InvariantCultureIgnoreCase)
|| !IsWithinScheduledServerResetTimes())
{
_lastStartResult = new StartResult(ErrorCode.LoginFailed);
}
_ibAutomaterInitializeEvent.Set();
}
// an existing session was detected
else if (text.Contains("Existing session detected", StringComparison.InvariantCultureIgnoreCase))
{
_lastStartResult = new StartResult(ErrorCode.ExistingSessionDetected);
_ibAutomaterInitializeEvent.Set();
}
// a security dialog (2FA) was detected by IBAutomater
else if (text.Contains("Second Factor Authentication", StringComparison.InvariantCultureIgnoreCase))
{
if (text.Contains("[WINDOW_OPENED]", StringComparison.InvariantCultureIgnoreCase))
{
// waiting for 2FA confirmation on IBKR mobile app
const string message = "Waiting for 2FA confirmation on IBKR mobile app (to be confirmed within 3 minutes).";
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(message));
}
}
// 2FA timed out for the maximum number of attempts
else if (text.Contains("2FA maximum attempts reached", StringComparison.InvariantCultureIgnoreCase))
{
const string message = "IB Automater 2FA timeout.";
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(message));
_lastStartResult = new StartResult(ErrorCode.TwoFactorConfirmationTimeout);
_ibAutomaterInitializeEvent.Set();
}
// a security dialog (code card) was detected by IBAutomater
else if (text.Contains("Security Code Card Authentication", StringComparison.InvariantCultureIgnoreCase)
|| text.Contains("Enter security code", StringComparison.InvariantCultureIgnoreCase))
{
_lastStartResult = new StartResult(ErrorCode.SecurityDialogDetected);
_ibAutomaterInitializeEvent.Set();
}
// the IBGateway version is no longer supported
else if (text.Contains("is no longer supported", StringComparison.InvariantCultureIgnoreCase))
{
_lastStartResult = new StartResult(ErrorCode.UnsupportedVersion);
_ibAutomaterInitializeEvent.Set();
}
// a Java exception was thrown
if (text.StartsWith("Exception", StringComparison.InvariantCultureIgnoreCase))
{
TraceIbLauncherLogFile();
_lastStartResult = new StartResult(ErrorCode.JavaException, text);
_ibAutomaterInitializeEvent.Set();
}
// API support is not available for accounts that support free trading
else if (text.Contains("API support is not available", StringComparison.InvariantCultureIgnoreCase))
{
_lastStartResult = new StartResult(ErrorCode.ApiSupportNotAvailable);
_ibAutomaterInitializeEvent.Set();
}
// an unknown message window was detected
else if (text.StartsWith("Unknown message window detected", StringComparison.InvariantCultureIgnoreCase))
{
TraceIbLauncherLogFile();
_lastStartResult = new StartResult(ErrorCode.UnknownMessageWindowDetected, text);
_ibAutomaterInitializeEvent.Set();
}
// initialization completed
else if (text.Contains("Configuration settings updated", StringComparison.InvariantCultureIgnoreCase))
{
// load server name and region
LoadIbServerInformation();
_ibAutomaterInitializeEvent.Set();
}
// daily restart with no authentication required
else if (text.Contains("Restart in progress", StringComparison.InvariantCultureIgnoreCase)
|| text.Contains("The application will automatically restart in", StringComparison.InvariantCultureIgnoreCase))
{
_isRestartInProgress = true;
}
// weekly restart with full authentication
else if (text.Contains("Auto-restart token expired", StringComparison.InvariantCultureIgnoreCase))
{
_isRestartInProgress = false;
_ibAutomaterInitializeEvent.Set();
}
// authentication/connection in progress
if (text.Contains("Window event:", StringComparison.InvariantCultureIgnoreCase))
{
_isAuthenticating = text.Contains("Authenticating", StringComparison.InvariantCultureIgnoreCase) ||
text.Contains("Connecting to server", StringComparison.InvariantCultureIgnoreCase) ||
text.Contains("server error, will retry", StringComparison.InvariantCultureIgnoreCase);
}
}
}
private void OnProcessExited(object sender, EventArgs e)
{
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs("IBGateway process exited"));
if (_isRestartInProgress)
{
_ibAutomaterInitializeEvent.Reset();
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs("Waiting for IBGateway auto-restart"));
if (!_ibAutomaterInitializeEvent.WaitOne(_initializationTimeout))
{
TraceIbLauncherLogFile();
_lastStartResult = new StartResult(ErrorCode.InitializationTimeout, "Auto-restart timed out");
// fire Exited event so the client can reconnect or die
Exited?.Invoke(this, new ExitedEventArgs(0));
return;
}
if (_isRestartInProgress)
{
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs("IB Automater initialized."));
// find new IBGateway process (created by auto-restart)
var process = GetIbGatewayProcess();
if (process == null)
{
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"IBGateway restarted process not found"));
TraceIbLauncherLogFile();
_lastStartResult = new StartResult(ErrorCode.RestartedProcessNotFound, "IBGateway process was not found after restart");
// fire Exited event so the client can reconnect or die
Exited?.Invoke(this, new ExitedEventArgs(0));
}
else
{
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"IBGateway restarted process found: Id:{process.Id} - Name:{process.ProcessName}. Arguments: {GetProcessArguments(process)}"));
// fire Restarted event so the client can reconnect only (without starting IBGateway)
Restarted?.Invoke(this, new EventArgs());
process.Exited -= OnProcessExited;
// replace process
_process = process;
// we cannot add output/error redirection event handlers here as we didn't start the process
process.Exited += OnProcessExited;
process.EnableRaisingEvents = true;
}
_isRestartInProgress = false;
}
else
{
Exited?.Invoke(this, new ExitedEventArgs(GetProcessExitCode(_process)));
}
}
else
{
Exited?.Invoke(this, new ExitedEventArgs(GetProcessExitCode(_process)));
}
}
/// <summary>
/// Stops the IB Gateway
/// </summary>
/// <remarks>The IB Gateway application will be terminated</remarks>
public void Stop()
{
lock (_locker)
{
if (!IsRunning())
{
return;
}
_timerLogReader.Change(Timeout.Infinite, Timeout.Infinite);
var ibGatewayVersionPath = GetIbGatewayVersionPath();
var shutdownFilePath = Path.Combine(ibGatewayVersionPath, "shutdown");
File.WriteAllBytes(shutdownFilePath, Array.Empty<byte>());
// stop any restart threads
StopGatewayRestartTimeoutMonitor();
// then we wait for the process to exit.
// we'll wait 15 seconds, since it will take up to 1 second for the java automater to receive the signal
// plus a 14 second buffer for the gateway to exit.
if (!_process.WaitForExit(15000))
{
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(
"Timeout waiting for the IBAutomater to shutdown the IB Gateway. Proceeding to kill the process."));
// if the process does not exit after a timeout, then we kill it
if (IsWindows)
{
foreach (var process in Process.GetProcesses())
{
try
{
if (process.MainWindowTitle.ToLower().Contains("gateway"))
{
process.Kill();
}
}
catch (Exception)
{
// ignored
}
}
}
else
{
try
{
Process.Start("pkill", "java");
Process.Start("pkill", "Xvfb");
}
catch (Exception)
{
// ignored
}
}
// wait for the process to exit
_process.WaitForExit();
}
_process = null;
}
}
/// <summary>
/// Restarts the IB Gateway
/// </summary>
/// <remarks>The IB Gateway application will be restarted</remarks>
public StartResult Restart()
{
lock (_locker)
{
Stop();
Thread.Sleep(2500);
return Start(false);
}
}
/// <summary>
/// Triggers a restart from within the IB Gateway using it's daily restart functionality.
/// This is different than normal restart because it will not require a 2FA call
/// </summary>
public void SoftRestart()
{
if (_isDisposeCalled || _gatewaySoftRestartTokenSource != null && !_gatewaySoftRestartTokenSource.IsCancellationRequested)
{
return;
}
// We increment the restart delay each time we try to restart the gateway within an hour to limit the number of restarts.
var currentRestartCount = Interlocked.Increment(ref _gatewaySoftRestartCount);
var delay = TimeSpan.FromMinutes(5) * (currentRestartCount - 1);
// we take the lock to avoid it getting disposed while we are evaluating it
lock (_gatewaySoftRestartTokenSource ?? new object())
{
_gatewaySoftRestartTokenSource?.Dispose();
_gatewaySoftRestartTokenSource = new CancellationTokenSource();
}
Task.Delay(delay, _gatewaySoftRestartTokenSource.Token).ContinueWith(_ =>
{
if (_isDisposeCalled)
{
return;
}
lock (_locker)
{
var ibGatewayVersionPath = GetIbGatewayVersionPath();
var restartFilePath = Path.Combine(ibGatewayVersionPath, "restart");
File.WriteAllBytes(restartFilePath, Array.Empty<byte>());
StartGatewayRestartTimeoutMonitor();
};
});
}
/// <summary>
/// Gets the last <see cref="StartResult"/> instance
/// </summary>
/// <returns>Returns the last start result instance</returns>
public StartResult GetLastStartResult()
{
return _lastStartResult;
}
/// <summary>
/// This function is used to decide whether or not we should kill an algorithm
/// when we lose contact with IB servers. IB performs server resets nightly
/// and on Fridays they take everything down, so we'll prevent killing algos
/// during the scheduled reset times.
/// </summary>
public bool IsWithinScheduledServerResetTimes()
{
// Use schedule based on server region:
// https://www.interactivebrokers.com/en/index.php?f=2225
bool result;
var utcTime = DateTime.UtcNow;
var newYorkTime = utcTime.ConvertFromUtc(TimeZoneNewYork);
var newYorkTimeOfDay = newYorkTime.TimeOfDay;
if (IsWithinWeekendServerResetTimes(utcTime))
{
result = true;
}
else
{
switch (_ibServerRegion)
{
case Region.Europe:
{
// Saturday - Thursday: 05:45 - 06:45 CET
var euTime = utcTime.ConvertFromUtc(TimeZoneZurich);
var euTimeOfDay = euTime.TimeOfDay;
result = euTimeOfDay > new TimeSpan(5, 30, 0) && euTimeOfDay < new TimeSpan(7, 0, 0);
}
break;
case Region.Asia:
{
// Saturday - Thursday: First reset: 16:30 - 17:00 ET
if (newYorkTimeOfDay > new TimeSpan(16, 15, 0) && newYorkTimeOfDay < new TimeSpan(17, 15, 0))
{
result = true;
}
else
{
// Saturday - Thursday: Second reset: 20:15 - 21:00 HKT
var hkTime = utcTime.ConvertFromUtc(TimeZoneHongKong);
var hkTimeOfDay = hkTime.TimeOfDay;
result = hkTimeOfDay > new TimeSpan(20, 0, 0) && hkTimeOfDay < new TimeSpan(21, 15, 0);
}
}
break;
case Region.America:
default:
{
// Saturday - Thursday: 23:45 - 00:45 ET
result = newYorkTimeOfDay > new TimeSpan(23, 30, 0) || newYorkTimeOfDay < new TimeSpan(1, 0, 0);
}
break;
}
}
if (result != _isWithinScheduledServerResetTimesLastValue)
{
_isWithinScheduledServerResetTimesLastValue = result;
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(
$"IBAutomater.IsWithinScheduledServerResetTimes(): {result}"));
}
return result;
}
/// <summary>
/// Returns whether the current time is within the IB weekend server reset period.
/// </summary>
public bool IsWithinWeekendServerResetTimes()
{
return IsWithinWeekendServerResetTimes(DateTime.UtcNow);
}
/// <summary>
/// Returns whether the current time is within the IB weekend server reset period.
/// </summary>
public bool IsWithinWeekendServerResetTimes(DateTime utcTime)
{
// Use schedule based on server region:
// https://www.interactivebrokers.com/en/index.php?f=2225
bool result = false;
var newYorkTime = utcTime.ConvertFromUtc(TimeZoneNewYork);
var newYorkTimeOfDay = newYorkTime.TimeOfDay;
// Note: we add 15 minutes *before* and *after* all time ranges for safety margin
// During the Friday evening reset period, all services will be unavailable in all regions for the duration of the reset.
if (newYorkTime.DayOfWeek == DayOfWeek.Friday && newYorkTimeOfDay > new TimeSpan(22, 45, 0) ||
// Occasionally the disconnection due to the IB reset period might last
// much longer than expected during weekends (even up to the cash sync time).
newYorkTime.DayOfWeek == DayOfWeek.Saturday ||
// Occasionally disconnection on the first hours of Sunday
newYorkTime.DayOfWeek == DayOfWeek.Sunday && newYorkTimeOfDay < new TimeSpan(2, 0, 0))
{
// Friday: 23:00 - 03:00 ET for all regions
result = true;
}
return result;
}
/// <summary>
/// Returns whether the IBGateway is running
/// </summary>
/// <returns>true if the IBGateway is running</returns>
public bool IsRunning()
{
lock (_locker)
{
if (_process == null)
{
return false;
}
var exited = _process.HasExited;
if (exited)
{
_process = null;
}
return !exited;
}
}
private void ExecuteProcessAndWaitForExit(string fileName, string arguments)
{
var p = new Process
{
StartInfo = new ProcessStartInfo(fileName, arguments)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true
},
EnableRaisingEvents = true
};
p.OutputDataReceived += (sender, e) =>
{
if (e.Data != null)
{
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"{fileName}: {e.Data}"));
}
};
p.ErrorDataReceived += (sender, e) =>
{
if (e.Data != null)
{
ErrorDataReceived?.Invoke(this, new ErrorDataReceivedEventArgs($"{fileName}: {e.Data}"));
}
};
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
p.WaitForExit();
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"{fileName} {arguments}: process exit code: {p.ExitCode}"));
}
private static bool IsLinux
{
get
{
var p = (int)Environment.OSVersion.Platform;
return p == 4 || p == 6 || p == 128;
}
}
private static bool IsWindows => !IsLinux;
private void LoadIbServerInformation()
{
// After a successful login, IBGateway saves the connected/redirected host name to the Peer key in the jts.ini file.
var iniFileName = GetIbGatewayIniFile();
// Note: Attempting to connect to a different server via jts.ini will not change anything.
// IB will route you back to the server they have set for you on their server side.
// You need to request a server change and only then will your system connect to the changed server address.
if (File.Exists(iniFileName))
{
const string key = "Peer=";
foreach (var line in File.ReadLines(iniFileName))
{
if (line.StartsWith(key))
{
var value = line.Substring(key.Length);
_ibServerName = value.Substring(0, value.IndexOf(':'));
if (!_ibServerMap.TryGetValue(_ibServerName, out _ibServerRegion))
{
_ibServerRegion = Region.America;
ErrorDataReceived?.Invoke(this, new ErrorDataReceivedEventArgs(
$"LoadIbServerInformation(): Unknown server name: {_ibServerName}, region set to {_ibServerRegion}"));
}
// known server name and region
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(
$"LoadIbServerInformation(): ServerName: {_ibServerName}, ServerRegion: {_ibServerRegion}"));
return;
}
}
_ibServerRegion = Region.America;
ErrorDataReceived?.Invoke(this, new ErrorDataReceivedEventArgs(
$"LoadIbServerInformation(): Unable to find the server name in the IB ini file: {iniFileName}, region set to {_ibServerRegion}"));
}
else
{
ErrorDataReceived?.Invoke(this, new ErrorDataReceivedEventArgs(
$"LoadIbServerInformation(): IB ini file not found: {iniFileName}"));
}
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(
$"LoadIbServerInformation(): ServerName: {_ibServerName}, ServerRegion: {_ibServerRegion}"));
}
private string GetJreInstallPath(string ibGatewayVersionPath)
{
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs("Searching for TWS JRE path"));
// Find TWS Java location (depends on OS and IBGateway version)
var install4JPath = $"{ibGatewayVersionPath}/.install4j";
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"Install4J path: {install4JPath}"));
foreach (var fileName in new[] { "pref_jre.cfg", "inst_jre.cfg" })
{
var install4JConfigFileName = $"{install4JPath}/{fileName}";
if (File.Exists(install4JConfigFileName))
{
OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"File found: {install4JConfigFileName}"));
var jreInstallPath = File.ReadAllText(install4JConfigFileName)