Degiro Connector

repository·main·Indexed 43 days ago

https://github.com/chavithra/degiro-connector

A Python library for interfacing with the Degiro API. Version 3.0.36 allows users to manage trades, access account and portfolio information, retrieve company data, and consume real-time market data streams and chart series via the Quotecast API.

Tokens
17.8K
Snippets
69
Records
77
Agent score
55%

What's inside Degiro Connector

  1. Overview of degiro-connector features

    main

    The degiro-connector provides access to various Degiro API endpoints. Key capabilities include:

    • Account & Portfolio: Retrieve account info, cash reports (CSV, HTML, PDF, XLS), account overview, portfolio lists, and transaction history.
    • Trading: Create, update, and delete orders; manage pending orders; and establish trading connections.
    • Market Data: Fetch real-time data via Quotecasts, retrieve chart data, and search for products (Stocks, ETFs, Bonds, etc.).
    • Company Information: Access company profiles, financial statements, ratios, estimates, and news.
    • Personalization: Manage favorites lists and add/edit/delete notes related to products.
    • Real-time Data: Establish connections for real-time data streams and chart series.
  2. Understand the DataFrame structure for real-time data

    main

    When subscribing to data streams, the resulting DataFrame includes the chosen metrics plus these standard columns:

    • product_id: Product identifier (e.g., "AAPL.BATS,E").
    • response_datetime: Datetime when the data was received.
    • request_duration: Duration of the request used to fetch the data.
  3. Distinguish between user_token and int_account

    main

    It is critical to use the correct identifier for the intended task:

    • user_token: Used to fetch real-time data and charts (via the quotecast module).
    • int_account: Required for most trading operations (via the trading module).

    Note: int_account is NOT required for initial connection or fetching ClientDetails and Config tables.

  4. Workflows for consuming Charts and Real-time data

    main

    The library supports two primary workflows for market data:

    Charts Series Data

    1. Fetch charts: Retrieve chart data directly using your user_token.
    2. Convert: Transform the retrieved data into a pandas DataFrame.

    Real-time Data Streams

    1. Connect: Establish a connection using your user_token.
    2. Subscribe: Subscribe to specific metrics.
    3. Fetch: Retrieve the metrics from the stream.
    4. Convert: Transform the metrics into a pandas DataFrame.
  5. Handle TradingAPI TimeoutError

    main

    The TradingAPI session can time out. It is strongly recommended to catch TimeoutError on every function call to the TradingAPI. When a TimeoutError occurs, you should call trading_api.connect() to establish a new session and then retry the original operation.

    While you can attempt to prevent timeouts by making periodic calls (e.g., every 10 minutes using get_update()), explicit exception handling is the most robust method.

    try:
        checking_response = trading_api.check_order(order=order)
    except TimeoutError:
        logging.warning("TradingAPI session did timeout, reconnecting for new session ID...")
        trading_api.connect()
        checking_response = trading_api.check_order(order=order)
  6. Configure Two-Factor Authentication (2FA) for Trading

    main

    If 2FA is enabled on your Degiro account, you have three ways to authenticate:

    1. Using totp_secret_key (Recommended): Provide the 32-character setup key from Degiro. The library will automatically generate the required one_time_password for every connection.
    2. Using one_time_password: Manually provide the 6-digit code generated by your authenticator app (e.g., Google Authenticator). This code is only valid for 30 seconds.
    3. Using in_app_token: Use the 'In App' validation method by providing the token provided by Degiro during a successful username/password login, allowing approval via the mobile app.
    # SOLUTION 1: Using totp_secret_key (Automated)
    credentials = Credentials(
        username=YOUR_USERNAME,
        password=YOUR_PASSWORD,
        int_account=YOUR_INT_ACCOUNT,
        totp_secret_key=YOUR_2FA_SECRET_KEY,
    )
    trading_api = API(credentials=credentials)
    trading_api.connect()
    
    # SOLUTION 2: Using one_time_password (Manual)
    credentials = Credentials(
        username=YOUR_USERNAME,
        password=YOUR_PASSWORD,
        int_account=YOUR_INT_ACCOUNT,
        one_time_password=YOUR_2FA_OTP,
    )
    trading_api = API(credentials=credentials)
    trading_api.connect()
  7. How to find your `user_token`

    main

    The user_token is required for many operations, including fetching charts and connecting to real-time streams. You can locate it by retrieving one of the following tables:

    • Config table: Look for the clientId attribute.
    • ClientDetails table: Look for the id attribute.
  8. Login to the Trading API

    main

    To use the trading.api module, you must establish a connection using Credentials and the API.connect() method. You will need your Degiro username, password, and optionally your int_account.

    from degiro_connector.trading.api import API, Credentials
    
    credentials = Credentials(
        username = YOUR_USERNAME,
        password = YOUR_PASSWORD,
        int_account = YOUR_INT_ACCOUNT,  # OPTIONAL FOR LOGIN
    )
    
    # SETUP TRADING API
    trading_api = API(credentials=credentials)
    
    # ESTABLISH CONNECTION
    trading_api.connect()
  9. Create an Order using check_order() and confirm_order()

    main

    Order creation is a two-step process to ensure validity before execution:

    1. Check Order: Call trading_api.check_order(order=order). This returns a dict containing a confirmation_id if successful, or None if it fails. The response also includes transaction_fees and free_space_new.
    2. Confirm Order: Call trading_api.confirm_order(confirmation_id=..., order=order). This uses the confirmation_id from the first step. On success, it returns a dict containing the order_id (required for future updates/deletions) and response_datetime.
    order = Order(
        buy_sell=Action.BUY,
        order_type=OrderType.LIMIT,
        price=12.1,
        product_id=72160,
        size=1,
        time_type=TimeType.GOOD_TILL_DAY,
    )
    checking_response = trading_api.check_order(order=order)
    confirmation_response = trading_api.confirm_order(
        confirmation_id=checking_response.confirmation_id,
        order=order,
    )
  10. Install the degiro-connector library

    main

    Install the library using pip. It is recommended to install the qrcode and quotecast extras to enable real-time data and QR code functionality.

    To upgrade to the latest version, use the --no-cache-dir flag to ensure you aren't using a cached version.

    To remove the library, use pip uninstall.

    # INSTALL
    pip install degiro-connector[qrcode,quotecast]
    
    # UPGRADE
    pip install --no-cache-dir --upgrade degiro-connector[qrcode,quotecast]
    
    # UNINSTALL
    pip uninstall degiro-connector
  11. Manage authenticated sessions with ModelSession

    main

    The ModelSession class provides a thread-safe way to manage requests.Session objects. It uses threading.local() to ensure that session data is isolated within individual threads, making it suitable for multi-threaded applications.

    When you access the session property, the class automatically builds and stores a session if one does not already exist for the current thread. You can also manually reset or replace the session using reset_session or the session setter.

    from degiro_connector.core.models.model_session import ModelSession
    import requests
    
    # Initialize the session manager with optional custom headers or hooks
    manager = ModelSession(headers={'User-Agent': 'my-app'}, hooks=None)
    
    # Access the thread-local requests.Session object
    # This will automatically call build_session if it's the first access in this thread
    current_session = manager.session
    
    # Use the session as you would with standard requests
    response = current_session.get('https://api.example.com')
    
    # Reset the session with new configuration
    manager.reset_session(headers={'New-Header': 'value'})
  12. Configure ChartRequest overrides

    main

    When creating a ChartRequest, you can use the override dictionary to force specific API parameters. This is useful if you want to bypass the default period or resolution logic.

    Example override keys:

    • resolution: e.g., "P1D" (1 Day)
    • period: e.g., "P1W" (1 Week)
    chart_request = ChartRequest(
        period = Interval.P1D,
        resolution = Interval.PT1H,
        series=["price:issueid:360148977"],
        override={
            "resolution": "P1D",
            "period": "P1W",
        }
    )