{"id":19553590,"url":"https://github.com/quantconnect/ibautomater","last_synced_at":"2025-05-15T17:03:53.925Z","repository":{"id":34870259,"uuid":"180573226","full_name":"QuantConnect/IBAutomater","owner":"QuantConnect","description":"Automates IB Gateway start, stopping and restarting.","archived":false,"fork":false,"pushed_at":"2025-03-24T16:23:52.000Z","size":321,"stargazers_count":113,"open_issues_count":5,"forks_count":45,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-04-30T09:50:20.256Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://www.lean.io","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/QuantConnect.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-04-10T12:06:19.000Z","updated_at":"2025-04-29T10:42:32.000Z","dependencies_parsed_at":"2024-08-02T13:21:55.982Z","dependency_job_id":"d725b01d-4ba9-46a1-97d4-bb5bdfea9881","html_url":"https://github.com/QuantConnect/IBAutomater","commit_stats":{"total_commits":159,"total_committers":8,"mean_commits":19.875,"dds":0.2075471698113207,"last_synced_commit":"e896b2715a2654df2b2ffbeef032f2c907622c17"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/QuantConnect%2FIBAutomater","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/QuantConnect%2FIBAutomater/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/QuantConnect%2FIBAutomater/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/QuantConnect%2FIBAutomater/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/QuantConnect","download_url":"https://codeload.github.com/QuantConnect/IBAutomater/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254384983,"owners_count":22062422,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-11T04:23:57.891Z","updated_at":"2025-05-15T17:03:53.901Z","avatar_url":"https://github.com/QuantConnect.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# QuantConnect / IBAutomater\n\nIBAutomater is an automation tool for IB Gateway v978 and above. It supports starting, stopping and automated logins for IB Gateway. This package is best used in conjunction with LEAN. LEAN handles the automatic login and portfolio construction once you start the IB Gateway.\n\n## Installation\n\nIBAutomater is available on [NuGet](https://www.nuget.org/packages/QuantConnect.IBAutomater/):\n\n`PM\u003e Install-Package QuantConnect.IBAutomater`\n\nTo get started with IBAutomater, first you will need to get the library itself. The easiest way to do this is to install the package into your project using  [NuGet](https://www.nuget.org/packages/QuantConnect.IBAutomater/). Using Visual Studio this can be done in two ways.\n\n#### Using the package manager\n\nIn Visual Studio right click on your solution and select 'Manage NuGet Packages for solution...'. A screen will appear which initially shows the currently installed packages. At the top select 'Browse'. This will let you download the package from the NuGet server. In the search box type 'QuantConnect.IBAutomater'. The QuantConnect.IBAutomater package should come up in the results. After selecting the package you can then on the right hand side select in which projects in your solution the package should install. After you've selected all projects you wish to install and use QuantConnect.IBAutomater in click 'Install' and the package will be downloaded and added to your selected projects.\n\n#### Using the package manager console\n\nIn Visual Studio in the top menu select 'Tools' -\u003e 'NuGet Package Manager' -\u003e 'Package Manager Console'. This should open up a command line interface. On top of the interface there is a dropdown menu where you can select the Default Project. This is the project that IBAutomater will be installed in. After selecting the correct project type Install-Package QuantConnect.IBAutomater in the command line interface. This should install the latest version of the package in your project.\n\nAfter doing either of above steps you should now be ready to start using IBAutomater.\n\n## Code example\n\n``` C#\nusing QuantConnect.IBAutomater;\n\n// Create a new instance of IBAutomater\n_ibAutomater = new IBAutomater.IBAutomater(ibDirectory, ibVersion, userName, password, tradingMode, port, exportIbGatewayLogs);\n\n// You can bind to event handlers to receive the output data.\n_ibAutomater.OutputDataReceived += OnIbAutomaterOutputDataReceived;\n\n// Gracefully handle errors\n_ibAutomater.ErrorDataReceived += OnIbAutomaterErrorDataReceived;\n\n// Get events once the IB Gateway has exited.\n_ibAutomater.Exited += OnIbAutomaterExited;\n\n// Get events once the IB Gateway has auto-restarted.\n_ibAutomater.Restarted += OnIbAutomaterRestarted;\n\n// Trigger the IB Gateway to start and login with your configured parameters.\n_ibAutomater.Start(false);\n\n// Stop IB Gateway with a simple command.\n_ibAutomater.Stop();\n```\n\n## How it works\n\nIBAutomater has been implemented as two components:\n\n1. a Java component (.jar file)\n\n    The IBAutomater.jar file is loaded as a Java agent into the IB Gateway process with the following advantages:\n    \n    - remove the requirement of installing Java separately as IB Gateway uses a bundled version of the Java runtime\n    - avoid dependencies on the IB Gateway jar libraries\n    - allow us to handle auto-restarts requiring full authentication only weekly (instead of daily)\n\n    More information on the Java Instrumentation API can be found [here](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/package-summary.html)\n\n    This component is responsible for interacting with the IB Gateway user interface, performing the following tasks:\n\n    - entering login credentials\n    - configuring IB Gateway settings\n    - dismissing message and confirmation windows\n  \n2. a C# component (.dll file), .NET assembly built for both NET Standard 2.0 and NET 5.0\n\n    This component takes care of the following tasks:\n\n    - starting and stopping the IB Gateway\n    - notifying the client application of any error conditions\n    - firing events such as `Exited` and `Restarted`\n\n## IB Gateway auto-restarts\n\nAs the IB Gateway requires a daily shutdown (or restart), \nIBAutomater always selects auto-restart instead of auto-logoff \nbecause it allows users with 2FA enabled to authenticate only once per week instead of each day.\n\nIBAutomater handles the detection of auto-restarts and notifies the client application with events.\nThese are the two events that have to be handled by the client:\n1. `Restarted` - The IB Gateway was auto-restarted with no authentication required (soft restart),\nthis happens every day at the configured auto-restart time.\n\n\u003e For now IBAutomater does not set the auto-restart time \n(the default time is 11:45 PM, in the system timezone), \nbut this setting might be configurable in future versions. \n\n2. `Exited` - The IB Gateway was closed by IBAutomater (because full authentication is required or there was an error)\nand the client application is responsible for \nrestarting the IB Gateway via the `Start()` method.\n\n###### Example auto-restart event handling code\n\n``` C#\n\nprivate void OnIbAutomaterExited(object sender, ExitedEventArgs e)\n{\n    // check if IB Gateway was closed because of an IBAutomater error\n    var result = _ibAutomater.GetLastStartResult();\n    CheckIbAutomaterError(result);\n\n    if (!result.HasError)\n    {\n        // IB Gateway was closed by IBAutomater because the auto-restart token expired or it was closed manually (less likely)\n        Console.WriteLine(\"OnIbAutomaterExited(): IB Gateway close detected, restarting IBAutomater in 10 seconds...\");\n\n        // Wait a few seconds for IB Gateway to shutdown\n        Thread.Sleep(TimeSpan.FromSeconds(10));\n\n        try\n        {\n            // Close the client API connection\n            Disconnect();\n\n            // Restart IB Gateway\n            CheckIbAutomaterError(_ibAutomater.Start(false));\n\n            // Open the client API connection\n            Connect();\n        }\n        catch (Exception exception)\n        {\n            Console.WriteLine($\"OnIbAutomaterExited(): IBAutomaterRestartError - {exception}\");\n        }\n    }\n}\n\nprivate void OnIbAutomaterRestarted(object sender, EventArgs e)\n{\n    // check if IB Gateway was closed because of an IBAutomater error\n    var result = _ibAutomater.GetLastStartResult();\n    CheckIbAutomaterError(result);\n\n    if (!result.HasError)\n    {\n        // IB Gateway was restarted automatically\n        Console.WriteLine(\"OnIbAutomaterRestarted(): IB Gateway restart detected, reconnecting...\");\n\n        try\n        {\n            // Close the client API connection\n            Disconnect();\n\n            // Open the client API connection\n            Connect();\n        }\n        catch (Exception exception)\n        {\n            Console.WriteLine($\"OnIbAutomaterRestarted(): IBAutomaterAutoRestartError - {exception}\");\n        }\n    }\n}\n\nprivate void CheckIbAutomaterError(StartResult result)\n{\n    if (result.HasError)\n    {\n        // notify the user that an IBAutomater error has occurred\n        Console.WriteLine($\"CheckIbAutomaterError(): {result.ErrorCode} - {result.ErrorMessage}\");\n    }\n}\n```\n\n## IB weekend/maintenance periods\n\nAccording to the [IB documentation](https://www.interactivebrokers.com/en/index.php?f=2225), \nthe IB weekend reset times should start on Friday at 23:00 ET and should last four hours, \nbut sometimes the maintenance lasts more and during this period the IB Gateway is unable to complete a Login operation.\n\nFor this reason IBAutomater detects failed login attempts during this period \nand automatically closes the IBGateway application (although IBGateway will sometimes exit by itself).\n\nIf the client application intends to continue running through the weekend, it should handle the `OnExited` event\nand delay further connection attempts until the next Sunday at 4:00 PM ET \n(one hour before Forex markets open), when we expect to be able to login successfully.\n\n## Two-factor authentication (2FA)\n\nThe only 2FA method supported by IBAutomater is the IBKR mobile application with seamless authentication enabled.\n\nThe 2FA request will only be sent to the phone when logging in for the first time at startup and once per week after the weekly auto-restart.\n\nWhen this method is selected, IB Gateway shows a 2FA popup window (after the user/password credentials have been validated)\nand waits for the user to complete the authentication by entering the PIN on the phone.\n\nIf the PIN is correct, the popup window will automatically close and both IB Gateway and IBAutomater will proceed normally.\n\nIf the PIN is incorrect (or the user does not send a PIN within 3 minutes) the window will automatically close/reopen \nand IB Gateway will send another 2FA request to the phone.\n\nAfter three failed attempts, IBAutomater will be terminated and \nshow the following error message:\n```\nThe two factor authentication request timed out. \nThe request must be confirmed within 3 minutes.\n```\n\n## How to build\n\nTo build the NuGet package we need to complete the following three steps in order:\n1. Build the Java project\n2. Build the C# solution\n3. Upload the new package to NuGet\n\n#### 1. Java build (with NetBeans)\n\n- Download Apache NetBeans 12.x [here](https://netbeans.apache.org/)\n- Install Apache NetBeans 12.1 or higher (currently bundled Java version: JDK 15)\n- Open the project in /IBAutomater/java/IBAutomater\n- Build the project: MainMenu -\u003e Run -\u003e Clean and Build Project\n  - output: /IBAutomater/java/IBAutomater/dist/IBAutomater.jar\n\n#### 2. C# build (with Visual Studio)\n\n- Increment the version number in QuantConnect.IBAutomater.csproj\n- Open the solution file: /IBAutomater/IBAutomater.sln\n- Rebuild solution \u0026 test locally\n\n#### 3. NuGet upload\n\n- In the /IBAutomater/ folder, run the following commands:\n```\n  dotnet pack QuantConnect.IBAutomater/QuantConnect.IBAutomater.csproj --output ./packages -p:PackageVersion=2.0.XXXX --configuration Release --include-symbols\n```\n- Extract `QuantConnect.IBAutomater.2.0.XXXX.nupkg` to sanity test it's contents before pushing\n- Make sure 'IBAutomater.sh' line endings are unix\n```\n  dotnet nuget push ./packages/QuantConnect.IBAutomater.2.0.XXXX.nupkg --api-key \u003cAPI KEY\u003e --source https://api.nuget.org/v3/index.json\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fquantconnect%2Fibautomater","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fquantconnect%2Fibautomater","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fquantconnect%2Fibautomater/lists"}