IBAutomater

repository·master·Indexed 40 days ago

https://github.com/quantconnect/ibautomater

An automation tool for IB Gateway (v978+) designed to handle starting, stopping, and automated logins. Optimized for use with LEAN, it manages the IB Gateway lifecycle, including daily auto-restarts and weekly 2FA requirements via a Java agent and a .NET assembly supporting .NET Standard 2.0 and .NET 5.0.

Tokens
1.8K
Snippets
4
Records
6
Agent score
0%

What's inside IBAutomater

  1. How IBAutomater works

    master

    IBAutomater consists of two integrated components:

    1. Java Component (IBAutomater.jar): Loaded as a Java agent into the IB Gateway process. It interacts directly with the IB Gateway UI to enter credentials, configure settings, and dismiss popups. This approach avoids external Java dependencies and allows for weekly-only full authentication via auto-restarts.
    2. C# Component (.dll): A .NET assembly (supporting .NET Standard 2.0 and .NET 5.0) that manages the process lifecycle (starting/stopping), notifies the client of errors, and fires lifecycle events like Exited and Restarted.
  2. Two-factor authentication (2FA) requirements

    master

    IBAutomater supports 2FA via the IBKR mobile application with seamless authentication enabled.

    • Frequency: 2FA is required only during the first login at startup and once per week after the weekly auto-restart.
    • Process: After credentials are validated, a 2FA popup appears in IB Gateway. The user must enter the PIN on their phone.
    • Timeouts: The user has 3 minutes to respond. If the PIN is incorrect or the timeout is reached, the window reopens. After three failed attempts, IBAutomater terminates with the error: The two factor authentication request timed out. The request must be confirmed within 3 minutes.
  3. Install QuantConnect.IBAutomater via NuGet

    master

    You can install the IBAutomater library using the NuGet Package Manager in Visual Studio.

    Using the Package Manager Console

    Open the Package Manager Console via Tools -> NuGet Package Manager -> Package Manager Console. Ensure the correct project is selected in the dropdown, then run:

    Install-Package QuantConnect.IBAutomater

    Using the Visual Studio GUI

    1. Right-click your solution and select Manage NuGet Packages for solution....
    2. Select the Browse tab.
    3. Search for QuantConnect.IBAutomater.
    4. Select the package and choose the target projects in the right-hand pane.
    5. Click Install.
    PM> Install-Package QuantConnect.IBAutomater
  4. Create a new version of the NuGet package

    master

    To release a new version of the QuantConnect.IBAutomater NuGet package, follow these steps:

    1. Update Version: Open QuantConnect.IBAutomater.csproj and update the version number.
    2. Pack the Project: Generate the .nupkg file using the dotnet CLI.
    3. Configure API Key: Ensure your NuGet API key is set in your environment.
    4. Push to NuGet: Upload the generated package to the NuGet gallery.
    # 1. Pack the project
    dotnet pack
    
    # 2. Set the API key
    nuget setApiKey <my-api-key>
    
    # 3. Push the package (replace version as needed)
    nuget push QuantConnect.IBAutomater.1.0.1.nupkg -Source https://api.nuget.org/v3/index.json
  5. Handle IB Gateway auto-restarts and exits

    master

    IBAutomater uses auto-restarts instead of auto-logoff to allow users with 2FA to authenticate only once per week. You must handle two specific events to maintain connectivity:

    1. Restarted: Triggered during a 'soft restart' (daily auto-restart). No authentication is required. You should use this event to reconnect your client API connection.
    2. Exited: Triggered when IB Gateway is closed because full authentication is required (e.g., weekly reset) or an error occurred. You are responsible for calling Start() to restart the gateway.

    Note on Weekend Maintenance: During IB weekend maintenance (typically Friday 23:00 ET to Sunday), login attempts will fail. If your application runs through the weekend, handle the Exited event and delay restart attempts until Sunday at 4:00 PM ET.

    private void OnIbAutomaterExited(object sender, ExitedEventArgs e)
    {
        var result = _ibAutomater.GetLastStartResult();
        if (!result.HasError)
        {
            // IB Gateway was closed because auto-restart token expired
            Thread.Sleep(TimeSpan.FromSeconds(10));
            Disconnect();
            _ibAutomater.Start(false);
            Connect();
        }
    }
    
    private void OnIbAutomaterRestarted(object sender, EventArgs e)
    {
        var result = _ibAutomater.GetLastStartResult();
        if (!result.HasError)
        {
            // Soft restart detected, reconnect client API
            Disconnect();
            Connect();
        }
    }
    
    private void CheckIbAutomaterError(StartResult result)
    {
        if (result.HasError)
        {
            Console.WriteLine($"{result.ErrorCode} - {result.ErrorMessage}");
        }
    }
  6. Use the IBAutomater API

    master

    To automate IB Gateway, instantiate the IBAutomater class with your configuration parameters and subscribe to its events to handle lifecycle changes like restarts or errors.

    Constructor Parameters:

    • ibDirectory: Directory of IB Gateway.
    • ibVersion: IB Gateway version.
    • userName: IB Gateway username.
    • password: IB Gateway password.
    • tradingMode: Trading mode.
    • port: Port number.
    • exportIbGatewayLogs: Boolean to export logs.

    Key Methods:

    • Start(bool): Triggers IB Gateway to start and login.
    • Stop(): Stops IB Gateway.
    • GetLastStartResult(): Retrieves the result of the last start attempt, including error details.
    using QuantConnect.IBAutomater;
    
    // Create a new instance of IBAutomater
    _ibAutomater = new IBAutomater.IBAutomater(ibDirectory, ibVersion, userName, password, tradingMode, port, exportIbGatewayLogs);
    
    // Bind to event handlers
    _ibAutomater.OutputDataReceived += OnIbAutomaterOutputDataReceived;
    _ibAutomater.ErrorDataReceived += OnIbAutomaterErrorDataReceived;
    _ibAutomater.Exited += OnIbAutomaterExited;
    _ibAutomater.Restarted += OnIbAutomaterRestarted;
    
    // Control IB Gateway
    _ibAutomater.Start(false);
    _ibAutomater.Stop();