Skip to content

Commit b70a24a

Browse files
author
Wasin Waeosri
committed
Change logs:
1. Revise trkd_wsstreaming.py to let shorter variable names 2. Add comment for trkd_wsstreaming.py 3. Update README.md file 4. Add LICENSE.md file
1 parent 72bd127 commit b70a24a

File tree

3 files changed

+47
-28
lines changed

3 files changed

+47
-28
lines changed

LICENSE.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Copyright 2018 Refinitiv
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.

README.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,10 @@ This is an example project that shows how to implement TRKD HTTP JSON client and
1414
- trkd_onlinereport.py: An example application that shows how to subscribe the Online Report data from TRKD service
1515
- trkd_chart.py: An example application that shows how to subscribe and download the Chart image data from TRKD service
1616
- trkd_wsstreaming.py: An example application that show how to subscribe the Quote data from TRKD Streming service via a WebSocket connection
17-
- requestments.txt: A requirement file contains a list of required libraries.
17+
- requestments.txt: A requirement file contains a list of required libraries for HTTP JSON and WebSocket connections.
1818
- docs\TRKD_REST_with_Python.docx: A document that describes the trkd_authen.py and trkd_quote.py applications
1919

20+
All source code and scripts are provided under the Apache 2.0 license. Thye are provided AS IS with no warranty or guarantee of fit for purpose. See the project's LICENSE.md for details.
2021

