### Set up virtual environment and install saxo_openapi Source: https://github.com/hootnot/saxo_openapi/blob/master/README.rst Commands to create a Python 3.7 virtual environment, activate it, and install the saxo_openapi package along with requests. After installation, obtain a token from developer.saxo and try some examples. ```bash $ mkdir tst_saxo_openapi $ cd tst_saxo_openapi $ /usr/local/bin/python3.7 -m venv venv37 $ . ./venv37/bin/activate (venv37) feite@oatr:~/tst_saxo_openapi$ $ pip install saxo_openapi requests # get a token from developer.saxo # try some examples ``` -------------------------------- ### Create and activate a virtual environment Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/installation.rst Create a Python 3.6 virtual environment, activate it, and install saxo_openapi within it. This isolates the installation from the system Python environment. ```bash $ python3.6 -m venv $ . .//bin/activate $ pip install git+https://github.com/hootnot/saxo_openapi.git ``` -------------------------------- ### Example response output Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/rootservices/sessions/CreateSessionCapabilitiesSubscription.rst Example output from the request, showing the subscription details including Snapshot with DataLevel and TradeLevel, and State 'Active'. ```default { "ContextId": "20190314053019906", "Format": "application/json", "InactivityTimeout": 120, "ReferenceId": "S56886", "RefreshRate": 1000, "Snapshot": { "DataLevel": "Standard", "TradeLevel": "OrdersOnly" }, "State": "Active" } ``` -------------------------------- ### Shorten params setup using account_info() Source: https://github.com/hootnot/saxo_openapi/blob/master/jupyter/balances.ipynb Uses the account_info() helper from saxo_openapi.contrib.session to obtain the ClientKey directly, simplifying the params setup. ```python from saxo_openapi.contrib.session import account_info ai = account_info(client) params = { 'ClientKey': ai.ClientKey } print(params) ``` ```text Output: {'ClientKey': 'fOA0tvOyQqW2aHpWi9P5bw=='} ``` -------------------------------- ### UserUpdate request setup and data body Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/users/UserUpdate.rst Shows how to instantiate a UserUpdate request with a data dict containing the language parameter. The example imports the required modules and creates an API client with an access token. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.portfolio as pf >>> import json >>> client = saxo_openapi.API(access_token=...) >>> data = { "Language": "nl" } ``` -------------------------------- ### Example response from CreatePriceSubscription Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/trading/prices/CreatePriceSubscription.rst Example JSON response showing the subscription state, snapshot with quote data, and metadata like InactivityTimeout and RefreshRate. ```default { "ContextId": "explorer_1552305379377", "Format": "application/json", "InactivityTimeout": 30, "ReferenceId": "N_935", "RefreshRate": 1000, "Snapshot": { "AssetType": "FxSpot", "LastUpdated": "2019-03-11T21:14:00.578000Z", "PriceSource": "SBFX", "Quote": { "Amount": 100000, "Ask": 1.35827, "Bid": 1.35754, "DelayedByMinutes": 0, "ErrorCode": "None", "Mid": 1.357905, "PriceTypeAsk": "Tradable", "PriceTypeBid": "Tradable", "RFQState": "None" }, "Uic": 45 }, "State": "Active" } ``` -------------------------------- ### PrecheckOrder usage example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/trading/orders/PrecheckOrder.rst Example of using the PrecheckOrder endpoint with the saxo_openapi client, including request creation and response printing. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.trading as tr >>> import json >>> client = saxo_openapi.API(access_token=...) >>> data = ... >>> r = tr.orders.PrecheckOrder(data=data) >>> client.request(r) >>> print(json.dumps(r.response, indent=4)) ``` -------------------------------- ### MarketOrderFxSpot usage example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/contrib/orders/MarketOrderFxSpot.rst Shows how to create a MarketOrderFxSpot order, tie it to an account, and send it via the API. The example prints the response, which includes an OrderId. ```pycon >>> from saxo_openapi import API >>> from saxo_openapi.contrib.orders import ( ... tie_account_to_order, ... MarketOrderFxSpot) >>> token = "..." >>> client = API(access_token=token) >>> order = tie_account_to_order( ... AccountKey, ... MarketOrderFxSpot(Uic=21, Amount=25000)) >>> r = tr.orders.Order(data=req) >>> rv = client.request(r) >>> print(json.dumps(rv, indent=2)) { "OrderId": "76703544" } ``` -------------------------------- ### AssetType usage example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/saxo_openapi.definitions.accounthistory.rst Shows how to import the module and access the AssetType definition. The example prints the Name ID and then retrieves its description using the __getitem__ method. ```pycon >>> import saxo_openapi.definitions.accounthistory as defaccounthistory >>> print(defaccounthistory.AssetType.Name) Name >>> c = defaccounthistory.AssetType() >>> print(c[c.Name]) Description >>> # or >>> print(defaccounthistory.AssetType().definitions[c.Name]) >>> # all keys >>> print(defaccounthistory.AssetType().definitions.keys()) >>> ... ``` -------------------------------- ### ToOpenClose usage example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/saxo_openapi.definitions.orders.rst Shows how to access ToOpenClose definitions and their descriptions. The example prints the ID for ToClose, retrieves the description via __getitem__, and lists all keys. ```pycon >>> import saxo_openapi.definitions.orders as deforders >>> print(deforders.ToOpenClose.ToClose) ToClose >>> c = deforders.ToOpenClose() >>> print(c[c.ToClose]) Order/Position is ToClose >>> # or >>> print(deforders.ToOpenClose().definitions[c.ToClose]) >>> # all keys >>> print(deforders.ToOpenClose().definitions.keys()) >>> ... ``` -------------------------------- ### Example response from PositionsQuery Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/positions/PositionsQuery.rst Example JSON response showing the structure of the positions data, including position details such as NetPositionId, PositionBase, and PositionView fields. ```default { "__count": 4, "Data": [ { "NetPositionId": "EURUSD__FxSpot", "PositionBase": { "AccountId": "9226397", "Amount": -100000, "AssetType": "FxSpot", "CanBeClosed": true, "ClientId": "9226397", "CloseConversionRateSettled": false, "CorrelationKey": "46dc6b2a-5b6f-43c8-b747-6b530da9110e", "ExecutionTimeOpen": "2019-03-04T00:10:23.040641Z", "IsMarketOpen": true, "OpenPrice": 1.13715, "RelatedOpenOrders": [], "SourceOrderId": "76271915", "SpotDate": "2019-03-06", "Status": "Open", "Uic": 21, "ValueDate": "2019-03-06T00:00:00.000000Z" }, "PositionId": "212561926", "PositionView": { "CalculationReliability": "Ok", "ConversionRateCurrent": 0.882905, "ConversionRateOpen": 0.882905, "CurrentPrice": 1.13273, "CurrentPriceDelayMinutes": 0, "CurrentPriceType": "Ask", "Exposure": -100000, "ExposureCurrency": "EUR", "ExposureInBaseCurrency": -100000, "InstrumentPriceDayPercentChange": -0.34, "ProfitLossOnTrade": 442, "ProfitLossOnTradeInBaseCurrency": 390.24, "TradeCostsTotal": -11.35, "TradeCostsTotalInBaseCurrency": -10.02 } }, { "NetPositionId": "EURUSD__FxSpot", "PositionBase": { "AccountId": "9226397", "Amount": 100000, "AssetType": "FxSpot", "CanBeClosed": true, "ClientId": "9226397", "CloseConversionRateSettled": false, "CorrelationKey": "50fae087-b7d4-49ab-afa2-5145cd56a7c5", "ExecutionTimeOpen": "2019-03-04T00:04:11.340151Z", "IsMarketOpen": true, "OpenPrice": 1.1371, "RelatedOpenOrders": [], "SourceOrderId": "76271912", "SpotDate": "2019-03-06", "Status": "Open", "Uic": 21, "ValueDate": "2019-03-06T00:00:00.000000Z" }, "PositionId": "212561892", "PositionView": { "CalculationReliability": "Ok", "ConversionRateCurrent": 0.882905, "ConversionRateOpen": 0.882905, "CurrentPrice": 1.13253, "CurrentPriceDelayMinutes": 0, "CurrentPriceType": "Bid", "Exposure": 100000, "ExposureCurrency": "EUR", "ExposureInBaseCurrency": 100000, "InstrumentPriceDayPercentChange": -0.34, "ProfitLossOnTrade": -457, "ProfitLossOnTradeInBaseCurrency": -403.49, "TradeCostsTotal": -11.35, "TradeCostsTotalInBaseCurrency": -10.02 } }, { "NetPositionId": "GBPAUD__FxSpot", "PositionBase": { "AccountId": "9226397", "Amount": 500000, "AssetType": "FxSpot", "CanBeClosed": true, "ClientId": "9226397", "CloseConversionRateSettled": false, "CorrelationKey": "206cceed-2240-43f8-8c46-840e8b722549", "ExecutionTimeOpen": "2019-03-03T23:35:08.243690Z", "IsMarketOpen": true, "OpenPrice": 1.86391, "RelatedOpenOrders": [], "SourceOrderId": "76271862", "SpotDate": "2019-03-06", "Status": "Open", "Uic": 22, "ValueDate": "2019-03-06T00:00:00.000000Z" }, "PositionId": "212550212", "PositionView": { "CalculationReliability": "Ok", "ConversionRateCurrent": 0.62534, "ConversionRateOpen": 0.62534, "CurrentPrice": 1.86127, "CurrentPriceDelayMinutes": 0, "CurrentPriceType": "Bid", "Exposure": 500000, "ExposureCurrency": "GBP", "ExposureInBaseCurrency": 582115, "InstrumentPriceDayPercentChange": -0.19, "ProfitLossOnTrade": -1320, "ProfitLossOnTradeInBaseCurrency": -825.45, "TradeCostsTotal": -93.13, "TradeCostsTotalInBaseCurrency": -58.24 } }, { "NetPositionId": "GBPCAD__FxSpot", "PositionBase": { "AccountId": "9226397", "Amount": 100000, "AssetType": "FxSpot", "CanBeClosed": true, "ClientId": "9226397", "CloseConversionRateSettled": false, "CorrelationKey": "206cceed-2240-43f8-8c46-840e8b722549", "ExecutionTimeOpen": "2019-03-03T23:35:08.243690Z", "IsMarketOpen": true, "OpenPrice": 1.86391, "RelatedOpenOrders": [], "SourceOrderId": "76271862", "SpotDate": "2019-03-06", "Status": "Open", "Uic": 22, "ValueDate": "2019-03-06T00:00:00.000000Z" }, "PositionId": "212550212", "PositionView": { "CalculationReliability": "Ok", "ConversionRateCurrent": 0.62534, "ConversionRateOpen": 0.62534, "CurrentPrice": 1.86127, "CurrentPriceDelayMinutes": 0, "CurrentPriceType": "Bid", "Exposure": 500000, "ExposureCurrency": "GBP", "ExposureInBaseCurrency": 582115, "InstrumentPriceDayPercentChange": -0.19, "ProfitLossOnTrade": -1320, "ProfitLossOnTradeInBaseCurrency": -825.45, "TradeCostsTotal": -93.13, "TradeCostsTotalInBaseCurrency": -58.24 } } ] } ``` -------------------------------- ### UsersMe request example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/users/UsersMe.rst Instantiate a UsersMe request, send it via the API client, and print the response as JSON. The example uses the saxo_openapi library and requires an access token. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.portfolio as pf >>> import json >>> client = saxo_openapi.API(access_token=...) >>> r = pf.users.UsersMe() >>> client.request(r) >>> print(json.dumps(r.response, indent=4)) ``` -------------------------------- ### Setup client and account for onfill orders Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/contrib/orders/onfill.rst Initializes the API client and retrieves the first account's AccountKey, which is required to attach to order bodies before placing orders. ```pycon >>> import json >>> from saxo_openapi import API >>> import saxo_openapi.endpoints.trading as tr >>> import saxo_openapi.endpoints.portfolio as pf >>> from saxo_openapi.contrib.orders import ( ... tie_account_to_order, ... MarketOrderFxSpot, ... TakeProfitDetails, ... StopLossDetails) >>> token = "..." >>> client = API(access_token=token) >>> r = pf.accounts.AccountsMe() >>> rv = client.request(r) >>> # take the first account ... >>> acct = rv['Data'][0] >>> AccountKey = acct['AccountKey'] ``` -------------------------------- ### CreateExposureSubscription request setup Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/exposure/CreateExposureSubscription.rst Sets up a subscription and returns an initial snapshot of instrument exposure. The data dictionary includes Arguments, ContextId, and ReferenceId. The endpoint is 'openapi/port/v1/exposure/instruments/subscriptions' with expected status 201. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.portfolio as pf >>> import json >>> client = saxo_openapi.API(access_token=...) >>> data = { "Arguments": { "ClientKey": "Cf4xZWiYL6W1nMKpygBLLA==" }, "ContextId": "explorer_1552035128308", "ReferenceId": "Z_807" } ``` -------------------------------- ### Example response from PositionsMe endpoint Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/positions/PositionsMe.rst Shows the JSON structure returned by the endpoint, including position details such as NetPositionId, PositionBase, and PositionView fields. ```default { "__count": 4, "Data": [ { "NetPositionId": "EURUSD__FxSpot", "PositionBase": { "AccountId": "9226397", "Amount": -100000, "AssetType": "FxSpot", "CanBeClosed": true, "ClientId": "9226397", "CloseConversionRateSettled": false, "CorrelationKey": "46dc6b2a-5b6f-43c8-b747-6b530da9110e", "ExecutionTimeOpen": "2019-03-04T00:10:23.040641Z", "IsMarketOpen": true, "OpenPrice": 1.13715, "RelatedOpenOrders": [], "SourceOrderId": "76271915", "SpotDate": "2019-03-06", "Status": "Open", "Uic": 21, "ValueDate": "2019-03-06T00:00:00.000000Z" }, "PositionId": "212561926", "PositionView": { "CalculationReliability": "Ok", "ConversionRateCurrent": 0.882595, "ConversionRateOpen": 0.882595, "CurrentPrice": 1.13312, "CurrentPriceDelayMinutes": 0, "CurrentPriceType": "Ask", "Exposure": -100000, "ExposureCurrency": "EUR", "ExposureInBaseCurrency": -100000, "InstrumentPriceDayPercentChange": -0.31, "ProfitLossOnTrade": 403, "ProfitLossOnTradeInBaseCurrency": 355.69, "TradeCostsTotal": -11.36, "TradeCostsTotalInBaseCurrency": -10.03 } }, { "NetPositionId": "EURUSD__FxSpot", "PositionBase": { "AccountId": "9226397", "Amount": 100000, "AssetType": "FxSpot", "CanBeClosed": true, "ClientId": "9226397", "CloseConversionRateSettled": false, "CorrelationKey": "50fae087-b7d4-49ab-afa2-5145cd56a7c5", "ExecutionTimeOpen": "2019-03-04T00:04:11.340151Z", "IsMarketOpen": true, "OpenPrice": 1.1371, "RelatedOpenOrders": [], "SourceOrderId": "76271912", "SpotDate": "2019-03-06", "Status": "Open", "Uic": 21, "ValueDate": "2019-03-06T00:00:00.000000Z" }, "PositionId": "212561892", "PositionView": { "CalculationReliability": "Ok", "ConversionRateCurrent": 0.882595, "ConversionRateOpen": 0.882595, "CurrentPrice": 1.13292, "CurrentPriceDelayMinutes": 0, "CurrentPriceType": "Bid", "Exposure": 100000, "ExposureCurrency": "EUR", "ExposureInBaseCurrency": 100000, "InstrumentPriceDayPercentChange": -0.31, "ProfitLossOnTrade": -418, "ProfitLossOnTradeInBaseCurrency": -368.92, "TradeCostsTotal": -11.35, "TradeCostsTotalInBaseCurrency": -10.02 } }, { "NetPositionId": "GBPAUD__FxSpot", "PositionBase": { "AccountId": "9226397", "Amount": 500000, "AssetType": "FxSpot", "CanBeClosed": true, "ClientId": "9226397", "CloseConversionRateSettled": false, "CorrelationKey": "206cceed-2240-43f8-8c46-840e8b722549", "ExecutionTimeOpen": "2019-03-03T23:35:08.243690Z", "IsMarketOpen": true, "OpenPrice": 1.86391, "RelatedOpenOrders": [], "SourceOrderId": "76271862", "SpotDate": "2019-03-06", "Status": "Open", "Uic": 22, "ValueDate": "2019-03-06T00:00:00.000000Z" }, "PositionId": "212550212", "PositionView": { "CalculationReliability": "Ok", "ConversionRateCurrent": 0.6254, "ConversionRateOpen": 0.6254, "CurrentPrice": 1.85999, "CurrentPriceDelayMinutes": 0, "CurrentPriceType": "Bid", "Exposure": 500000, "ExposureCurrency": "GBP", "ExposureInBaseCurrency": 581757.5, "InstrumentPriceDayPercentChange": -0.25, "ProfitLossOnTrade": -1960, "ProfitLossOnTradeInBaseCurrency": -1225.78, "TradeCostsTotal": -93.1, "TradeCostsTotalInBaseCurrency": -58.22 } }, { "NetPositionId": "GBPCAD__FxSpot", "PositionBase": { "AccountId": "9226397", "Amount": 100000, "AssetType": "FxSpot", "CanBeClosed": true, "ClientId": "9226397", "CloseConversionRateSettled": false, "CorrelationKey": "19c44107-6858-4191-805c-764a69d27491", "ExecutionTimeOpen": "2019-03-04T00:00:00.000000Z", "IsMarketOpen": true, "OpenPrice": 1.86391, "RelatedOpenOrders": [], "SourceOrderId": "76271862", "SpotDate": "2019-03-06", "Status": "Open", "Uic": 22, "ValueDate": "2019-03-06T00:00:00.000000Z" }, "PositionId": "212550212", "PositionView": { "CalculationReliability": "Ok", "ConversionRateCurrent": 0.6254, "ConversionRateOpen": 0.6254, "CurrentPrice": 1.85999, "CurrentPriceDelayMinutes": 0, "CurrentPriceType": "Bid", "Exposure": 100000, "ExposureCurrency": "GBP", "ExposureInBaseCurrency": 116351.5, "InstrumentPriceDayPercentChange": -0.25, "ProfitLossOnTrade": -392, "ProfitLossOnTradeInBaseCurrency": -245.16, "TradeCostsTotal": -18.62, "TradeCostsTotalInBaseCurrency": -11.64 } } ] } ``` -------------------------------- ### ClientDetailsMe request example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/clients/ClientDetailsMe.rst Instantiate a ClientDetailsMe request and send it using the saxo_openapi client. The response is printed as formatted JSON. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.portfolio as pf >>> import json >>> client = saxo_openapi.API(access_token=...) >>> r = pf.clients.ClientDetailsMe() >>> client.request(r) >>> print(json.dumps(r.response, indent=4)) ``` -------------------------------- ### Instantiate AccountPerformance request Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/accounthistory/performance/AccountPerformance.rst Sets up the client and parameters for an AccountPerformance request. Requires ClientKey and either StandardPeriod or FromDate/ToDate. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.accounthistory as ah >>> import json >>> client = saxo_openapi.API(access_token=...) >>> ClientKey = 'Cf4xZWiYL6W1nMKpygBLLA==' >>> params = { "FromDate": "2019-03-01", "ToDate": "2019-03-10" } ``` -------------------------------- ### ClientDetailsByOwner request setup Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/clients/ClientDetailsByOwner.rst Imports required modules and creates an API client with an access token. Defines the querystring parameters with an OwnerKey. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.portfolio as pf >>> import json >>> client = saxo_openapi.API(access_token=...) >>> params = { "OwnerKey": "Cf4xZWiYL6W1nMKpygBLLA==" } ``` -------------------------------- ### Get Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/rootservices/diagnostics.rst The Get class represents a GET request to the diagnostics endpoint. It is used to retrieve diagnostic information. ```APIDOC ## [GET] Get ### Description The Get class represents a GET request to the diagnostics endpoint. It is used to retrieve diagnostic information. ### Method GET ### Endpoint (Endpoint path not specified in source) ### Parameters No parameters documented. ### Response No response schema documented. ``` -------------------------------- ### POST openapi/port/v1/accounts/subscriptions/ Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/accounts/SubscriptionCreate.rst Set up a subscription and returns an initial snapshot containing a list of accounts as specified by the parameters in the request. This endpoint creates a new subscription for account data. ```APIDOC ## [POST] openapi/port/v1/accounts/subscriptions/ ### Description Set up a subscription and returns an initial snapshot containing a list of accounts as specified by the parameters in the request. ### Method POST ### Endpoint openapi/port/v1/accounts/subscriptions/ ### Parameters #### Request Body - **data** (dict) - Required - dict representing the request body. ### Response #### Success Response (201) - **ContextId** (string) - The context ID of the subscription - **Format** (string) - The format of the response data - **InactivityTimeout** (integer) - The inactivity timeout in seconds - **ReferenceId** (string) - The reference ID of the subscription - **RefreshRate** (integer) - The refresh rate in milliseconds - **Snapshot** (object) - The initial snapshot containing account data - **Data** (array) - List of account objects - **AccountGroupKey** (string) - The account group key - **AccountId** (string) - The account ID - **AccountKey** (string) - The account key - **AccountType** (string) - The account type - **Active** (boolean) - Whether the account is active - **CanUseCashPositionsAsMarginCollateral** (boolean) - Whether cash positions can be used as margin collateral - **ClientId** (string) - The client ID - **ClientKey** (string) - The client key - **CreationDate** (string) - The account creation date - **Currency** (string) - The account currency - **CurrencyDecimals** (integer) - The number of currency decimals - **DirectMarketAccess** (boolean) - Whether direct market access is enabled - **DisplayName** (string) - The display name of the account - **IndividualMargining** (boolean) - Whether individual margining is used - **IsCurrencyConversionAtSettlementTime** (boolean) - Whether currency conversion occurs at settlement time - **IsMarginTradingAllowed** (boolean) - Whether margin trading is allowed - **IsShareable** (boolean) - Whether the account is shareable - **IsTrialAccount** (boolean) - Whether this is a trial account - **LegalAssetTypes** (array) - List of legal asset types - **Sharing** (array) - List of sharing settings - **SupportsAccountValueProtectionLimit** (boolean) - Whether account value protection limit is supported - **UseCashPositionsAsMarginCollateral** (boolean) - Whether cash positions are used as margin collateral - **State** (string) - The state of the subscription ### Request Example ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.portfolio as pf >>> import json >>> client = saxo_openapi.API(access_token=...) >>> data = { "Arguments": { "ClientKey": "Cf4xZWiYL6W1nMKpygBLLA==" }, "ContextId": "explorer_1551455553043", "ReferenceId": "I_213" } ``` ```pycon >>> r = pf.accounts.SubscriptionCreate(data=data) >>> client.request(r) >>> print(json.dumps(r.response, indent=2)) ``` #### Response Example ```default { "ContextId": "explorer_1551455553043", "Format": "application/json", "InactivityTimeout": 30, "ReferenceId": "I_213", "RefreshRate": 5000, "Snapshot": { "Data": [ { "AccountGroupKey": "Cf4xZWiYL6W1nMKpygBLLA==", "AccountId": "9226397", "AccountKey": "Cf4xZWiYL6W1nMKpygBLLA==", "AccountType": "Normal", "Active": true, "CanUseCashPositionsAsMarginCollateral": true, "ClientId": "9226397", "ClientKey": "Cf4xZWiYL6W1nMKpygBLLA==", "CreationDate": "2019-02-02T10:47:42.313000Z", "Currency": "EUR", "CurrencyDecimals": 2, "DirectMarketAccess": false, "DisplayName": "bram", "IndividualMargining": false, "IsCurrencyConversionAtSettlementTime": true, "IsMarginTradingAllowed": true, "IsShareable": false, "IsTrialAccount": true, "LegalAssetTypes": [ "FxSpot", "FxForwards", "FxVanillaOption", "FxKnockInOption", "FxKnockOutOption", "FxOneTouchOption", "FxNoTouchOption" ], "Sharing": [ "NoSharing" ], "SupportsAccountValueProtectionLimit": false, "UseCashPositionsAsMarginCollateral": true } ] }, "State": "Active" } ``` ``` -------------------------------- ### GET openapi/root/v1/diagnostics/get/ Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/rootservices/diagnostics/Get.rst Send a GET request to the diagnostics endpoint and receive a 200 OK response. This endpoint is used to verify connectivity and service availability. No data is returned in the response. ```APIDOC ## [GET] openapi/root/v1/diagnostics/get/ ### Description Send a GET request and get a 200 OK response back. This endpoint is used to check the health of the API service. ### Method GET ### Endpoint openapi/root/v1/diagnostics/get/ ### Response #### Success Response (200) No data is returned. ### Request Example ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.rootservices as rs >>> import json >>> client = saxo_openapi.API(access_token=...) >>> r = rs.diagnostics.Get() >>> rv = client.request(r) >>> assert r.status_code == r.expected_status ``` ``` -------------------------------- ### Send GET request to diagnostics endpoint Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/rootservices/diagnostics/Get.rst Instantiate a Get request and send it using the client. The response status code is asserted to match the expected status (200). No data is returned. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.rootservices as rs >>> import json >>> client = saxo_openapi.API(access_token=...) >>> r = rs.diagnostics.Get() >>> rv = client.request(r) >>> assert r.status_code == r.expected_status ``` -------------------------------- ### Example response from CreateExposureSubscription Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/exposure/CreateExposureSubscription.rst Example output showing the subscription response with ContextId, Format, InactivityTimeout, ReferenceId, RefreshRate, Snapshot data, and State. The snapshot contains exposure details for multiple instruments. ```default { "ContextId": "explorer_1552035128308", "Format": "application/json", "InactivityTimeout": 30, "ReferenceId": "Z_807", "RefreshRate": 1000, "Snapshot": { "Data": [ { "Amount": 60000, "AssetType": "FxSpot", "AverageOpenPrice": 1.13071, "CalculationReliability": "Ok", "CanBeClosed": true, "DisplayAndFormat": { "Currency": "USD", "Decimals": 4, "Description": "Euro/US Dollar", "Format": "AllowDecimalPips", "Symbol": "EURUSD" }, "InstrumentPriceDayPercentChange": 0.44, "NetPositionId": "EURUSD__FxSpot", "ProfitLossOnTrade": -396.6, "Uic": 21 }, { "Amount": -50000, "AssetType": "FxSpot", "AverageOpenPrice": 8.6839, "CalculationReliability": "Ok", "CanBeClosed": true, "DisplayAndFormat": { "Currency": "DKK", "Decimals": 4, "Description": "British Pound/Danish Krone", "Format": "Normal", "Symbol": "GBPDKK" }, "InstrumentPriceDayPercentChange": -0.98, "NetPositionId": "GBPDKK__FxSpot", "ProfitLossOnTrade": 2420, "Uic": 25 } ] }, "State": "Active" } ``` -------------------------------- ### GET openapi/root/v1/features/availability/ Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/rootservices/features/Availability.rst Get the availability of all features. This endpoint returns a list of features and their availability status. ```APIDOC ## [GET] openapi/root/v1/features/availability/ ### Description Get the availability of all features. ### Method GET ### Endpoint openapi/root/v1/features/availability/ ### Response #### Success Response (200) - **Available** (boolean) - Indicates whether the feature is available. - **Feature** (string) - The name of the feature. #### Response Example ```json [ { "Available": true, "Feature": "News" }, { "Available": true, "Feature": "GainersLosers" }, { "Available": true, "Feature": "Calendar" }, { "Available": true, "Feature": "Chart" } ] ``` ``` -------------------------------- ### Trading example with token from file Source: https://github.com/hootnot/saxo_openapi/blob/master/README.rst Initializes the saxo_openapi client for trading endpoints using an access token read from a file named tok.txt. The token file must contain the token as a single line; the example reads and strips whitespace from it. ```python from saxo_openapi import API import saxo_openapi.endpoints.trading as tr import saxo_openapi.endpoints.portfolio as pf import json # Place your token in a file named: tok.txt tok = "" with open("tok.txt") as I: tok = I.read().strip() # Our client to process the requests client = API(access_token=tok) ``` -------------------------------- ### Example: Creating and submitting a LimitOrderFxSpot Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/contrib/orders/LimitOrderFxSpot.rst Shows how to create a LimitOrderFxSpot order, tie it to an account, and submit it via the API. The example uses Uic=21, Amount=25000, and OrderPrice=1.1025, and prints the response containing the OrderId. ```pycon >>> from saxo_openapi import API >>> from saxo_openapi.contrib.orders import ( ... tie_account_to_order, ... LimitOrderFxSpot) >>> token = "..." >>> client = API(access_token=token) >>> order = tie_account_to_order( ... AccountKey, ... LimitOrderFxSpot(Uic=21, Amount=25000, OrderPrice=1.1025)) >>> r = tr.orders.Order(data=order) >>> rv = client.request(r) >>> print(json.dumps(rv, indent=2)) { "OrderId": "76703544" } ``` -------------------------------- ### CancelOrders output example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/trading/orders/CancelOrders.rst Example response from the CancelOrders request, showing the cancelled order ID. ```default { "Orders": [ { "OrderId": "76289286" } ] } ``` -------------------------------- ### Python client usage for placing an order Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/trading/orders/Order.rst Shows how to instantiate an Order request, send it via the client, and print the response. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.trading as tr >>> import json >>> client = saxo_openapi.API(access_token=...) >>> data = ... >>> r = tr.orders.Order(data=data) >>> client.request(r) >>> print(json.dumps(r.response, indent=4)) ``` -------------------------------- ### CancelOrders params example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/trading/orders/CancelOrders.rst Example of the params dictionary for the CancelOrders request, containing the AccountKey required for the operation. ```default params = { "AccountKey": "Cf4xZWiYL6W1nMKpygBLLA==" } ``` -------------------------------- ### Run stream_example.py with context ID Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/examples/stream_proc.rst Command to start the stream processing script, passing a context ID as argument. The program runs but produces no output until subscriptions are created. ```bash $ python stream_example.py ctxt_20190311 ``` -------------------------------- ### PrecheckOrder response example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/trading/orders/PrecheckOrder.rst Example response from the PrecheckOrder endpoint, showing estimated cash required and pre-check result. ```default { "EstimatedCashRequired": 296.275, "EstimatedCashRequiredCurrency": "EUR", "InstrumentToAccountConversionRate": 0.88239, "PreCheckResult": "Ok" } ``` -------------------------------- ### OrderDetails request setup Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/orders/OrderDetails.rst Setup for the OrderDetails request, including importing required modules, creating an API client, and defining the OrderId and parameters. The params dict includes a ClientKey. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.portfolio as pf >>> import json >>> client = saxo_openapi.API(access_token=...) >>> OrderId = '76332324' >>> params = { "ClientKey": "Cf4xZWiYL6W1nMKpygBLLA==" } ``` -------------------------------- ### POST openapi/port/v1/balances/subscriptions Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/balances/BalanceSubscriptionCreate.rst Sets up a subscription for balance data and returns an initial snapshot. This endpoint is used to create a new balance subscription, providing real-time updates on account balances and related metrics. ```APIDOC ## [POST] openapi/port/v1/balances/subscriptions ### Description Set up a subscription and returns an initial snapshot of a balance. ### Method POST ### Endpoint openapi/port/v1/balances/subscriptions ### Parameters #### Request Body - **data** (dict) - Required - dict representing the data body parameters ### Response #### Success Response (201) - **ContextId** (string) - The context ID of the subscription. - **Format** (string) - The format of the response data. - **InactivityTimeout** (integer) - Timeout in seconds for inactivity. - **ReferenceId** (string) - The reference ID of the subscription. - **RefreshRate** (integer) - The refresh rate in milliseconds. - **Snapshot** (object) - The initial snapshot of the balance. - **State** (string) - The state of the subscription. ### Request Example ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.portfolio as pf >>> import json >>> client = saxo_openapi.API(access_token=...) >>> data = { "Arguments": { "ClientKey": "Cf4xZWiYL6W1nMKpygBLLA==" }, "ContextId": "explorer_1551792578055", "ReferenceId": "U_452" } ``` ### Response Example ```default { "ContextId": "explorer_1551792578055", "Format": "application/json", "InactivityTimeout": 30, "ReferenceId": "U_452", "RefreshRate": 1000, "Snapshot": { "CalculationReliability": "Ok", "CashBalance": 999956.74, "ChangesScheduled": false, "ClosedPositionsCount": 0, "CollateralCreditValue": { "Line": 979847, "UtilzationPct": 0 }, "CostToClosePositions": -37.54, "Currency": "EUR", "CurrencyDecimals": 2, "InitialMargin": { "MarginAvailable": 979847, "MarginUsedByCurrentPositions": -17733.77, "MarginUtilizationPct": 1.78, "NetEquityForMargin": 997580.77 }, "IsPortfolioMarginModelSimple": true, "MarginAvailableForTrading": 979847, "MarginCollateralNotAvailable": 0, "MarginExposureCoveragePct": 140.63, "MarginNetExposure": 709350.7, "MarginUsedByCurrentPositions": -17733.77, "MarginUtilizationPct": 1.78, "NetEquityForMargin": 997580.77, "NetPositionsCount": 3, "NonMarginPositionsValue": 0, "OpenPositionsCount": 3, "OptionPremiumsMarketValue": 0, "OrdersCount": 1, "OtherCollateral": 0, "TotalValue": 997580.77, "TransactionsNotBooked": 0, "UnrealizedMarginClosedProfitLoss": 0, "UnrealizedMarginOpenProfitLoss": -2338.43, "UnrealizedMarginProfitLoss": -2338.43, "UnrealizedPositionsValue": -2375.97 }, "State": "Active" } ``` ``` -------------------------------- ### ClientDetailsByOwner response example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/portfolio/clients/ClientDetailsByOwner.rst Example JSON response containing client details such as ClientId, ClientKey, DefaultCurrency, and legal asset types. ```default { "Data": [ { "AccountValueProtectionLimit": 10000, "ClientId": "9226397", "ClientKey": "Cf4xZWiYL6W1nMKpygBLLA==", "CurrencyDecimals": 2, "DefaultAccountId": "9226397", "DefaultAccountKey": "Cf4xZWiYL6W1nMKpygBLLA==", "DefaultCurrency": "EUR", "IsMarginTradingAllowed": true, "IsVariationMarginEligible": false, "LegalAssetTypes": [ "FxSpot", "FxForwards", "FxVanillaOption", "FxKnockInOption", "FxKnockOutOption", "FxOneTouchOption", "FxNoTouchOption" ], "LegalAssetTypesAreIndicative": false, "Name": "F. Brekeveld", "PositionNettingMode": "EndOfDay", "SupportsAccountValueProtectionLimit": true } ] } ``` -------------------------------- ### GetSessionCapabilities request example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/rootservices/sessions/GetSessionCapabilities.rst Shows how to instantiate and send a GetSessionCapabilities request using the saxo_openapi client. The example imports the required modules, creates an API client with an access token, sends the request, and prints the response. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.rootservices as rs >>> import json >>> client = saxo_openapi.API(access_token=...) >>> r = rs.sessions.GetSessionCapabilities() >>> rv = client.request(r) >>> print(rv) ``` -------------------------------- ### Setup params with ClientDetailsMe Source: https://github.com/hootnot/saxo_openapi/blob/master/jupyter/balances.ipynb Sets up the params dictionary for the AccountBalances request by first retrieving the ClientKey via ClientDetailsMe. ```python r = pf.clients.ClientDetailsMe() rv = client.request(r) params = { 'ClientKey': rv['ClientKey'] } ``` -------------------------------- ### ChangeOrder response output example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/trading/orders/ChangeOrder.rst Example of the response returned by the ChangeOrder request, containing the OrderId of the changed order. ```default { "OrderId": "76289286" } ``` -------------------------------- ### User request example Source: https://github.com/hootnot/saxo_openapi/blob/master/docs/endpoints/rootservices/user/User.rst Instantiate a User request and send it using the API client. The response is printed as JSON. ```pycon >>> import saxo_openapi >>> import saxo_openapi.endpoints.rootservices as rs >>> import json >>> client = saxo_openapi.API(access_token=...) >>> r = rs.user.User() >>> rv = client.request(r) >>> print(rv) ```