Package: degiro-connector
1.Degiro ConnectorThis is yet another library to access Degiro's API.1.1. Contributing⭐️ Hopefully you have starred the project ⭐️You can contribute to the project in two ways:Code and documentation: pull requests are welcome !Feedback: feel free to open an issue or send me a message if you have a feedback or question.1.2. Which features ?Here are the features you can access through this library :EndpointFeature(s)AccountCashReportExport cash movements in a specific format : CSV, HTML, PDF or XLS.AccountInfoRetrieve a table containing : "clientId" and Currencies.AccountOverviewRetrieve all the cash movements between two dates.AgendaCrucial events regarding products : Dividend, Economic, Earnings, Holiday, IPO or Split.BondsETFsFundsFuturesLeveragedsLookupOptionsStocksWarrantsSearch list of products according their name, type and other criterias.For instance all the stocks from NASDAQ 100.ChartRetrieve chart data.ClientDetailsRetrieve a table containing : "clientId", "intAccount" and other account information.CompanyProfileRetrieve a company's profile using its ISIN code.CompanyRatiosRetrieve a company's ratios using its ISIN code.ConfigRetrieve a table containing : "clientId" and URLs which are constitutive of Degiro's API.EstimatesSummariesRetrieve a company's estimates summaries using its ISIN code.FavoritesAdd/Delete/Prioritize/Retrieve favorites lists.FavoritesProductsAdd/Update products associated with a favorite list.FinancialStatementsRetrieve a company's financial statements using its ISIN code.LatestNewsRetrieve latest news about all the companies.LoginQuotecastEstablish a connection for quotecast operations.LoginTradingEstablish a connection for trading operations.LogoutTradingDestroy previously established connection for trading operations.NewsByCompanyRetrieve news related to a specific company.OrderCreate, update, delete an Order.OrderHistoryRetrieve all Orders created between two dates.OrdersList pending Orders.PortfolioList products in your Portfolio.ProductsConfigRetrieve a table containing : useful parameters to filter products.ProductsInfoSearch for products using their ids.QuotecastsFetch real-time data on financial products.For instance the real-time stock Price.TopNewsPreviewRetrieve some news preview about all the companies.TotalPorfolioRetrieve aggregated information about your assets.TransactionsHistoryRetrieve all Transactions created between two dates.UnderlyingsList Underlyings for Futures and Options.1.3. How to install ?pipinstalldegiro-connector1.4. How to upgrade ?pipinstall--no-cache-dir--upgradedegiro-connector1.5. How to uninstall ?pipuninstalldegiro-connector1.6. Table of contents1.Degiro Connector1.1. Contributing1.2. Which features ?1.3. How to install ?1.4. How to upgrade ?1.5. How to uninstall ?1.6. Table of contents2. Real-time data2.1. What are the workflows ?2.2. How to find youruser_token?2.3. How to get a Chart ?2.4. How to format a chart.series ?2.5. How to find a productvwd_id?2.6. What are the credentials ?2.7. How to connect ?2.8. Is there a timeout ?2.9. How to subscribe to a data-stream ?2.10. How to unsubscribe to a data-stream ?2.11. How to fetch the data ?2.12. How to use this data ?2.13. Which are the available data types ?2.14. What is a Ticker ?2.15. What is inside the list[Metric] ?2.16. What is inside the DataFrame ?3. Trading connection3.1. How to login ?3.2. How to logout ?3.3. What are the credentials ?3.4. How to find your : int_account ?3.5. How to use 2FA ?3.6. How to find your : totp_secret_key ?3.7. How to find your : one_time_password ?3.8. Is there a timeout ?3.9. How to manage : TimeoutError ?4. Order4.1. How to create an Order ?4.1.1. Check Order4.1.2. Confirm Order4.2. How to update an Order ?4.3. How to delete an Order ?5. Portfolio5.1. How to retrieve pending Orders ?5.2. How to get the Portfolio ?5.3. How to get the TotalPortfolio ?5.4. How to retrieve the OrdersHistory ?5.5. How to retrieve the TransactionsHistory ?6. Account6.1. How to retrieve the table : Config ?6.2. How to retrieve the table : ClientDetails ?6.3. How to retrieve the table : AccountInfo ?6.4. How to get the table : AccountOverview ?6.5. How to export the table : AccountReport ?6.6. How to export the table : PositionReport ?7. Products7.1. How to get the table : ProductsConfig ?7.2. How to lookup products (search by name) ?7.3. How to search bonds ?7.4. How to search etfs ?7.5. How to search funds ?7.6. How to search futures ?7.7. How to search leverageds ?7.8. How to search options ?7.9. How to search stocks ?7.10. How to search warrants ?7.11. How to search products from ids ?7.12. How to get my favorite products ?7.13. How to create a favorite list ?7.14. How to delete a favorite list ?7.15. How to move a favorite list ?7.16. How to put favorite list products ?7.17. How to delete favorite list products ?7.18. How to get futures/options underlyings ?8. Companies8.1. How to get : CompanyProfile ?8.2. How to get : CompanyRatios ?8.3. How to get : FinancialStatements ?8.4. How to get : LatestNews ?8.5. How to get : TopNewsPreview ?8.6. How to get : NewsByCompany ?8.7. How to get : Agenda ?8.8. How to get : EstimatesSummaries ?9. Contributing10. License2. Real-time dataIt is possible to fetch the following data from Degiro's API:Charts series dataStreams of data in real-time2.1. What are the workflows ?CHARTSTo consume charts series :A. Fetch charts : directly with your "user_token".
B. Convert to a DataFrame.REAL-TIMETo consume real-time data-stream :A. Connect : with your "user_token".
B. Subscribe to metrics.
C. Fetch these metrics.
D. Convert to a DataFrame.All the details of these steps are explained in the rest of this section.2.2. How to find youruser_token?You can find your "user_token" inside one of these tables :"Config" : attribute "clientId""ClientDetails" : attribute "id"See sections related to"Config"and"ClientDetails"tables.2.3. How to get a Chart ?You can fetch an object containing the same data than in Degiro's website graph.For that you need to prepare a ChartRequest.Here is a table with the available attributes for ChartRequest.ParameterTypeDescriptionrequestidstrIt sends you back whatever string you put here, you can set it to : "1".resolutionChart.ResolutionResolution of the chart like : Chart.Resolution.PT1M.culturestrCountry code like : "en-US" or "fr-FR".periodChart.PeriodPeriod of the chart, like : Chart.Period.P1D.seriesrepeated stringData to get like : ['issueid:36014897', 'price:issueid:360148977'].tzstrTimezone like : "Europe/Paris"Example of code :chart_fetcher=ChartFetcher(user_token=user_token)chart_request=ChartRequest(culture="fr-FR",# override={#     "resolution": "P1D",#     "period": "P1W",# },period=Interval.P1D,requestid="1",resolution=Interval.PT60M,series=["issueid:360148977","price:issueid:360148977","ohlc:issueid:360148977","volume:issueid:360148977",# "vwdkey:AAPL.BATS,E",# "price:vwdkey:AAPL.BATS,E",# "ohlc:vwdkey:AAPL.BATS,E",# "volume:vwdkey:AAPL.BATS,E",],tz="Europe/Paris",)chart=chart_fetcher.get_chart(chart_request=chart_request,raw=False,)Theissueidparameter is thevwd_idof the product from which you want theChartdata.See the section related tovwd_idfor more information.All the models are described in this module :chart.pyFor a more comprehensive example :chart.py2.4. How to format a chart.series ?A Chart object contains a list of series.There is a SeriesFormatter to help you convertir a series into apolars.DataFrame.df=SeriesFormatter.format(series=chart.series)print(df)Here are the result for different series.id.issueid:360148977issueIdcompanyIdnameidentifier...windowPreviousClosePricewindowEndPricei64i64strstr...f64f643601489779245Créditissueid:3...12.858-0.00047price:issueid:360148977timestamppricedatetime[μs]f642023-12-29 09:00:0012.8582023-12-29 10:58:58.80012.85......2023-12-29 17:28:58.80012.832023-12-29 17:34:58.79999912.852volume:issueid:360148977timestampvolumedatetime[μs]f642023-12-29 09:58:58.80061627.02023-12-29 10:58:58.80083854.02023-12-29 11:58:58.80078240.02023-12-29 12:58:01.20069263.02023-12-29 13:58:58.80059040.02023-12-29 14:58:58.80062831.02023-12-29 15:58:01.20066681.02023-12-29 16:58:58.800529315.02023-12-29 17:34:58.7999991.317919e6ohlc:issueid:360148977timestampopenhighlowclosedatetime[μs]f64f64f64f642023-12-29 09:00:0012.85812.89812.85812.8722023-12-29 10:00:0012.87212.87612.8412.852023-12-29 11:00:0012.8512.86412.84212.8482023-12-29 12:00:0012.84412.88412.84412.872023-12-29 13:00:0012.86812.88612.8612.872023-12-29 14:00:0012.87212.90212.86812.8862023-12-29 15:00:0012.88412.89412.87412.8762023-12-29 16:00:0012.87612.88212.85412.8582023-12-29 17:00:0012.85612.85812.8312.852All the models are described in this module :chart.pyFor a more comprehensive example :chart_format.py2.5. How to find a productvwd_id?In operations related toQuotecast, Degiro uses thevwd_idto identify a product.Which means that if you want aChartorReal-time datafor a specific product : you first need to find this product'svwd_id.This two identifiers are not the same :IdentifierAPI name(s)DescriptionidstrId used identify a product inTradingrelated endpoints.vwd_idissueidvwdIdvwdIdSecondaryId used identify a product inQuotecast(ChartandReal-time data) related endpoint.Here are some methods you can use to fetch a product'svwd_id:product_searchget_products_infoThe methodproduct_searchlet you use the name or other attributes of a product to fetch it'svwd_id.The methodget_products_infolet you use a product'sidto fetch it'svwd_id.2.6. What are the credentials ?The only credential you need in order to fetch real-time data and charts is the :user_tokenBeware, these two identifiers are not the same thing :user_token : used to fetch real-time data and charts.int_account : used for some trading operations.2.7. How to connect ?In order to fetch data you need to establish a connection.You can use the following code to connect :session_id=TickerFetcher.get_session_id(user_token=YOUR_USER_TOKEN)2.8. Is there a timeout ?Connection timeout is around 15 seconds.Which means a connection will cease to work after this timeout.This timeout is reset each time you use this connection to :Subscribe to a metric (for instance a stock Price)Fetch the data-streamSo if you use it nonstop (in a loop) you won't need to reconnect.2.9. How to subscribe to a data-stream ?If one needs the following data from the "AAPL" stock :LastDateLastTimeLastPriceLastVolumeYou can use this library to retrieve updates like this :product_idLastPriceLastVolumeLastDatetimeUTCrequest_duration_sresponse_datetime_utcstrf64i64datetime[μs]f64datetime[μs]36001575134.612023-12-29 16:35:231.0213372024-01-01 17:31:22.482618AAPL.BATS,E192.55null2023-12-29 20:59:591.0213372024-01-01 17:31:22.482618To subscribe to a data-stream you need to setup a TickerRequest.A Request has the following parameters :ParameterTypeDescriptionrequest_typestrThe value "subscription" or "unsubscription".request_mapdictMap of products and metrics to subscribe/unsubscribe to.Here is an example of a request :ticker_request=TickerRequest(request_type="subscription",request_map={"360015751":['LastDate','LastTime','LastPrice','LastVolume','AskPrice','AskVolume','LowPrice','HighPrice','BidPrice','BidVolume'],"AAPL.BATS,E":['LastDate','LastTime','LastPrice','LastVolume','AskPrice','AskVolume','LowPrice','HighPrice','BidPrice','BidVolume'],},)In this example these are thevwd_idof the products from which you wantReal-time data:360015751AAPL.BATS,ESee thesectionrelated tovwd_idfor more information.Once you have built this Request object you can send it to Degiro's API like this :TickerFetcher.subscribe(ticker_request=ticker_request,session_id=session_id,)For more comprehensive examples :realtime_poller.py/realtime_one_shot.py2.10. How to unsubscribe to a data-stream ?To remove metrics from the data-stream you need to setup a TickerRequest.If you try to unsubscribe to a metric to which you didn't subscribed previously it will most likely have no impact.A Request has the following parameters :ParameterTypeDescriptionrequest_typestrThe value "subscription" or "unsubscription".request_mapdictMap of products and metrics to subscribe/unsubscribe to.Here is an example of a request :ticker_request=TickerRequest(request_type="unsubscription",request_map={"360015751":['LastDate','LastTime','LastPrice','LastVolume','AskPrice','AskVolume','LowPrice','HighPrice','BidPrice','BidVolume'],"AAPL.BATS,E":['LastDate','LastTime','LastPrice','LastVolume','AskPrice','AskVolume','LowPrice','HighPrice','BidPrice','BidVolume'],},)TickerFetcher.subscribe(ticker_request=ticker_request,session_id=session_id,)For more comprehensive examples :realtime_poller.py/realtime_one_shot.py2.11. How to fetch the data ?You can use the following code :session_id=TickerFetcher.get_session_id(user_token=user_token)logger=TickerFetcher.build_logger()session=TickerFetcher.build_session()ticker=TickerFetcher.fetch_ticker(session_id=session_id,session=session,logger=logger,)For a more comprehensive example :realtime_poller.py2.12. How to use this data ?Received data is aQuotecastobject with the following properties :ParameterTypeDescriptionjson_datadictDictionary representation of what Degiro's API has sent.metadataMetadataContaining the "response_datetime" and "request_duration".Here is how to access these properties :json_text=ticker.json_textresponse_datetime=ticker.response_datetimerequest_duration=ticker.request_durationNotes:The API sometimes might return an empty Quotecast message.The API often returns a subset of the requested metrics, e.g. only'LastPrice'. This should be considered when appending consecutive data responses.2.13. Which are the available data types ?This library provides the tools to convert Degiro's JSON data into something more programmer-friendly.Here is the list of available data types :TypeDescriptionlist[Metric]List of Metric, which is a Pydantic BaseModel.polars.DataFrameDataFrame from the library Polars.There are integrated method to turnpolars.DataFrameinto Pythondict/listorpandas.DataFrame.Here is how to build each type :# BUILD `LIST[METRIC]`ticker_to_metric_list=TickerToMetricList()metric_list=ticker_to_metric_list.parse(ticker=ticker)# BUILD `POLARS.DATAFRAME`ticker_to_df=TickerToDF()polars_df=ticker_to_df.parse(ticker=ticker)# BUILD `LIST[DICT]`python_list=polars_df.to_dicts()# BUILD PANDAS.DATAFRAME# YOU NEED PANDAS AND PYARROW INSTALLEDpandas_df=df.to_pandas()2.14. What is a Ticker ?The generated Ticker contains :ParameterTypeDescriptionjson_textstrThe json message receivedresponse_datetimedatetimeDatetime of the response.request_durationtimedeltaDuration of the request.A Ticker is Pydantic BaseModel, it can serialize and deserialize into json.Here is how to manipulate a Ticker object :# GET TICKER PARAMETERSjson_text=ticker.json_textresponse_datetime=ticker.response_datetimerequest_duration=ticker.request_duration# SERIALIZE/DESERIALIZEticker_json=Ticker.model_dump_json()ticker_json=Ticker.model_validate_json(json_data=ticker_json)2.15. What is inside thelist[Metric]?Thelist[Metric]is the parsed version of thejsonmessage received from Degiro's API.A Metric contains the following parameters :ParameterTypeDescriptionmetric_typeMetricTypestrproduct_idstrThe product identifier in the Quotecast API.valuestrfloatExample -list[Metric]: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,),}2.16. What is inside the DataFrame ?In addition to whatever metrics you have chosen to subscribe to (see the example insection 2.6), the DataFrame will contain the following columns :ColumnDescriptionproduct_idProduct identifier, for instance "AAPL.BATS,E" for APPLE stock.response_datetimeDatetime at which the data was received.request_durationDuration of the request used to fetch the data.Example - DataFrame :product_idLastPriceLastVolumeLastDatetimeUTCrequest_duration_sresponse_datetime_utcstrf64i64datetime[μs]f64datetime[μs]36001575134.612023-12-29 16:35:231.0213372024-01-01 17:31:22.482618AAPL.BATS,E192.55null2023-12-29 20:59:591.0213372024-01-01 17:31:22.4826183. Trading connectionThis library is divided into two modules :quotecast : to consume real-time financial data.trading : to manage your Degiro's account.The modulequotecastis described in the section related to real-time data.The rest of this document will only refer to the module :trading.3.1. How to login ?In order to use the moduletrading.apiyou need to establish a connection.Check the section related toint_accountto understand how to get yours.Here is how to connect :credentials=Credentials(username=YOUR_USERNAME,password=YOUR_PASSWORD,int_account=YOUR_INT_ACCOUNT,# OPTIONAL FOR LOGIN)# SETUP TRADING APItrading_api=API(credentials=credentials)# ESTABLISH CONNECTIONtrading_api.connect()For a more comprehensive example :connection.py3.2. How to logout ?Once you no longer need to use the API you can destroy your connection.You can use the following code to disconnect :# DESTROY CONNECTIONtrading_api.logout()For a more comprehensive example :logout.py3.3. What are the credentials ?Some credentials are required to use Degiro's trading API.Here are these credentials :ParameterTypeDescriptionusernamestrUsername used to log into Degiro's website.passwordstrPassword used to log into Degiro's website.int_accountintOPTIONAL : unique identifier of the account : used by Degiro's server.totp_secret_keystrOPTIONAL : used for Two-factor Authentication (2FA).one_time_passwordstrOPTIONAL : used for Two-factor Authentication (2FA).Check the section related toint_accountto understand how to get yours.Check the section related to2FAif you want to know more about these two parameters :totp_secret_keyone_time_password3.4. How to find your : int_account ?To get yourint_acccountyou can run this example :client_details_table.pySee section related toClientDetailstable for more details.Thisint_acccountis required to do most of the trading operations available in this connector.Here are some operations for which yourint_acccountis not required :ConnectionFetch table : ClientDetailsFetch table : ConfigBeware, these two identifiers are not the same thing :user_token : used to fetch real-time data and charts.int_account : used for some trading operations.3.5. How to use 2FA ?First I will briefly explain what is :Two-Factor Authentication (2FA).I recommend to skip a few paragraphs if you already know what is2FA.In a standard connection you are providing two parameters:usernamepasswordIf you useTwo-Factor Authentication (2FA)you need an extra parameter:one_time_passwordThisone_time_passwordhas a validity of 30 secondes and is generated using atotp_secret_keycode.Usually you use an app like‎Google Authenticatorto store thistotp_secret_keyand generate theone_time_password.Thetotp_secret_keyis stored inside the QRCode which is displayed when you enable 2FA on Degiro's websiteTo use2FAwith this library you have two solutions.SOLUTION 1Provide yourtotp_secret_key: the library will use it to generate a newone_time_passwordat each connection.So you won't have to type yourone_time_passwordmanually at each connection.This is the proper way.See the section abouttotp_secret_keyto understand how to get yours.Here is an example of connection with thetotp_secret_key:credentials=Credentials(username=YOUR_USERNAME,password=YOUR_PASSWORD,int_account=YOUR_INT_ACCOUNT,# OPTIONAL FOR LOGINtotp_secret_key=YOUR_2FA_SECRET_KEY,# ONLY IF 2FA IS ENABLED)# SETUP TRADING APItrading_api=API(credentials=credentials)# ESTABLISH CONNECTIONtrading_api.connect()A complete example here :connection_2fa.pySOLUTION 2Provide a newone_time_passwordat each connection.Here is an example of connection with theone_time_password:credentials=Credentials(username=YOUR_USERNAME,password=YOUR_PASSWORD,int_account=YOUR_INT_ACCOUNT,# OPTIONAL FOR LOGINone_time_password=YOUR_2FA_OTP,# ONLY IF 2FA IS ENABLED)# SETUP TRADING APItrading_api=API(credentials=credentials)# ESTABLISH CONNECTIONtrading_api.connect()A complete example here :connection_otp.py3.6. How to find your : totp_secret_key ?The parametertotp_secret_keyis only required if you have enabled2FAon Degiro's website.When you try to activate2FAon Degiro's website, it displays aQRCode.ThisQRCodechanges at each activation.AQRCodeis a picture which can be converted into a text.You can download thisQRCodeand use a tool to extract the text from it.This extracted text will look like this :otpauth://totp/DEGIRO:YOUR_USERNAME?algorithm=SHA1&issuer=DEGIRO&secret=YOUR_TOPT_SECRET_KEY&digits=6&period=30Has you can guess the "totp_secret_key" is in this part :secret=YOUR_TOPT_SECRET_KEYHere is an example of script that extracts the text from aQRCode:qrcode.py3.7. How to find your : one_time_password ?The parameterone_time_passwordis the password you type when you log in the website using2FA.Usually you get it through an app likeGoogle Authenticator.It is preferable to use the parametertotp_secret_keyinstead ofone_time_password.3.8. Is there a timeout ?A connection for trading operations has a timeout of 30 minutes.
It'sdefinedin seconds as constanttimeouts.TRADING_TIMEOUT.The timeout period is started when theTradingAPI.connect()results successfully.Every time an operation is made to thisTradingAPIconnection, the timeout for this connection will be reset.If aTradingAPIconnection is left unused during the timeout period, the connection will expire.
Every consecutive function call to theTraderAPIwill then throw aTimeoutErrorexception.A connection timeout might occur when your trading strategy only performs a few trades per day, e.g. once per hour.
So when finally a buy opportuntiy occurs,check_order():# FETCH CHECKING_RESPONSEchecking_response=trading_api.check_order(order=order)Will fail withTimeoutError:TimeoutError: Connection has probably expired.3.9. How to manage : TimeoutError ?HANDLE EXCEPTIONIt's recommended to catch theTimeoutErroron every function call to theTradingAPI.When it's detected, it's sufficient to callconnect()again, followed by repeating the original call that threw the exception.
Example for thecheck_order()call:try:checking_response=trading_api.check_order(order=order)exceptTimeoutError:logging.warning("TradingAPI session did timeout, reconnecting for new session ID...")trading_api.connect()checking_response=trading_api.check_order(order=order)This shows the following in the log, while the order is checked successfully after a successful reconnect:WARNING-TradingAPIsessiondidtimeout,reconnectingfornewsessionID...INFO-get_session_id:response_dict:{'isPassCodeEnabled':False,'locale':'nl_NL','redirectUrl':'https://trader.degiro.nl/trader/','sessionId':'2BADBBEF3****','status':0,'statusText':'success'}INFO-confirmation_id:"053df7cf-****"response_datetime{seconds:1643801134nanos:715765000}REFRESH TIMEOUTAs mentioned before, the timeout will be reset after each call to theTradingAPI. This provides the opportunity to make a periodic function call, for example every 10 minutes toget_update().However, this might interfere with your other logic and might not be robust over time when DeGiro decides to decrease the timeout on their server.Therefor it's strongly recommended to always incorporate the exception handling forTimeoutErroras indicated in the example above.CHANGE PERIODIt's possible to change the timeout period while creating theTradingAPI. Just add aModelConnectionobject for parameterconnection_storage:# SETUP TRADING APItrading_api=TradingAPI(credentials=credentials,connection_storage=ModelConnection(timeout=600,))# Connect:trading_api.connect()The connection will now expire after 10 minutes (10 * 60 s).4. OrderCreating and updating of orders is done with anOrderobject. Here are the parameters:ParameterTypeDescriptionidstrOptional forupdate_order(). It's theorder_idof the createdOrderas returned byconfirm_order().actionOrder.ActionWhether you want to :BUYorSELL.order_typeOrder.OrderTypeType of order :LIMIT,STOP_LIMIT,MARKETorSTOP_LOSS.pricefloatLimit price of the order.Optional for the followingorder_type:LIMITandSTOPLIMIT.product_idintIdentifier of the product concerned by the order.sizefloatSize of the order.stop_pricefloatStop price of the order.Optional for the followingorder_type:STOPLIMITandSTOPLOSStime_typeOrder.TimeTypeDuration of the order :GOOD_TILL_DAYorGOOD_TILL_CANCELEDThe full description of anOrderis available here :order.py4.1. How to create an Order ?The order creation is done in two steps :Checking : send theOrderto the API to check if it is valid.Confirmation : confirm the creation of theOrder.Keeping these two steps (instead of reducing to one single "create" function) provides more options.4.1.1 Check orderUse thecheck_order()function of the Trading API:Request parametersParameterTypeDescriptionorderOrderThe order to create with all necessaryparameters.Response parametersOn a succesfull request, adictwith the following parameters is returned:ParameterTypeDescriptionconfirmation_idstrId necessary to confirm the creation of the Order by theconfirm_order()function.response_datetimedatetimeDatetime of the response.free_space_newfloatNew free space (balance) if the Order is confirmed.transaction_feesfloatTransaction fees that will be applied to the Order.show_ex_ante_report_linkbool?When the request fails,Noneis returned.4.1.2 Confirm orderUse theconfirm_order()function of the Trading API:Request parametersParameterTypeDescriptionconfirmation_idstrThe confirmtation id from thecheck_order()response.orderOrderThe same order from thecheck_order()request.Response parametersOn a succesfull request, adictwith the following parameters is returned:ParameterTypeDescriptionorder_idstrA unique id of the accepted order. This id is required toupdateordeletethe pending order.response_datetimedatetimeDatetime of the response.When the request fails,Noneis returned.4.1.3 Example of combining these functionsorder=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,)For a more comprehensive example :order.py4.2. How to update an Order ?To modify a specific Order, you need to set it up with theorder_idfrom theconfirm_order()response and use theupdate_order()function of the Trading API:Request parametersParameterTypeDescriptionorderOrderThe order to update with all necessaryparameters, includingidas returned byconfirm_order().Response parametersOn a succesfull request, aboolwith the valueTrueis returned.When the request fails,Noneis returned. A valid reason is that the pending order has been already executed on the exchange, and thisorder_idno longer exists.Here is an example:# ORDER SETUPorder=Order(id=YOUR_ORDER_ID,# `order_id` from `confirm_order()` responseaction=Order.Action.BUY,order_type=Order.OrderType.LIMIT,price=10.60,product_id=71981,size=1,time_type=Order.TimeType.GOOD_TILL_DAY,)# UPDATE ORDERsucccess=trading_api.update_order(order=order)4.3. How to delete an Order ?To delete a specific Order you just need theorder_idfrom theconfirm_order()response and use thedelete_order()function of the Trading API:Request parametersParameterTypeDescriptionorder_idstrThe unique id of the accepted order as returned byconfirm_order().Response parametersOn a succesfull request, aboolwith the valueTrueis returned.When the request fails,Noneis returned. A valid reason is that the pending order has been already executed on the exchange, and thisorder_idno longer exists.Here is an example:# DELETE ORDERsucccess=trading_api.delete_order(order_id=YOUR_ORDER_ID)# `order_id` from `confirm_order()` response5. Portfolio5.1. How to retrieve pending Orders ?This is how to get the list of Orders currently created but not yet executed or deleted :account_update=trading_api.get_update(request_list=[UpdateRequest(option=UpdateOption.ORDERS,last_updated=0,),],raw=True,)Example : Ordersproduct_id      time_type  price  size                                    id  ...  action  order_type stop_price retained_order  sent_to_exchange
0           0  GOOD_TILL_DAY      2     3  202cb962-ac59-075b-964b-07152d234b70  ...     BUY       LIMIT         16             17                18For a more comprehensive example :update.py5.2. How to get the Portfolio ?This is how to list the stocks/products currently in the portfolio :account_update=trading_api.get_update(request_list=[UpdateRequest(option=UpdateOption.PORTFOLIO,last_updated=0,),],raw=True,)For a more comprehensive example :update.pyNote: In order to resolve product IDs to Human readable names, see7.12. How to search products from ids ?5.3. How to get the TotalPortfolio ?This is how to get aggregated data about the portfolio :account_update=trading_api.get_update(request_list=[UpdateRequest(option=UpdateOption.TOTALPORTFOLIO,last_updated=0,),],raw=True,)Example : DataFramedegiroCash  flatexCash  totalCash  totalDepositWithdrawal  todayDepositWithdrawal  ...  reportNetliq  reportOverallMargin  reportTotalLongVal  reportDeficit  marginCallStatus
0           0           1          2                       3                       4  ...            16                   17                  18             19    NO_MARGIN_CALLFor a more comprehensive example :update.py5.4. How to retrieve the OrdersHistory ?This method returns data about passed orders between two dates.The result contains a list of "Orders" objects with the following attributes :ParameterTypeDescriptioncreatedstrRFC 3339 Datetime, example : "2020-10-06T20:07:18+02:00".orderIdstrMD5 HASH, example : "098f6bcd-4621-d373-cade-4e832627b4f6"productIdintId of the product example : 65156sizefloatSize of the order, example : 10.0000pricefloatPrice of the order, example : 8.6800buysellstr"B" or "S"orderTypeIdintsee 3.OrderorderTimeTypeIdintsee 3.OrderstopPricefloatPrice like : 0.0000totalTradedSizeint-typestr"CREATE", "DELETE" or "MODIFY"statusstr"CONFIRMED"laststrRFC 3339 Datetime, example : "2020-10-06T20:07:18+02:00".isActivebool-Here is how to get this data :# SETUP REQUESTorders_history=trading_api.get_orders_history(history_request=HistoryRequest(from_date=date(year=date.today().year,month=1,day=1),to_date=date.today(),),raw=True,)For a more comprehensive example :orders_history.py5.5. How to retrieve the TransactionsHistory ?Here is how to get this data :# SETUP REQUESTfrom_date=TransactionsHistory.Request.Date(year=2020,month=11,day=15)to_date=TransactionsHistory.Request.Date(year=2020,month=10,day=15)request=TransactionsHistory.Request(from_date=from_date,to_date=to_date)# FETCH DATAtransactions_history=trading_api.get_transactions_history(request=request)For a more comprehensive example :transactions_history.py6. Account6.1. How to retrieve the table : Config ?The config table contains the following informations :ParameterTypeDescriptionsessionIdstrCurrent session id.clientIdintUnique Degiro's Account identifier also called "userToken"tradingUrlstr-paUrlstr-reportingUrlstr-paymentServiceUrlstr-productSearchUrlstr-dictionaryUrlstr-productTypesUrlstr-companiesServiceUrlstr-i18nUrlstr-vwdQuotecastServiceUrlstr-vwdNewsUrlstr-vwdGossipsUrlstr-taskManagerUrlstr-refinitivNewsUrlstr-refinitivAgendaUrlstr-refinitivCompanyProfileUrlstr-refinitivCompanyRatiosUrlstr-refinitivFinancialStatementsUrlstr-refinitivClipsUrlstr-landingPathstr-betaLandingPathstr-mobileLandingPathstr-loginUrlstr-Here is how to get this table :# FETCH DATAconfig_table=trading_api.get_config()# EXTRACT SOME DATAuser_token=config_table['clientId']session_id=config_table['sessionId']For a more comprehensive example :config_table.py6.2. How to retrieve the table : ClientDetails ?The ClientDetails table contains information about the current Degiro Account.ParameterTypeidintintAccountintloggedInPersonIdintclientRolestreffectiveClientRolestrcontractTypestrusernamestrdisplayNamestremailstrfirstContact.firstNamestrfirstContact.lastNamestrfirstContact.displayNamestrfirstContact.nationalitystrfirstContact.genderstrfirstContact.dateOfBirthstrfirstContact.placeOfBirthstrfirstContact.countryOfBirthstraddress.streetAddressstraddress.streetAddressNumberstraddress.zipstraddress.citystraddress.countrystrcellphoneNumberstrlocalestrlanguagestrculturestrbankAccount.bankAccountIdintbankAccount.bicstrbankAccount.ibanstrbankAccount.statusstrflatexBankAccount.bicstrflatexBankAccount.ibanstrmemberCodestrisWithdrawalAvailableboolisAllocationAvailableboolisIskClientboolisCollectivePortfolioboolisAmClientActiveboolcanUpgradeboolHere is how to get this table :# FETCH DATAclient_details_table=trading_api.get_client_details()# EXTRACT SOME DATAint_account=client_details_table['data']['intAccount']user_token=client_details_table['data']['id']For a more comprehensive example :client_details_table.py6.3. How to retrieve the table : AccountInfo ?The AccountInfo table contains the following information about currencies.ParameterTypeclientIdintbaseCurrencystrcurrencyPairsdictmarginTypestrcashFundsdictcompensationCappingfloatHere is how to get this table :account_info_table=trading_api.get_account_info()For a more comprehensive example :account_info_table.py6.4. How to get the table : AccountOverview ?It will provide a list of cash movements.Here is how to get this data :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,)For a more comprehensive example :account_overview.pyEach cash movement contains this kind of parameters :ParameterTypedatestrvalueDatestridintorderIdstrdescriptionstrproductIdintcurrencystrchangefloatbalancedictunsettledCashfloattotalfloat6.5. How to export the table : AccountReport ?It will export a list of cash movements in a specific format.Available formats :CSVHTMLPDFXLSHere is how to get this content inCSVformat :report=trading_api.get_account_report(report_request=ReportRequest(country="FR",lang="fr",format=Format.CSV,from_date=date(year=date.today().year-1,month=1,day=1),to_date=date.today(),),raw=False,)Here are the available parameters forCashAccountReport.Request:ParameterTypeDescriptionformatCashAccountReport.FormatWanted format :CSVHTMLPDFXLScountrystrCountry name, like :FRlangintLanguage, like :frfrom_dateCashAccountReport.Request.DateEvents starting after this date.to_dateCashAccountReport.Request.DateEvents before this date.Models definitions are available are in this module :account.pyFor a more comprehensive example :account_report.py6.6. How to export the table : PositionReport ?It will export a list of cash movements in a specific format.Available formats :CSVHTMLPDFXLSHere is how to get this content inCSVformat :# SETUP REQUESTreport=trading_api.get_position_report(report_request=ReportRequest(country="FR",lang="fr",format=Format.XLS,from_date=date(year=date.today().year-1,month=1,day=1),to_date=date.today(),),raw=False,)Here are the available parameters forPositionReport.Request:ParameterTypeDescriptionformatPositionReport.FormatWanted format :CSVHTMLPDFXLScountrystrCountry name, like :FRlangintLanguage, like :frto_datePositionReport.Request.DateEvents before this date.Models definitions are available are in this module :account.pyFor a more comprehensive example :position_report.py7. Products7.1. How to get the table : ProductsConfig ?This table contains useful parameters to filter products.Here are the parameters which are inside this table :ParameterTypestockCountrieslistbondExchangeslistbondIssuerTypeslisteurexCountrieslistfutureExchangeslistoptionExchangeslistcombinationExchangeslistcfdExchangeslistexchangeslistindiceslistregionslistcountrieslistproductTypeslistetfFeeTypeslistinvestmentFundFeeTypeslistoptionAggregateTypeslistleveragedAggregateTypeslistetfAggregateTypeslistinvestmentFundAggregateTypeslistlookupSortColumnsliststockSortColumnslistbondSortColumnslistcfdSortColumnslistetfSortColumnslistfutureSortColumnslistHere is how to get this data :# FETCH DATAproducts_config=trading_api.get_products_config()For a more comprehensive example :products_config.py7.2. How to lookup products (search by name) ?Text research on a financial product.Here is how to get this data :product_request=LookupRequest(search_text='APPLE',limit=10,offset=0,product_type_id=1,)products_lookup=trading_api.product_search(product_request=product_request)For a more comprehensive example :product_lookup.py7.3. How to search bonds ?Here is how to get this data :# SETUP REQUESTproduct_request=BondsRequest(bond_issuer_type_id=0,bond_exchange_id=710,search_text='',offset=0,limit=100,require_total=True,sort_columns='name',sort_types='asc',)# FETCH DATAbond_list=trading_api.product_search(product_request=product_request)For a more comprehensive example :product_search.py7.4. How to search etfs ?Here is how to get this data :# SETUP REQUESTproduct_request=ETFsRequest(popular_only=False,input_aggregate_types='',input_aggregate_values='',search_text='',offset=0,limit=100,require_total=True,sort_columns='name',sort_types='asc',)# FETCH DATAetf_list=trading_api.product_search(product_request=product_request)For a more comprehensive example :product_search.py7.5. How to search funds ?Here is how to get this data :# SETUP REQUESTproduct_request=FundsRequest(search_text='',offset=0,limit=100,require_total=True,sort_columns='name',sort_types='asc',)# FETCH DATAfund_list=trading_api.product_search(product_request=product_request)For a more comprehensive example :product_search.py7.6. How to search futures ?Here is how to get this data :# SETUP REQUESTproduct_request=FuturesRequest(future_exchange_id=1,underlying_isin='FR0003500008',search_text='',offset=0,limit=100,require_total=True,sort_columns='name',sort_types='asc',)# FETCH DATAfund_list=trading_api.product_search(product_request=product_request)For a more comprehensive example :product_search.py7.7. How to search leverageds ?Here is how to get this data :# SETUP REQUESTproduct_request=LeveragedsRequest(popular_only=False,input_aggregate_types='',input_aggregate_values='',search_text='',offset=0,limit=100,require_total=True,sort_columns='name',sort_types='asc',)# FETCH DATAetf_list=trading_api.product_search(product_request=product_request)For a more comprehensive example :product_search.py7.8. How to search options ?Here is how to get this data :# SETUP REQUESTproduct_request=OptionsRequest(input_aggregate_types='',input_aggregate_values='',option_exchange_id=3,underlying_isin='FR0003500008',search_text='',offset=0,limit=100,require_total=True,sort_columns='expirationDate,strike',sort_types='asc,asc',)# FETCH DATAoption_list=trading_api.product_search(product_request=product_request)For a more comprehensive example :product_search.py7.9. How to search stocks ?It contains information about available stocks.Here is how to get this data :# SETUP REQUESTproduct_request=StocksRequest(index_id=122001,# NASDAQ 100# exchange_id=663,  # NASDAQ# You can either use `index_id` or `exchange id`# See which one to use in the `ProductsConfig` tableis_in_us_green_list=True,stock_country_id=846,# USsearch_text='',offset=0,limit=100,require_total=True,sort_columns='name',sort_types='asc',)# FETCH DATAstock_list=trading_api.product_search(product_request=product_request)For a more comprehensive example :product_search.py7.10. How to search warrants ?Here is how to get this data :# SETUP REQUESTproduct_request=WarrantsRequest(search_text='',offset=0,limit=100,require_total=True,sort_columns='name',sort_types='asc',)# FETCH DATAwarrant_list=trading_api.product_search(product_request=product_request)For a more comprehensive example :product_search.py7.11. How to search products from ids ?Here is how to get this data :product_info=trading_api.get_products_info(product_list=[96008,1153605,5462588],raw=False,)For a more comprehensive example :products_info.py7.12. How to get my favorite products ?Here is how to get this data :favorites_batch=trading_api.get_favorites()For a more comprehensive example :favorite_get.py7.13. How to create a favorite list ?Example :favorite_id=trading_api.create_favorite(name="SOME_NAME")For a more comprehensive example :favorite_create.py7.14. How to delete a favorite list ?Example :success=trading_api.delete_favorite(id=1234567)For a more comprehensive example :favorite_delete.py7.15. How to move a favorite list ?Example :success=trading_api.move_favorite(list_id=1234567,position=1,)For a more comprehensive example :favorite_move.py7.16. How to put favorite list products ?Example :success=trading_api.put_favorite_product(id=1234567,product_id=1234567,)For a more comprehensive example :favorite_put_product.py7.17. How to delete favorite list products ?Example :success=trading_api.delete_favorite_product(id=1234567,product_id=1234567,)For a more comprehensive example :
[favorite_delete product.py](examples/trading/favorite_delete product.py)7.18. How to get futures/options underlyings ?Example :underlying_list=trading_api.get_underlyings(underlyings_request=UnderlyingsRequest(future_exchange_id=1,# option_exchange_id=3,),raw=False,)For a more comprehensive example :favorite_get_underlyings.py8. Companies8.1. How to get : CompanyProfile ?Here is how to get this data :# FETCH DATAcompany_profile=trading_api.get_company_profile(product_isin='FR0000131906',)For a more comprehensive example :company_profile.py8.2. How to get : CompanyRatios ?This table contains information about the company.Here are the parameters which are inside this table :ParameterTypetotalFloatstrsharesOutstrconsRecommendationTrenddictforecastDatadictcurrentRatiosdictHere is how to get this data :# FETCH DATAcompany_ratios=trading_api.get_company_ratios(product_isin='FR0000131906',)For a more comprehensive example :company_ratios.py8.3. How to get : FinancialStatements ?Here is how to get this data :# FETCH DATAfinancials_statements=trading_api.get_financials_statements(product_isin='FR0000131906',)For a more comprehensive example :financial_statements.py8.4. How to get : LatestNews ?Here is how to get this data :# SETUP REQUESTrequest=LatestNews.Request(offset=0,languages='en,fr',limit=20,)# FETCH DATAlatest_news=trading_api.get_latest_news(request=request,raw=True,)For a more comprehensive example :latest_news.py8.5. How to get : TopNewsPreview ?Here is how to get this data :# FETCH DATAtop_news_preview=trading_api.get_top_news_preview(raw=True)For a more comprehensive example :top_news_preview.py8.6. How to get : NewsByCompany ?Here is how to get this data :# SETUP REQUESTrequest=NewsByCompany.Request(isin='NL0000235190',limit=10,offset=0,languages='en,fr',)# FETCH DATAnews_by_company=trading_api.get_news_by_company(request=request,raw=True,)For a more comprehensive example :news_by_company.py8.7. How to get : Agenda ?Here is how to get this data :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,)Here are the available parameters forAgenda.Request:ParameterTypeDescriptioncalendar_typeAgenda.CalendarTypeType of agenda :DIVIDEND_CALENDARECONOMIC_CALENDAREARNINGS_CALENDARHOLIDAY_CALENDARIPO_CALENDARSPLIT_CALENDARoffsetint-limitint-order_by_descbool-start_dateTimestampEvents starting after this date.end_dateTimestampEvents before this date.company_namestrFilter used on the events description.countriesstrComma separated list of countries like :FR,USclassificationsstrComma separated list of sectors like :GovernmentSector,ExternalSectorunitsstrComma separated list of units like :Acre,BarrelExact definitions ofAgendaandAgendaRequestare in this module :agenda.pyFor a more comprehensive example :agenda.py8.8. How to get : EstimatesSummaries ?Here is how to get this data :estimates_summaries=trading_api.get_estimates_summaries(product_isin="FR0000131906",raw=False,)Here are the available parameters forAgenda.Request:ParameterTypeDescriptionannualdictIndicators by year.currencystrcurrency, exampleEUR.interimdictIndicators by quarter.lastRetrievedstrLast Retrieved, example :2021-12-31T20:07:30.939Z.lastUpdatedstrLast updated,, example :2021-02-18T01:30:00Z.preferredMeasurestrPreferred measure, example :EPS.ricstrReuters Instrument Code, example :BOUY.PA.Exact definition ofEstimatesSummariesis in this file :product.pyFor a more comprehensive example :estimates_summaries.py9. LicenseBSD-3-Clause License