Skip to main content

Interactive Brokers OAuth

Project description

IBKR Authentication Workflow

codecov

Interactive Brokers provides an extensive API that can be used for trading and account management.

It's also possible to authenticate for the API via OAuth.

ibauth is a Python client for handling the full Interactive Brokers (IBKR) Web API authentication flow. It wraps the OAuth2 + session lifecycle steps (access_token, bearer_token, ssodh_init, tickle, etc.) into a simple, reusable interface.

🔑 Features:

  • Obtain and refresh IBKR OAuth2 tokens.
  • Manage brokerage sessions (ssodh_init, validate_sso, tickle, logout).
  • YAML-based configuration (easy to keep credentials outside of code).
  • Logging of requests and responses for troubleshooting.

Documentation for the IBKR Web API can be found in the official reference.

API Gateway

https://www.interactivebrokers.com/campus/ibkr-api-page/cpapi-v1/#gw-step-one

Basically during the process the java app creates a local address to which you use as the base URL. The java app then handles all the encrypted stuff between it and IBKR. Once the portal is setup, then you need to go to it, and there will be a loing page, you need to input your details and submit, I used Python believe it or not, with Selenium. At that stage the warning bells should have rung that Matlab could not do this, hence having to do Python. And no ChatGPT back then, it was shit hard figure it out. Dunno how I did it, must have been all thos monkeys typing random stuff on those keyboards. Anyhow, then when you submite, they requre authentication. Forpaper trading account you could use and SMS code, and this could be achieved through google messages, no hardware needed. BUT, when it came to live acounts, that is 2FA, straight through their app and it pops up asking you to click, then to ask if you want to proceed, then provide your fingerprint. That is where the robot came in.

When OAuth is selected as an authentication method with IBKR, this is typically allocated to a FA (Financial Advisor) account, which may have 1 or more client accounts under its control. Typically the FA account will have have paid data subscriptions which provide real-time market data, and this may be applied in the trading functions on all the client accounts. The FA account directs trading on behalf of the client accounts, with their allocated capital.


Requirements

  • Python 3.11+
  • A valid IBKR account with Web API access enabled.
  • An RSA private key (.pem) registered with IBKR.

Dependencies are listed in requirements.txt.


Installation

You can install either from PyPI (preferred) or GitHub (which may give access to updates not yet published on PyPI).

# Install from PyPI.
pip install ibauth

# Install from GitHub.
pip install git+https://github.com/datawookie/ibkr-oauth-flow

Configuration

Authentication parameters are supplied via a YAML configuration file:

client_id: "your-client-id"
client_key_id: "your-client-key-id"
credential: "your-credential"
private_key_file: "/path/to/privatekey.pem"
domain: "api.ibkr.com"
  • client_id: Application client ID from IBKR.
  • client_key_id: Key identifier associated with your private key.
  • credential: IBKR credential string.
  • private_key_file: Path to your RSA private key (.pem).
  • domain: Usually api.ibkr.com, but IBKR supports numbered subdomains (1.api.ibkr.com, 5.api.ibkr.com, …).

How It Works

The IBKR Web API requires multiple steps to establish and maintain a brokerage session. ibauth automates these steps:

  1. Access Token Exchange your client credentials + JWS for an access token. → auth.get_access_token()

  2. Bearer Token Use the access token and your public IP to obtain a bearer token. → auth.get_bearer_token()

  3. Session Initialisation Start a brokerage session using the bearer token. → auth.ssodh_init()

  4. Session Validation (optional) Confirm that your session is active. → auth.validate_sso()

  5. Keepalive ("Tickle") Periodically ping the API to keep the session alive. → auth.tickle()

  6. Logout End the session when finished. → auth.logout()

    +--------------+        +--------------+        +---------------+
    |  Access      |        |  Bearer      |        |  Brokerage    |
    |  Token       | -----> |  Token       | -----> |  Session      |
    +--------------+        +--------------+        +---------------+
           |                        |                        |
           v                        v                        v
    get_access_token()     get_bearer_token()       ssodh_init() / tickle()

Quick Start

import logging
import time
import ibauth

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)7s] %(message)s",
)

logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("charset_normalizer").setLevel(logging.WARNING)

if __name__ == "__main__":
    auth = ibauth.auth_from_yaml("config.yaml")

    auth.get_access_token()
    auth.get_bearer_token()

    auth.ssodh_init()
    auth.validate_sso()

    # Keep session alive
    for _ in range(3):
        auth.tickle()
        time.sleep(10)

    # Dynamically change the API domain
    auth.domain = "5.api.ibkr.com"
    auth.tickle()

    auth.logout()

Testing

This project uses pytest. To run the test suite:

pytest

To include coverage:

pytest --cov=src/ibauth --cov-report=term-missing

Development

Clone the repo and install dependencies into a virtual environment:

git clone https://github.com/datawookie/ibkr-oauth-flow.git
cd ibkr-oauth-flow
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Deploy to PyPI

This requires UV_PUBLISH_TOKEN to be set to a PyPi token in environment.

Publishing requires a PyPI token (UV_PUBLISH_TOKEN) to be available in your environment.

make deploy

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ibauth-0.0.8.tar.gz (13.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ibauth-0.0.8-py3-none-any.whl (9.0 kB view details)

Uploaded Python 3

File details

Details for the file ibauth-0.0.8.tar.gz.

File metadata

  • Download URL: ibauth-0.0.8.tar.gz
  • Upload date:
  • Size: 13.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.2

File hashes

Hashes for ibauth-0.0.8.tar.gz
Algorithm Hash digest
SHA256 3b4f002677daaad061b4d679344a140366ba9031139212ddf5a04a7030e88b35
MD5 ed39cb73e043fec5f72da18af841fae8
BLAKE2b-256 5aba67500845126546e9cbef367a671b8714e68ffe5e634368c6e8fbbcd13f45

See more details on using hashes here.

File details

Details for the file ibauth-0.0.8-py3-none-any.whl.

File metadata

  • Download URL: ibauth-0.0.8-py3-none-any.whl
  • Upload date:
  • Size: 9.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.2

File hashes

Hashes for ibauth-0.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 506390922fa588a58b5e5cf29a85a4641ac6f7d0d5282a32200696641efab71b
MD5 2463856a898ecd3589169221e0a1751b
BLAKE2b-256 e8c9d957aff7d384192c0ff3adcefb80e8d5d949bba0a615b0726296c028be7d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page