2122
## Prerequisite
2223
The following softwares are required to use this script
@@ -46,7 +47,13 @@ The best way is via the pip package management tool
4647
$>pip install -r requestments.txt
4748
```
4849

49-
*Note*: If you aim to use only TRKD HTTP JSON services, you can just install requests library via ```pip install requests``` command.
50+
*Note*: If you aim to use only TRKD HTTP JSON services, you can just install requests library via a ```pip install requests``` command.
51+
52+
## References
53+
For further details, please check out the following resources:
54+
* [Thomson Reuters Knowledge Direct API page](https://developers.thomsonreuters.com/thomson-reuters-knowledge-direct-trkd) on the [Thomson Reuters Developer Community](https://developers.thomsonreuters.com/) web site.
55+
* [Thomson Reuters Knowledge Direct API Catalog](https://www.trkd.thomsonreuters.com/SupportSite/RequestBuilder/requestbuilder.aspx) web site.
56+
* [Elektron WebSocket API](https://developers.thomsonreuters.com/websocket-api) page on the [Thomson Reuters Developer Community](https://developers.thomsonreuters.com/) web site.
5057

5158
## Release Note
5259
- Version 1: 6 Sep 2016
@@ -85,3 +92,4 @@ The best way is via the pip package management tool
8592
- remove all ```is not None``` statements and make them a bit more **Pythonic**.
8693
- version 1.0.11: January 2019
8794
- Add trkd_wsstreaming.py application for TRKD Streaming service.
95+
- Add License.md file

trkd_wsstreaming.py

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@
4141

4242
ric_name = 'EUR='
4343

44-
expire_time_in_seconds = None
45-
time_before_expire_in_seconds = 15 * 60 # 15 Minutes to Seconds
44+
expire_time = 0
45+
time_to_relogin = 15 * 60 # 15 Minutes to Seconds
4646

4747
## ------------------------------------------ TRKD HTTP REST functions ------------------------------------------ ##
4848

@@ -85,15 +85,16 @@ def CreateAuthorization(username, password, appid):
8585

8686
## Calcuate Expiration time
8787
expire_datetime_utc = dateutil.parser.parse(expiration) ## Parse incoming Expiration to Python datetime object (UTC)
88-
utc_time_now = datetime.now(timezone.utc) ## Get current machine datetime in UTC
88+
now_datetime_utc = datetime.now(timezone.utc) ## Get current machine datetime object in UTC
8989

90-
time_difference = expire_datetime_utc - utc_time_now ## Get time different between now and expiration time value
91-
time_difference_in_seconds = int(round(time_difference / timedelta(seconds=1))) ## convert it to second as a round int
90+
expire_time = expire_datetime_utc - now_datetime_utc ## Get time different between now and expiration time value
91+
expire_time = int(round(expire_time / timedelta(seconds=1))) ## convert it to second as a round int
9292

93-
return token, expiration, time_difference_in_seconds
93+
return token, expiration, expire_time
9494

9595
## ------------------------------------------ TRKD WebSocket functions ------------------------------------------ ##
9696

97+
# Process incoming messages from TRKD Elektron WebSocket Server
9798
def process_message(message_json):
9899
""" Parse at high level and output JSON of message """
99100
message_type = message_json['Type']
@@ -103,21 +104,22 @@ def process_message(message_json):
103104
message_domain = message_json['Domain']
104105
if message_domain == "Login":
105106
process_login_response(message_json)
106-
elif message_type == "Ping":
107-
pong_json = { 'Type':'Pong' }
107+
# Ping and Pong messages are exchanged between endpoints of a connection to verify that the remote endpoint is still alive.
108+
elif message_type == "Ping":
109+
pong_json = { 'Type':'Pong' } # when either endpoint receives a Ping message, it should send a Pong message in response.
108110
web_socket_app.send(json.dumps(pong_json))
109111
print("SENT:")
110112
print(json.dumps(pong_json, sort_keys=True, indent=2, separators=(',', ':')))
111113

112-
114+
# Process incoming Login Refresh message from TRKD Elektron WebSocket Server
113115
def process_login_response(message_json):
114116
""" Send item request """
115117
global logged_in
116118

117119
logged_in = True
118120
send_market_price_request(ric_name)
119121

120-
122+
# Send JSON OMM Market Price Request message to TRKD Elektron WebSocket Server
121123
def send_market_price_request(ric_name):
122124
""" Create and send simple Market Price request """
123125
mp_req_json = {
@@ -130,7 +132,7 @@ def send_market_price_request(ric_name):
130132
print("SENT:")
131133
print(json.dumps(mp_req_json, sort_keys=True, indent=2, separators=(',', ':')))
132134

133-
135+
# Send JSON OMM Login Request message to TRKD Elektron WebSocket Server to initiate the OMM connection
134136
def send_login_request(is_refresh_token=False):
135137
""" Generate a login request from command line data (or defaults) and send """
136138
login_json = {
@@ -160,7 +162,7 @@ def send_login_request(is_refresh_token=False):
160162
print("SENT:")
161163
print(json.dumps(login_json, sort_keys=True, indent=2, separators=(',', ':')))
162164

163-
165+
# Receive every messages from TRKD Elektron WebSocket Server
164166
def on_message(_, message):
165167
""" Called when message received, parse message into JSON for processing """
166168
print("RECEIVED: ")
@@ -182,7 +184,7 @@ def on_close(_):
182184
print("WebSocket Closed")
183185
web_socket_open = False
184186

185-
187+
# Establish a WebSocket connection success
186188
def on_open(_):
187189
""" Called when handshake is complete and websocket is open, send login """
188190

@@ -200,10 +202,10 @@ def on_open(_):
200202
password = getpass.getpass(prompt='Please input password: ')
201203
appid = input('Please input appid: ')
202204

203-
token, expiration, expire_time_in_seconds = CreateAuthorization(username,password,appid)
205+
token, expiration, expire_time = CreateAuthorization(username,password,appid)
204206
print('Token = %s'%(token))
205207
print('Expiration = %s'%(expiration))
206-
print('Expiration in next = %d seconds'%(expire_time_in_seconds))
208+
print('Expiration in next = %d seconds'%(expire_time))
207209
## if authentiacation success, continue subscribing Quote
208210
if token and expiration:
209211
print('Do WS here')
@@ -215,30 +217,26 @@ def on_open(_):
215217
on_close=on_close,
216218
subprotocols=[ws_protocol])
217219
web_socket_app.on_open = on_open
218-
# for test
219220

220-
# expire_time_in_seconds = 120
221-
# time_before_expire_in_seconds = 15
222221
# Event loop
223222
wst = threading.Thread(target=web_socket_app.run_forever)
224223
wst.start()
225224

226225
try:
227226
while True:
228-
#time.sleep(1)
229-
if (expire_time_in_seconds > time_before_expire_in_seconds):
230-
time.sleep(expire_time_in_seconds-time_before_expire_in_seconds)
227+
if (expire_time > time_to_relogin):
228+
time.sleep(expire_time - time_to_relogin) # Sleep Thread until 15 minutes before expiration
231229
else:
232230
# failt the refresh sine value too small
233231
sys.exit(1)
234-
token, expiration, expire_time_in_seconds = CreateAuthorization(username,password,appid)
235-
print('new Token = %s'%(token))
236-
print('new Expiration = %s'%(expiration))
237-
print('new Expiration in next = %d seconds'%(expire_time_in_seconds))
232+
233+
# Re-issue login request before token expiration to keep session open.
234+
token, expiration, expire_time = CreateAuthorization(username,password,appid)
238235
if not token:
239236
sys.exit(1)
240237
if logged_in:
241238
print('############### Re-new Authentication to TRKD ###############')
242-
send_login_request(is_refresh_token=True)
239+
# Resend JSON OMM Login Request message with Refresh: false to TRKD Elektron WebSocket Server
240+
send_login_request(is_refresh_token=True)
243241
except KeyboardInterrupt:
244242
web_socket_app.close()

0 commit comments

Comments
 (0)