How to implement RKD JSON application with Python chapter 2: Quote
RKD Overview
The Refinitiv Knowledge Direct (RKD) API (formerly known as TRKD API) integrates into your website, trading platform, company intranet/extranet, advisory portal and mobile applications to provide up-to-date financial market data, news and analytics and powerful investment tools.
RKD offers a wide range of Refinitiv' information and services delivered in a request-response scenario via web services using today's industry standard protocols (SOAP/XML and REST/JSON). Connectivity can be via HTTP and HTTPS, over the Internet or Delivery Direct. All data are snapshot (non-streaming) data.
With new HTTP JSON services, developers can integrate RKD information to their application easier then before. This article provides an information regarding the basic knowledge of how to implement RKD JSON application to consume Quote data with Python language.
RKD Quote Service Overview
The Quotes service (RKD RetriveItem3 endpoint) enables you to retrieve a snapshot quote or a quote chain data. RKD API delivers snapshot prices only; you may not deliver streaming prices using RKD API. By default RKD provides delayed stock prices. However, if your organization has an agreement within an exchange to provide its prices in real-time, then real-time snapshot prices can be delivered by RKD for that exchange.
The Quotes service requires the Application ID and Service Token information from RKD Service Token in the request message’s header.
Note: Up to 75 instruments and 25 fields may be included in each request.
RKD JSON Application Implementation Process
The JSON application requires the following steps to consume data from RKD API services
- Authentication with RKD Authentication service (RKD Service Token) to get an service token
- Send a request message with the required input information with servicetoken and application id in the request header to the interested RKD service
RKD Quote Detail
RKD RetriveItem3 URL and Header
The URL enponint for the RKD Quote Service is following: https://api.rkd.refinitiv.com/api/Quotes/Quotes.svc/REST/Quotes_1/RetrieveItem_3
Header:
- Content-type = application/json;charset=utf-8
- X-Trkd-Auth-ApplicationID = Application ID
- X-Trkd-Auth-Token = Service Token
Method:
- Post
RKD RetriveItem3 Request Message
The RKD Quote RetrieveItem_3 operation request message is in JSON format. The message requires an item name (Symbol) as a mandatory input. If the fields information is not specify and "Scope" parameter value is "All", the request will be all fields data request message. The application can request specific fields data by using “:” string as a separator for each field (example “BID:ASK:CF_LAST”) in the "Fields" parameter with "Scope" parameter value "List".
An example of all fields request message structure is following
{
“RetrieveItem_Request_3”:{
“TrimResponse”: false,
“ItemRequest”: {
[{
“RequestKey”: [{“Name”: <Item Name>, “NameType”: “RIC”}],
“Fields”: <Field Names, separate each field with ‘:’>,
“Scope”: “All”,
“ProvideChainLinks”: true
}]
}
}
An example of the request message with specific fields subscription is shown below
{
"RetrieveItem_Request_3": {
"TrimResponse": false,
"ItemRequest": [{
"Fields": "CF_LAST:CF_HIGH:CF_LOW:CF_BID:CF_ASK:CF_YIELD",
"RequestKey": [{
"Name": "MSFT.O",
"NameType": "RIC"
}],
"Scope": "List",
"ProvideChainLinks": true
}]
}
}
"trkd_quote.py" Example Application
RKD API Quote service provides a snapshot (non-streaming) quote data for the application. To retreive quote data, your application must send a request message in JSON formation along with an authenticated credentials (Service Token) and application id information in a request message header.
This section describes how to implement the trkd_quote.py script that performs authentication with the TRDK Service Token, then requests for quote data with all fields or specific fields based on user input via a command line.
IMPLEMENTATION DETAILS
- Firstly, we create a file named “trkd_quote.py” in the working directory. Then we import all required libraries at the top of the source code
import os
import sys
import requests
import json
import getpass
2. Since this application needs to send multiple HTTP request messages to RKD Services (for authentication and request quote data), we will separate the HTTP request source code to the dedicate function call instead. We start by creating the doSendRequest() function which receives three parameters: the requested URL, request message and request message's header. This function sends the JSON request message to the URL and returns the HTTP response from the URL to the caller via the result parameter. If the HTTP response message status code is not 200 (200 OK), it shows the error detail.
# Send HTTP request for all services
def doSendRequest(url, requestMsg, headers):
result = None
try:
##send request
result = requests.post(url, data=json.dumps(requestMsg), headers=headers)
## handle error
if result.status_code is not 200:
print('Request fail')
print('response status %s'%(result.status_code))
if result.status_code == 500: ## if username or password or appid is wrong
print('Error: %s'%(result.json()))
result.raise_for_status()
except requests.exceptions.RequestException as e:
print('Exception!!!')
print(e)
sys.exit(1)
return result
3. Next, Then we add the code to receive the input user name, password and application id from a console
## ------------------------------------------ Main App ------------------------------------------ ##
##Get username, password and applicationid
username = raw_input('Please input username: ')
##use getpass.getpass to hide user inputted password
password = getpass.getpass(prompt='Please input password: ')
appid = raw_input('Please input appid: ')
4. Next, we create the CreateAuthorization() function to manage and handle RKD authentication process. We pass user name, password and application id information to the function, then print out the Service Token from RKD in the console.
## Perform authentication
def CreateAuthorization(username, password, appid):
token = None
return token
## ------------------------------------------ Main App ------------------------------------------ ##
... #code from previous step
token = CreateAuthorization(username,password,appid)
print('Token = %s'%(token))
5. In the CreateAuthorization() function, we create the authentication (authenMsg), the url (authenURL) and headers variables
## Perform authentication
def CreateAuthorization(username, password, appid):
token = None
##create authentication request URL, message and header
authenMsg = {'CreateServiceToken_Request_1': { 'ApplicationID':appid, 'Username':username,'Password':password }}
authenURL = 'https://api.rkd.refinitiv.com/api/TokenManagement/TokenManagement.svc/REST/Anonymous/TokenManagement_1/CreateServiceToken_1'
headers = {'content-type': 'application/json;charset=utf-8'}
6. Next, we send this authentication request message, URL and header to the doSendRequest() function. Once the application receives the response Service Token, we send the incoming Service Token back to the caller to prints out the token.
##Perform authentication
def CreateAuthorization(username, password, appid):
... #code froma previouse step
print('############### Sending Authentication request message to RKD ###############')
authenResult = doSendRequest(authenURL, authenMsg, headers)
if authenResult and authenResult.status_code == 200:
print('Authen success')
print('response status %s'%(authenResult.status_code))
##get Token
token = authenResult.json()['CreateServiceToken_Response_1']['Token']
return token
7. After we received the Service Token and that Token is not None, we pass the Service Token and application id to the RetreiveQuotes() function for requesting the Quote data.
## Perform Quote request
def RetrieveQuotes(token, appid):
pass #will be implemented in the next step
##------------------------------------------ Main App ------------------------------------------##
token = CreateAuthorization(username,password,appid)
print('Token = %s'%(token))
## if authentiacation success, continue subscribing Quote
if token:
RetrieveQuotes(token,appid)
8. The RetrieveQuotes() creates the Quote request message and sends it to the RKD RetrieveItem_3 servuce via doSendRequest() function. The code prints the incoming Quote response to the console. Please note that we will show how to create the Quote request message in the next step.
##Perform Quote request
def RetrieveQuotes(token, appid):
quoteRequestMsg = None
#create quote request message
quoteURL = 'https://api.rkd.refinitiv.com/api/Quotes/Quotes.svc/REST/Quotes_1/RetrieveItem_3'
headers = {'content-type': 'application/json;charset=utf-8' ,'X-Trkd-Auth-ApplicationID': appid, 'X-Trkd-Auth-Token' : token}
print('############### Sending Quote request message to RKD ###############')
quoteResult = doSendRequest(quoteURL, quoteRequestMsg,headers)
if quoteResult and quoteResult.status_code == 200:
print('Quote response message: ')
print(quoteResult.json())
9. The following steps aim for creating the Quote request message in JSON format that supports both all fields and specific fields request. Firstly, we get the user input for the Item name (Symbol) and All field (yes or no) information via the console. We also define a fieldName variable with the default field names value for the field subscription.
##Perform Quote request
def RetrieveQuotes(token, appid):
ricName = raw_input('Please input Symbol: ')
fieldFiltering = raw_input('Subscribe all Field? (Yes|No)')
quoteRequestMsg = None
fieldsName = 'CF_LAST:CF_HIGH:CF_LOW:CF_BID:CF_ASK:CF_YIELD:CF_SOURCE:CF_SRC_PAGE:CF_LOTSIZE:CF_DATE:CF_TIME:CF_TICK:CF_NETCHNG:CF_EXCHNG:CF_VOLUME:CF_CLOSE:CF_OPEN:CF_NAME:CF_CURRENCY'
10. Next, we create the Quote request message for the all field subscription (fieldFiltering variable = “Yes”)
##Perform Quote request
def RetrieveQuotes(token, appid):
...
if fieldFiltering == 'Yes':
## Request all Fields
quoteRequestMsg = \
{'RetrieveItem_Request_3': {'TrimResponse': False,
'ItemRequest': [{'RequestKey': [{'Name': ricName, 'NameType': 'RIC'}], 'Scope': 'All',
'ProvideChainLinks': True}]}}
11. Then we create the Quote request message for the specific fields subscription (fieldFiltering variable = “No”). The source code get user's interested fields from command line.
##Perform Quote request
def RetrieveQuotes(token, appid):
...
if fieldFiltering == 'Yes':
##Request all Fields
...
elif fieldFiltering == 'No':
##Request specific Fields
fieldsName = raw_input('Input interested Field Name in the following format (BID:ASK:TRDPRC_1)')
quoteRequestMsg = \
{'RetrieveItem_Request_3': {'TrimResponse': False,
'ItemRequest': [{
'RequestKey': [{'Name': ricName, 'NameType': 'RIC'}],
'Fields': fieldsName,
'Scope': 'List',
'ProvideChainLinks': True
}]}}
Then the application supports both all field and specific field subscription.
Running the application
The application source code is available at GitHub. You can get it via the following git command
$>git clone git@github.com:Refinitiv-API-Samples/Example.TRKD.Python.HTTPJSON.git
$>python trkd_quote.py
Then input your user name, password and application id. The result is shown in the Figure-1 below
Figure-1: The trkd_quote receives user name, password and application id via commandline
Then, input interested Symbol and whether user wants to subscribe all fields data or not ("Yes" or "No")
Figure-2: The trkd_quote asks for interested Symbol and Field subscription
If user subscribes all field data from RKD, RKD Quote service returns all fields data for the subscription item to the application
Figure-3: The trkd_quote all fields subscription result
If user wants only specific field data ("No" in previous step), the application lets user inputs interested field name by using colon (":") as a separator.
Figure-4: user inputs interested field name via a command line
Then the application subscribes only specific fields for user from RKD and display data in console.
Figure-5: RKD Quote result for BID and ASK fields
Conclusion
RKD Quote Service provides static quote data for users. It supports both all fields and specific fields data. Users need to authenticate permission with RKD Service Token first, then send the quote request message with Service Token and App ID in the request message header.
References
For further details, please check out the following resources:
- Refinitiv Knowledge Direct API page on the Refinitiv Developer Community web site.
- Refinitiv Knowledge Direct API Catalog web site.
For any question related to this article or Elektron WebSocket API page, please use the Developer Community Q&A Forum page.