### Setup & Configuration Reference Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/README.md Complete guide to setting up both APIs, including credentials management, 2FA configuration, connection timeouts, and logger configuration. ```APIDOC ## Setup & Configuration Reference ### Description Provides a complete guide to setting up both the Trading and Quotecast APIs, covering credentials management, 2FA configuration, connection timeouts, and logger integration. ### Key Topics & Methods: - Credentials model and loading methods (JSON files, environment variables, direct instantiation) - `build_credentials()` — Load from file/environment - 2FA configuration (TOTP, OTP, in-app token) with `totp_secret_key` - `ModelConnection(timeout=X)` — Configure timeouts - Logger configuration and custom logging integration - Session management - Credentials validation and security - Production setup examples ### For: First-time setup, credentials management, timeout configuration, logging integration. ``` -------------------------------- ### Install Degiro Connector Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/INDEX.md Install the Degiro connector with optional dependencies for QR code and quote casting. Ensure you have pip installed. ```bash pip install degiro-connector[qrcode,quotecast] ``` -------------------------------- ### Degiro Trading API Example Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/INDEX.md Example of how to initialize and use the Degiro Trading API. This includes connecting, fetching account configuration, and logging out. Requires valid credentials. ```python from degiro_connector.trading.api import API from degiro_connector.trading.models.credentials import Credentials # Create credentials credentials = Credentials( username="your_username", password="your_password", int_account=12345678, ) # Initialize API api = API(credentials=credentials) # Connect api.connect() # Get account info config = api.get_config() print(f"User token: {config['clientId']}") # Logout api.logout() ``` -------------------------------- ### Example Degiro Configuration Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/INDEX.md An example JSON configuration file for the Degiro connector. Include your username, password, account ID, and TOTP secret key. ```json { "username": "your_username", "password": "your_password", "int_account": 12345678, "totp_secret_key": "JBSWY3DPEBLW64TMMQ..." } ``` -------------------------------- ### Manage Notes with Degiro API Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Examples for getting, creating, editing, and deleting notes associated with a product. Ensure you have a valid API instance. ```python # Get notes = api.get_notes(product_id=72160) # Create note = api.create_note( note=NoteAddRequest(product_id=72160, text="Good stock") ) # Edit api.edit_note( note=NoteEditRequest(note_id=note.id, text="Updated note") ) # Delete api.delete_note(id=note.id) ``` -------------------------------- ### Example Test for Trading Action Source: https://github.com/chavithra/degiro-connector/blob/main/tests/README.md Demonstrates how to write a test for a trading action, including setting up the test environment, executing the action, and asserting the expected outcome. This example uses pytest markers for trading and network. ```python import pytest @pytest.mark.trading @pytest.mark.network def test_my_action(trading_connected): # SETUP some_request = "MY-REQUEST" # EXECUTE response = trading.my_action(some_request=some_request) # CHECK assert response is True ``` -------------------------------- ### Degiro Quotecast API Example Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/INDEX.md Example of how to initialize and use the Degiro Quotecast API to fetch chart data. Requires a user token and specific chart request parameters. ```python from degiro_connector.quotecast.api import API from degiro_connector.quotecast.models.chart import ChartRequest, Interval # Initialize API api = API(user_token=your_user_token) # Fetch chart chart = api.get_chart( chart_request=ChartRequest( requestid="1", resolution=Interval.PT60M, culture="en-US", period=Interval.P1D, series=["price:issueid:360148977"], tz="Europe/Paris", ), ) print(f"Chart series: {[s.id for s in chart.series]}") ``` -------------------------------- ### Get Account Configuration Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves the configuration table which includes session, client, and service URLs. Use this to get your clientId and sessionId. ```python config = api.get_config() user_token = config['clientId'] session_id = config['sessionId'] ``` -------------------------------- ### Retrieve Account Info Table Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Use this to get the AccountInfo table which contains currency details. No specific setup is required beyond having the trading_api object initialized. ```python account_info_table = trading_api.get_account_info() ``` -------------------------------- ### Product Search Examples Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Illustrates different ways to search for products, including text search, stocks with filters, bonds, and ETFs. ```APIDOC ## Product Search Examples ```python # Text search LookupRequest(search_text="APPLE", limit=10) # Stocks with filters StocksRequest( index_id=122001, # NASDAQ 100 is_in_us_green_list=True, search_text="", limit=100, ) # Bonds BondsRequest(bond_exchange_id=710, limit=100) # ETFs ETFsRequest(popular_only=False, limit=100) ``` ``` -------------------------------- ### Complete Real-Time Workflow Example Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/quotecast-api.md This snippet demonstrates a full workflow for fetching real-time ticker data. It includes obtaining a session, subscribing to specific tickers, and then fetching and processing the data in a loop. Ensure you have the necessary user token to obtain a session ID. ```python from degiro_connector.quotecast.tools.ticker_fetcher import TickerFetcher from degiro_connector.quotecast.tools.ticker_to_df import TickerToDF from degiro_connector.quotecast.models.ticker import TickerRequest import time # Step 1: Get session session_id = TickerFetcher.get_session_id(user_token=user_token) logger = TickerFetcher.build_logger() session = TickerFetcher.build_session() # Step 2: Subscribe ticker_request = TickerRequest( request_type="subscription", request_map={ "360015751": ["LastPrice", "LastVolume"], "AAPL.BATS,E": ["LastPrice", "LastVolume"], }, ) TickerFetcher.subscribe( ticker_request=ticker_request, session_id=session_id, session=session, ) # Step 3: Fetch in a loop converter = TickerToDF() for _ in range(10): # Fetch 10 times ticker = TickerFetcher.fetch_ticker( session_id=session_id, session=session, ) if ticker: df = converter.parse(ticker=ticker) print(df) time.sleep(1) ``` -------------------------------- ### Get Top News Preview Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Fetches a preview of the top news articles. Set raw=True for raw data. ```python # FETCH DATA top_news_preview = trading_api.get_top_news_preview(raw=True) ``` -------------------------------- ### Get Notes Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves all notes for a specific product. Supports returning raw JSON. ```APIDOC ## get_notes(product_id: int, raw: bool = False) ### Description Retrieves all notes for a product. ### Parameters #### Query Parameters - **product_id** (int) - Required - Product ID - **raw** (bool) - Optional - If True, return raw JSON ### Returns Dictionary with notes list ``` -------------------------------- ### Python Production Setup for Degiro API Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/configuration.md This snippet demonstrates how to set up and connect to the Degiro API in a production environment. It includes configuring logging, loading credentials from environment variables, and initializing the API with a specified session timeout. Ensure environment variables for credentials are set securely. ```python import os import logging from degiro_connector.trading.api import API from degiro_connector.trading.models.credentials import build_credentials from degiro_connector.core.models.model_connection import ModelConnection # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename='/var/log/degiro_trading.log', ) # Load credentials from environment credentials = build_credentials() # Initialize API with production settings api = API( credentials=credentials, connection_storage=ModelConnection(timeout=1800), logger=logging.getLogger(__name__), preload=True, ) # Connect try: api.connect() print("Connected successfully") except Exception as e: logging.error(f"Failed to connect: {e}") raise ``` -------------------------------- ### Get Company Ratios Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Retrieves financial ratios for a company. Requires the product ISIN. ```python # FETCH DATA company_ratios = trading_api.get_company_ratios( product_isin='FR0000131906', ) ``` -------------------------------- ### Get Financial Statements Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Fetches the financial statements for a company. Requires the product ISIN. ```python # FETCH DATA financials_statements = trading_api.get_financials_statements( product_isin='FR0000131906', ) ``` -------------------------------- ### Get Product Related Notes Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Retrieves notes associated with a specific product ID. Set raw=True to get raw data. ```python note_batch = trading_api.get_notes( product_id=1234567, raw=False, ) ``` -------------------------------- ### Check Required Order Fields Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/errors.md Before placing an order, verify that all fields required for a specific `OrderType` are provided. This example shows how to check fields for a LIMIT order. ```python from degiro_connector.trading.models.order import ORDER_FIELD_MAP # Check required fields required = ORDER_FIELD_MAP[OrderType.LIMIT] # {'buySell', 'orderType', 'price', 'productId', 'size', 'timeType'} ``` -------------------------------- ### Get Portfolio Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Retrieves a list of stocks and products currently held in the portfolio. Use `UpdateOption.PORTFOLIO` in the `request_list`. ```python account_update = trading_api.get_update( request_list=[ UpdateRequest( option=UpdateOption.PORTFOLIO, last_updated=0, ), ], raw=True, ) ``` -------------------------------- ### Get Estimates Summaries Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Retrieves a summary of financial estimates for a given product ISIN. Can specify raw output. ```python estimates_summaries = trading_api.get_estimates_summaries( product_isin="FR0000131906", raw=False, ) ``` -------------------------------- ### Connection Management with Custom Timeout Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/INDEX.md Configure connection parameters, such as timeout, using ModelConnection. This example sets a custom timeout of 10 minutes. ```python from degiro_connector.core.models.model_connection import ModelConnection # Custom timeout api = API( credentials=credentials, connection_storage=ModelConnection(timeout=600), # 10 min ) ``` -------------------------------- ### Search for Financial Products Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Examples of creating search requests for different financial product types, including text search, stocks with filters, bonds, and ETFs. Specify search criteria and limits. ```python # Text search LookupRequest(search_text="APPLE", limit=10) ``` ```python # Stocks with filters StocksRequest( index_id=122001, # NASDAQ 100 is_in_us_green_list=True, search_text="", limit=100, ) ``` ```python # Bonds BondsRequest(bond_exchange_id=710, limit=100) ``` ```python # ETFs ETFsRequest(popular_only=False, limit=100) ``` -------------------------------- ### Get Favorite Products Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Fetch a batch of the user's favorite products. This is a simple API call with no parameters. ```python favorites_batch = trading_api.get_favorite() ``` -------------------------------- ### Get Company Profile Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Fetches the profile information for a specific company using its ISIN. ```python # FETCH DATA company_profile = trading_api.get_company_profile( product_isin='FR0000131906', ) ``` -------------------------------- ### Favorites Management Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Provides examples for managing favorite lists, including listing, creating, adding/removing products, reordering, renaming, and deleting favorites. ```APIDOC ## Favorites Management ```python # List favorites = api.get_favorite() # Create fav_id = api.create_favorite(name="My List") # Add product api.put_favorite_product(id=fav_id, product_id=72160) # Remove product api.delete_favorite_product(id=fav_id, product_id=72160) # Reorder api.move_favorite(list_id=fav_id, position=0) # Rename api.rename_favorite(id=fav_id, name="New Name") # Delete api.delete_favorite(id=fav_id) ``` ``` -------------------------------- ### Get Product Information by IDs Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Retrieve detailed information for specific products using their IDs. Supports fetching raw or processed data. ```python product_info = trading_api.get_products_info( product_list=[96008, 1153605, 5462588], raw=False, ) ``` -------------------------------- ### Degiro Trading API - Common Methods Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Setup and use of the Degiro Trading API for managing credentials, connecting, fetching account information, executing and managing orders, retrieving portfolio updates and history, and searching for products. Remember to log out after use. ```python from degiro_connector.trading.api import API from degiro_connector.trading.models.credentials import Credentials # Setup creds = Credentials(username="user", password="pass", int_account=12345) api = API(credentials=creds) api.connect() # Account Info config = api.get_config() details = api.get_client_details() # Orders check = api.check_order(order=order) confirm = api.confirm_order(confirmation_id=check.confirmation_id, order=order) update = api.update_order(order=order) delete = api.delete_order(order_id=order.id) # Portfolio updates = api.get_update(request_list=[UpdateRequest(...)]) history = api.get_orders_history(history_request=HistoryRequest(...)) # Products results = api.product_search(product_request=LookupRequest(...)) config = api.get_products_config() api.logout() ``` -------------------------------- ### Get Products Config Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves configuration data used for product filtering, including available countries, exchanges, product types, and indices. ```APIDOC ## get_products_config ### Description Retrieves configuration data for product filtering. ### Method `get_products_config() -> dict` ### Returns Dictionary with lists of: - `countries`, `exchanges`: Available exchanges and countries - `productTypes`: Available product type filters - `indices`: Available indices - Sort columns for different product types ### Request Example ```python config = api.get_products_config() nasdaq_id = config['indices'][0]['id'] # Find NASDAQ ``` ``` -------------------------------- ### Get Latest News Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Retrieves the latest news articles. Allows filtering by offset, languages, and limit. ```python # SETUP REQUEST request = LatestNews.Request( offset=0, languages='en,fr', limit=20, ) # FETCH DATA latest_news = trading_api.get_latest_news( request=request, raw=True, ) ``` -------------------------------- ### Get Products Info Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves detailed information for a list of products specified by their IDs. The `raw` parameter can be set to True to return the raw JSON response. ```APIDOC ## get_products_info ### Description Retrieves product information by product IDs. ### Method `get_products_info(product_list: list[int], raw: bool = False) -> dict | None` ### Parameters #### Request Body - **product_list** (list[int]) - Required - List of product IDs to fetch - **raw** (bool) - Optional - If True, return raw JSON ### Returns Dictionary with product information including name, ISIN, vwd_id, and other properties ### Request Example ```python products = api.get_products_info( product_list=[96008, 1153605, 5462588], ) ``` ``` -------------------------------- ### Get News By Company Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Retrieves news articles filtered by company ISIN. Supports pagination and language filtering. ```python # SETUP REQUEST request = NewsByCompany.Request( isin='NL0000235190', limit=10, offset=0, languages='en,fr', ) # FETCH DATA news_by_company = trading_api.get_news_by_company( request=request, raw=True, ) ``` -------------------------------- ### Get Total Portfolio Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Fetches aggregated data about the entire portfolio, including cash balances and valuation. Specify `UpdateOption.TOTALPORTFOLIO` in the `request_list`. ```python account_update = trading_api.get_update( request_list=[ UpdateRequest( option=UpdateOption.TOTALPORTFOLIO, last_updated=0, ), ], raw=True, ) ``` -------------------------------- ### Get Futures/Options Underlyings Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Use this snippet to retrieve a list of futures or options underlyings. You can specify future or option exchange IDs. ```python underlying_list = trading_api.get_underlyings( underlyings_request= UnderlyingsRequest( future_exchange_id=1, # option_exchange_id=3, ), raw=False, ) ``` -------------------------------- ### Initialize Trading API with Full Configuration Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/configuration.md Shows how to initialize the Trading API with comprehensive configuration, including loading credentials from a file, setting up a logger, defining connection timeouts, and enabling preloading of action classes. ```python from degiro_connector.trading.api import API from degiro_connector.trading.models.credentials import Credentials, build_credentials from degiro_connector.core.models.model_connection import ModelConnection from degiro_connector.core.models.model_session import ModelSession import logging # Load credentials credentials = build_credentials(location="~/.degiro/credentials.json") # Create logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # Create connection config connection = ModelConnection(timeout=600) # 10 minutes # Create session config session_storage = ModelSession() # Initialize API api = API( credentials=credentials, connection_storage=connection, logger=logger, session_storage=session_storage, preload=True, # Load all action classes on init ) api.connect() ``` -------------------------------- ### Convert Polars DataFrame to Pandas DataFrame Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Converts a Polars DataFrame to a Pandas DataFrame. Requires Pandas and PyArrow to be installed. ```python # BUILD PANDAS.DATAFRAME # YOU NEED PANDAS AND PYARROW INSTALLED pandas_df = df.to_pandas() ``` -------------------------------- ### Get Account Updates (Orders, Portfolio) Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves account state updates for orders and portfolio. Specify the desired options and a timestamp for incremental updates. Set last_updated to 0 to fetch all data. ```python from degiro_connector.trading.models.account import UpdateRequest, UpdateOption updates = api.get_update( request_list=[ UpdateRequest( option=UpdateOption.ORDERS, last_updated=0, ), UpdateRequest( option=UpdateOption.PORTFOLIO, last_updated=0, ), ], ) ``` -------------------------------- ### Fetch News and Events with Degiro API Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Examples for retrieving the latest news, news filtered by company ISIN, and upcoming events from the calendar. Specify language and date ranges as needed. ```python # Latest news news = api.get_latest_news( request=LatestNews.Request(offset=0, limit=20, languages='en,fr') ) # By company news = api.get_news_by_company( request=NewsByCompany.Request(isin='NL0000235190', limit=10) ) # Events calendar agenda = api.get_agenda( agenda_request=AgendaRequest( calendar_type=CalendarType.EARNINGS_CALENDAR, start_date=datetime.now(), limit=25, ) ) ``` -------------------------------- ### Get Agenda Data Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Fetches agenda items such as earnings, dividends, or economic events. Requires an AgendaRequest object with specified dates and types. ```python agenda = trading_api.get_agenda( agenda_request=AgendaRequest( calendar_type=CalendarType.EARNINGS_CALENDAR, end_date=datetime.now(), start_date=datetime.now() - timedelta(days=1), offset=0, limit=25, ), raw=True, ) ``` -------------------------------- ### Get Product Filtering Configuration Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieve configuration data used for filtering products, including available countries, exchanges, product types, and indices. This data can be used to dynamically set filter parameters. ```python config = api.get_products_config() nasdaq_id = config['indices'][0]['id'] # Find NASDAQ ``` -------------------------------- ### Get Company Profile Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves company profile information using its ISIN code. Set `raw` to True to get the raw JSON response. ```python profile = api.get_company_profile(product_isin='NL0000235190') ``` -------------------------------- ### Initialize Quotecast API with Full Configuration Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/configuration.md Illustrates the full configuration for initializing the Quotecast API, including setting a user token, defining connection timeouts, and configuring a logger. Preloading is also enabled. ```python from degiro_connector.quotecast.api import API from degiro_connector.core.models.model_connection import ModelConnection import logging logger = logging.getLogger(__name__) api = API( user_token=12345678, connection_storage=ModelConnection(timeout=15), logger=logger, preload=True, ) ``` -------------------------------- ### Get Account Overview Data Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Retrieve the AccountOverview, which is a list of cash movements. Requires an OverviewRequest object specifying date range. Set raw=False for processed data. ```python account_overview = trading_api.get_account_overview( overview_request=OverviewRequest( from_date=date(year=date.today().year-1, month=1, day=1), to_date=date.today(), ), raw=False, ) ``` -------------------------------- ### Degiro Quotecast API - Real-Time Data Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Setup and usage of the Quotecast API for subscribing to real-time market data and fetching it. This includes obtaining a session ID, building a session, subscribing to specific tickers and data points, fetching the data, and converting it into a pandas DataFrame. ```python from degiro_connector.quotecast.tools.ticker_fetcher import TickerFetcher from degiro_connector.quotecast.tools.ticker_to_df import TickerToDF from degiro_connector.quotecast.models.ticker import TickerRequest # Setup session session_id = TickerFetcher.get_session_id(user_token=token) session = TickerFetcher.build_session() # Subscribe request = TickerRequest( request_type="subscription", request_map={"360015751": ["LastPrice", "LastVolume"]} ) TickerFetcher.subscribe(ticker_request=request, session_id=session_id) # Fetch data ticker = TickerFetcher.fetch_ticker(session_id=session_id) # Convert to DataFrame df = TickerToDF().parse(ticker=ticker) print(df) ``` -------------------------------- ### Initialize Degiro Trading API Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Instantiate the API with your trading credentials. Ensure you have imported the necessary classes. The `connect()` method must be called to establish a session. ```python from degiro_connector.trading.api import API from degiro_connector.trading.models.credentials import Credentials credentials = Credentials( username="your_username", password="your_password", int_account=12345678, ) api = API(credentials=credentials) api.connect() ``` -------------------------------- ### Create a New Note - Python Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md This snippet demonstrates how to create a new note for a product. Ensure you import `NoteAddRequest` and provide the `product_id` and `text` for the note. Set `raw=True` for raw JSON output. ```python from degiro_connector.trading.models.note import NoteAddRequest note = api.create_note( note=NoteAddRequest( product_id=1234567, text="Good long-term hold", ), ) ``` -------------------------------- ### Extracting TOTP Secret Key from QRCode Source: https://github.com/chavithra/degiro-connector/blob/main/README.md This script demonstrates how to extract the TOTP secret key from a QRCode by converting the image to text. Ensure you have a library capable of QR code scanning installed. ```python from degiro_connector.trading_api import TradingAPI from degiro_connector.utils.qrcode import qrcode_to_totp_secret # Assuming you have saved the QRCode as 'qrcode.png' with open('qrcode.png', 'rb') as f: totp_secret_key = qrcode_to_totp_secret(f.read()) print(f'Your TOTP Secret Key is: {totp_secret_key}') ``` -------------------------------- ### Get Latest News with Degiro Connector Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves the latest news across all companies. Specify offset, limit, and desired languages in the request object. The 'raw' parameter can be set to True to get the raw JSON response. ```python from degiro_connector.trading.models.news import LatestNews news = api.get_latest_news( request=LatestNews.Request( offset=0, limit=20, languages='en,fr', ), ) ``` -------------------------------- ### Handling TimeoutError in Trading Operations Source: https://github.com/chavithra/degiro-connector/blob/main/README.md This example shows how a TimeoutError might occur during trading operations if the connection has expired. It illustrates fetching a checking response which could fail if the connection is not reset frequently enough. ```python # FETCH CHECKING_RESPONSE checking_response = trading_api.check_order(order=order) ``` ```text TimeoutError: Connection has probably expired. ``` -------------------------------- ### Real-Time Price Streaming with Degiro Connector Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/tools-and-utilities.md Demonstrates how to set up a session, subscribe to real-time price and volume data for specific tickers, and continuously fetch and process updates. Use this for applications requiring live market data. Ensure you have a valid user token and network connectivity. ```python from degiro_connector.quotecast.tools.ticker_fetcher import TickerFetcher from degiro_connector.quotecast.tools.ticker_to_df import TickerToDF from degiro_connector.quotecast.models.ticker import TickerRequest import time # Setup session_id = TickerFetcher.get_session_id(user_token=12345678) logger = TickerFetcher.build_logger() session = TickerFetcher.build_session() converter = TickerToDF() # Subscribe ticker_request = TickerRequest( request_type="subscription", request_map={ "360015751": ["LastPrice", "LastVolume"], "AAPL.BATS,E": ["LastPrice", "LastVolume"], }, ) TickerFetcher.subscribe( ticker_request=ticker_request, session_id=session_id, session=session, logger=logger, ) # Poll for i in range(100): ticker = TickerFetcher.fetch_ticker( session_id=session_id, session=session, logger=logger, ) if ticker: df = converter.parse(ticker=ticker) print(f"\n=== Update {i+1} at {ticker.response_datetime} ===") print(df) # Your trading logic here time.sleep(1) ``` -------------------------------- ### Get Upcoming Payments Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves upcoming dividend and coupon payments. ```APIDOC ## get_upcoming_payments() -> dict | None ### Description Retrieves upcoming dividend and coupon payments. ### Parameters None ### Response #### Success Response (200) - **dict** - A dictionary containing upcoming payments. Each payment includes: - `product` (string) - Product name - `description` (string) - Payment description - `currency` (string) - Payment currency - `amount` (float) - Amount per share - `payDate` (string) - Payment date ### Response Example ```python payments = api.get_upcoming_payments() ``` ### Response Example ```json { "example": "Dictionary with upcoming payments" } ``` ``` -------------------------------- ### Connection Management Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to initialize the API with custom timeouts and implement an auto-reconnect pattern. ```APIDOC ## Connection Management ```python from degiro_connector.core.models.model_connection import ModelConnection # Custom timeout api = API( credentials=creds, connection_storage=ModelConnection(timeout=600), # 10 minutes ) # Auto-reconnect pattern try: result = api.some_method() except TimeoutError: api.connect() result = api.some_method() ``` ``` -------------------------------- ### API Constructor Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/quotecast-api.md Initializes the Quotecast API client with user credentials and optional configurations. ```APIDOC ## Constructor ```python API( user_token: int, connection_storage: ModelConnection | None = None, logger: logging.Logger | None = None, preload: bool = True, session_storage: ModelSession | None = None, ) ``` ### Parameters: - **user_token** (int) - Required - User identifier from Trading API Config.clientId - **connection_storage** (ModelConnection) - Optional - Connection timeout is 15 seconds for quotecast. Defaults to ModelConnection(timeout=15). - **logger** (logging.Logger) - Optional - Logger for API operations. Defaults to logging.getLogger(). - **preload** (bool) - Optional - Whether to preload all action classes on initialization. Defaults to True. - **session_storage** (ModelSession) - Optional - HTTP session storage. ### Returns: Quotecast API instance ### Example: ```python from degiro_connector.quotecast.api import API api = API(user_token=your_user_token) ``` ``` -------------------------------- ### Instantiate Credentials Directly Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/configuration.md Create a Credentials object by directly providing username, password, and internal account number. ```python from degiro_connector.trading.models.credentials import Credentials credentials = Credentials( username="your_username", password="your_password", int_account=12345678, ) ``` -------------------------------- ### Creating a List of Metric Objects in Python Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Shows how to construct a list of Metric objects, each representing a data point with product ID, metric type, and value. This is useful for parsing Degiro API responses. ```python metric_list = [ Metric( product_id=360114899, metric_type="LastDate", value="2020-11-06", ), Metric( product_id=360114899, metric_type="LastTime", value="17:36:17", ), Metric( product_id=360114899, metric_type="LastPrice", value=70.0, ), Metric( product_id=360114899, metric_type="LastVolume", value=100, ), Metric( product_id=360015751, metric_type="LastDate", value="2020-11-06", ), Metric( product_id=360015751, metric_type="LastTime", value="17:36:17", ), Metric( product_id=360015751, metric_type="LastPrice", value=22.99, ), Metric( product_id=360015751, metric_type="LastVolume", value=470, ), } ``` -------------------------------- ### Fetch Products Configuration Source: https://github.com/chavithra/degiro-connector/blob/main/README.md Retrieves product configuration data, which includes parameters for filtering various financial products. This data is useful for understanding available filtering options. ```python # FETCH DATA products_config = trading_api.get_products_config() ``` -------------------------------- ### Notes Management Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Operations for managing notes associated with products, including getting, creating, editing, and deleting notes. ```APIDOC ## Notes Management ### Get Notes Get existing notes for a product. ```python notes = api.get_notes(product_id=72160) ``` ### Create Note Create a new note for a product. ```python note = api.create_note( note=NoteAddRequest(product_id=72160, text="Good stock") ) ``` ### Edit Note Edit an existing note. ```python api.edit_note( note=NoteEditRequest(note_id=note.id, text="Updated note") ) ``` ### Delete Note Delete a note. ```python api.delete_note(id=note.id) ``` ``` -------------------------------- ### Authentication & Connection Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/INDEX.md Methods for initializing the API, establishing and ending sessions, and managing credentials. ```APIDOC ## API.__init__() ### Description Initialize API. ### Method `API.__init__()` ### Endpoint N/A (Initialization method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## API.connect() ### Description Establish API session. ### Method `API.connect()` ### Endpoint N/A (Session establishment method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## API.logout() ### Description End API session. ### Method `API.logout()` ### Endpoint N/A (Session termination method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## Credentials ### Description Represents authentication configuration. ### Method `Credentials` (Class/Type) ### Endpoint N/A (Data type definition) ### Parameters N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## build_credentials() ### Description Load authentication credentials. ### Method `build_credentials()` ### Endpoint N/A (Credential loading method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### ProductsConfig for Product Configuration Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/types.md Represents the configuration for products, typically returned by API.get_products_config(). It contains a dictionary of values. ```python class ProductsConfig(ProductInfo): values: dict ``` -------------------------------- ### Configure Credentials with TOTP Secret Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/errors.md When setting up credentials, use either `one_time_password` or `totp_secret_key`, but not both. The TOTP secret key is preferred. ```python credentials = Credentials( username="user", password="pass", totp_secret_key="JBSWY3DPEBLW64TMMQ...", ) ``` -------------------------------- ### API Constructor Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Initializes the Trading API with provided credentials and optional configuration for connection, logging, and session management. The `preload` parameter determines if all action classes are loaded upon initialization. ```APIDOC ## Constructor API ### Description Initializes the Trading API with provided credentials and optional configuration for connection, logging, and session management. The `preload` parameter determines if all action classes are loaded upon initialization. ### Parameters #### Parameters - **credentials** (Credentials) - Required - Trading account credentials (username, password, int_account, and optional 2FA) - **connection_storage** (ModelConnection) - Optional - Connection configuration including session timeout (1800s = 30 minutes). Defaults to ModelConnection(timeout=1800). - **logger** (logging.Logger) - Optional - Logger instance for API operations. Defaults to logging.getLogger(). - **preload** (bool) - Optional - Whether to preload all action classes on initialization. Defaults to True. - **session_storage** (ModelSession) - Optional - HTTP session management with hooks. Defaults to ModelSession. ### Returns API instance ### Example ```python from degiro_connector.trading.api import API from degiro_connector.trading.models.credentials import Credentials credentials = Credentials( username="your_username", password="your_password", int_account=12345678, ) api = API(credentials=credentials) api.connect() ``` ``` -------------------------------- ### Get Favorite Lists Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves all favorite product lists. Returns a dictionary containing favorite lists and their associated products. ```APIDOC ## get_favorite ### Description Retrieves all favorite product lists. ### Returns Dictionary with favorite lists and their products ### Example ```python favorites = api.get_favorite() ``` ``` -------------------------------- ### Get Orders History Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves all orders created between two specified dates. The `HistoryRequest` object defines the date range. ```APIDOC ## get_orders_history(history_request: HistoryRequest, raw: bool = False) -> History | dict | None ### Description Retrieves all orders created between two dates. The `HistoryRequest` object defines the date range. ### Parameters #### Path Parameters None #### Query Parameters - **raw** (bool) - Optional - If True, return raw JSON; if False, return History. #### Request Body - **history_request** (HistoryRequest) - Required - Object specifying the date range (`from_date`, `to_date`). ### Response #### Success Response (200) - **History** - An object containing a list of `HistoryItem` objects, each detailing an order. - **dict** - Raw JSON response if `raw` is True. ### Response Fields `HistoryItem` fields: - `orderId` (string) - Order identifier - `productId` (string) - Product traded - `created` (timestamp) - Creation timestamp - `last` (timestamp) - Last modification timestamp - `buysell` (string) - "B" (buy) or "S" (sell) - `price` (float) - Order price - `size` (integer) - Order quantity - `status` (string) - Order status (e.g., "CONFIRMED", "PENDING") - `type` (string) - Order type (e.g., "CREATE", "MODIFY", "DELETE") ### Request Example ```python from datetime import date from degiro_connector.trading.models.order import HistoryRequest history = api.get_orders_history( history_request=HistoryRequest( from_date=date(2024, 1, 1), to_date=date(2024, 12, 31), ), ) ``` ### Response Example ```json { "example": "History object or raw JSON" } ``` ``` -------------------------------- ### JSON Configuration File Format Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/configuration.md Create a JSON file containing your Degiro credentials. This file can then be used to build the credentials object. ```json { "username": "your_degiro_username", "password": "your_degiro_password", "int_account": 12345678, "totp_secret_key": "JBSWY3DPEBLW64TMMQ..." } ``` -------------------------------- ### connect() Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Establishes a trading session with Degiro's servers. This method must be called before invoking other API methods to ensure a valid session is active. ```APIDOC ## connect() ### Description Establishes a trading session with Degiro's servers. Must be called before using other API methods. ### Method connect ### Parameters None ### Returns `bool` - True if connection is successful. ### Raises TimeoutError if connection fails. ### Example ```python api.connect() ``` ``` -------------------------------- ### Retrieve Underlyings for Futures Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Use this snippet to get available underlyings for futures by specifying the `future_exchange_id`. Ensure you have imported `UnderlyingsRequest` from `degiro_connector.trading.models.product_search`. ```python from degiro_connector.trading.models.product_search import UnderlyingsRequest underlyings = api.get_underlyings( underlyings_request=UnderlyingsRequest( future_exchange_id=1, ), ) ``` -------------------------------- ### Initialize Quotecast API Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/quotecast-api.md Instantiate the Quotecast API with your user token. The user token is obtained from the Trading API's Config.clientId. Optional parameters allow customization of connection, logging, and session storage. ```python from degiro_connector.quotecast.api import API api = API(user_token=your_user_token) ``` -------------------------------- ### Get Transactions History Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves all executed transactions between two specified dates. The `TransactionsHistory.Request` object defines the date range and options. ```APIDOC ## get_transactions_history(request: TransactionsHistory.Request, raw: bool = False) -> dict | None ### Description Retrieves all executed transactions between two dates. The `TransactionsHistory.Request` object defines the date range and options. ### Parameters #### Path Parameters None #### Query Parameters - **raw** (bool) - Optional - If True, return raw JSON. #### Request Body - **request** (TransactionsHistory.Request) - Required - Object specifying the date range (`from_date`, `to_date`) and other options. ### Request Example ```python from degiro_connector.trading.models.transaction import TransactionsHistory history = api.get_transactions_history( request=TransactionsHistory.Request( from_date=TransactionsHistory.Request.Date(year=2024, month=1, day=1), to_date=TransactionsHistory.Request.Date(year=2024, month=12, day=31), ), ) ``` ### Response #### Success Response (200) - **dict** - A dictionary containing transaction history details, or raw JSON if `raw` is True. #### Response Example ```json { "example": "Dictionary with transaction history or raw JSON" } ``` ``` -------------------------------- ### API with Preload Enabled Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/configuration.md Initialize the API with preload enabled for immediate action class loading. This results in faster method calls but higher initial memory usage. ```python api = API(credentials=credentials, preload=True) # All actions are loaded immediately # Method calls are faster # Higher initial memory usage ``` -------------------------------- ### Quotecast (Real-Time Data) Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/INDEX.md Methods for initializing Quotecast, fetching real-time market data, and managing subscriptions. ```APIDOC ## API.__init__() (Quotecast) ### Description Initialize the Quotecast API client. ### Method `API.__init__()` ### Endpoint N/A (Initialization method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## get_chart() ### Description Retrieve historical chart data. ### Method `get_chart()` ### Endpoint N/A (Chart data retrieval method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## TickerFetcher.get_session_id() ### Description Obtain a session ID for real-time data access. ### Method `TickerFetcher.get_session_id()` ### Endpoint N/A (Session ID retrieval method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## TickerFetcher.subscribe() ### Description Subscribe to specific real-time metrics. ### Method `TickerFetcher.subscribe()` ### Endpoint N/A (Subscription method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## TickerFetcher.fetch_ticker() ### Description Get the latest real-time ticker data. ### Method `TickerFetcher.fetch_ticker()` ### Endpoint N/A (Ticker data fetch method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` ```APIDOC ## TickerFetcher.unsubscribe() ### Description Unsubscribe from real-time metrics. ### Method `TickerFetcher.unsubscribe()` ### Endpoint N/A (Unsubscription method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Create Note Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Creates a new note for a product. Requires note details including product ID and text. Supports returning raw JSON. ```APIDOC ## create_note(note: NoteAddRequest, raw: bool = False) ### Description Creates a note for a product. ### Parameters #### Request Body - **note** (NoteAddRequest) - Required - Note with product_id and text - **raw** (bool) - Optional - If True, return raw JSON ### Returns Created note object ``` -------------------------------- ### Establish QuoteCast Session Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/quotecast-api.md Establishes a session for real-time data access using a user token. Requires the user_token parameter. ```python from degiro_connector.quotecast.tools.ticker_fetcher import TickerFetcher session_id = TickerFetcher.get_session_id(user_token=your_user_token) ``` -------------------------------- ### Initialize TickerToMetricList Converter Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/tools-and-utilities.md Instantiate the TickerToMetricList converter. This tool is used to transform raw ticker data into a list of Metric objects. ```python ticker_to_metric_list = TickerToMetricList() ``` -------------------------------- ### Establish Trading Session Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Call the `connect()` method to establish a trading session with Degiro's servers. This must be done before invoking other API methods. ```python api.connect() ``` -------------------------------- ### Set Credentials via Environment Variable Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/QUICK_REFERENCE.md Set your DeGiro username and password using the DEGIRO_ACCOUNT environment variable in JSON format. ```bash # Set credentials via environment export DEGIRO_ACCOUNT='{"username":"user","password":"pass"}' ``` -------------------------------- ### Get Underlyings Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves available underlyings for futures and options. The `underlyings_request` parameter specifies the exchange ID, and the `raw` parameter controls the output format. ```APIDOC ## get_underlyings ### Description Retrieves available underlyings for futures and options. ### Method Signature `get_underlyings(underlyings_request: UnderlyingsRequest, raw: bool = False) -> dict | None` ### Parameters #### Parameters - **underlyings_request** (UnderlyingsRequest) - Required - Request with future_exchange_id or option_exchange_id - **raw** (bool) - Optional - If True, return raw JSON ### Example ```python from degiro_connector.trading.models.product_search import UnderlyingsRequest underlyings = api.get_underlyings( underlyings_request=UnderlyingsRequest( future_exchange_id=1, ), ) ``` ``` -------------------------------- ### Retrieve All Favorite Lists Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Call this function to get all your favorite product lists. The `raw` parameter can be set to True to receive the raw JSON response. ```python favorites = api.get_favorite() ``` -------------------------------- ### Build Credentials from Environment Variable Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/configuration.md Load credentials from the DEGIRO_ACCOUNT environment variable, which must contain a JSON string. ```python import os from degiro_connector.trading.models.credentials import build_credentials # Set environment variable os.environ["DEGIRO_ACCOUNT"] = '{"username": "user", "password": "pass"}' credentials = build_credentials() ``` ```bash export DEGIRO_ACCOUNT='{"username":"your_username","password":"your_password","int_account":12345678}' ``` -------------------------------- ### Get Account Updates Source: https://github.com/chavithra/degiro-connector/blob/main/_autodocs/trading-api.md Retrieves account state updates including orders, portfolio, and transactions. You can specify which data to fetch using `UpdateRequest` objects. ```APIDOC ## get_update(request_list: list[UpdateRequest], raw: bool = False) -> AccountUpdate | dict | None ### Description Retrieves account state updates including orders, portfolio, transactions. You can specify which data to fetch using `UpdateRequest` objects. ### Parameters #### Path Parameters None #### Query Parameters - **raw** (bool) - Optional - If True, return raw JSON; if False, return AccountUpdate. #### Request Body - **request_list** (list[UpdateRequest]) - Required - List of update requests specifying what data to fetch. Each `UpdateRequest` can specify an `option` (e.g., UpdateOption.ORDERS, UpdateOption.PORTFOLIO) and `last_updated` timestamp (0 to fetch all). ### Request Example ```python from degiro_connector.trading.models.account import UpdateRequest, UpdateOption updates = api.get_update( request_list=[ UpdateRequest( option=UpdateOption.ORDERS, last_updated=0, ), UpdateRequest( option=UpdateOption.PORTFOLIO, last_updated=0, ), ], ) ``` ### Response #### Success Response (200) - **AccountUpdate** - An object containing populated fields for the requested options. - **dict** - Raw JSON response if `raw` is True. #### Response Example ```json { "example": "AccountUpdate object or raw JSON" } ``` ```