Python example to handle on_close in ERP websocket
hi there,
we are trying to use the websocket API example you are providing to the community, but we face often some disconnects, and the method on_close is getting called. Iwould like to get some help here on what to do when this happens, is there somehow an easy way to reconnect ?
Could you provide me with a python example that handles such a situation when on_close() is called, as i would like to immediately reconnect?
In my code, i try to send a new authentification request with get_sts_token() but this is crashing, we get a 'WebSocketConnectiononClosedException: Connection is already closed.'
Any help and code python is welcome
Thank you
Best Answer
-
Yes, the Python example code is only to get users started quickly with API, and cannot handle every exception scenario that an application might encounter in production.
Here is a quick change that I tried and it works for if the websocket gets disconnected. You will have to make similar change in your application and check it for errors and robustness. There are a lot of assumptions built in - like your network has recovered and target machine is available for connections:
def on_close(_):
""" Called when websocket is closed """
global web_socket_open
web_socket_open = False
print("WebSocket Closed")
time.sleep(10)
print("Restarting...")
start()
def start():
global sts_token, refresh_token, expire_time
sts_token, refresh_token, expire_time = get_sts_token(None)
if not sts_token:
sys.exit(1)
# Start websocket handshake
ws_address = "wss://{}:{}/WebSocket".format(hostname, port)
print("Connecting to WebSocket " + ws_address + " ...")
web_socket_app = websocket.WebSocketApp(ws_address, on_message=on_message,
on_error=on_error,
on_close=on_close,
subprotocols=['tr_json2'])
web_socket_app.on_open = on_open
# Event loop
wst = threading.Thread(target=web_socket_app.run_forever, kwargs={'sslopt': {'check_hostname': False}})
wst.start()
try:
while True:
# Give 30 seconds to obtain the new security token and send reissue
if int(expire_time) > 30:
time.sleep(int(expire_time) - 30)
else:
# Fail the refresh since value too small
sys.exit(1)
sts_token, refresh_token, expire_time = get_sts_token(refresh_token)
if not sts_token:
sys.exit(1)
# Update token.
if logged_in:
send_login_request(web_socket_app, sts_token, True)
except KeyboardInterrupt:
web_socket_app.close()0
Answers
-
@Mehdi_deprecated_0, which exact example are you using; seems like you are connecting to an EDP cloud instance. We should also focus on why the websocket is disconnecting in the first place, and then put a re-connection logic to recover from any disconnect.
0 -
Hi Gurpreet,
why is the websocket disconnecting so frequently is a mystery to me. It happened again twice over the last 15h and i raised already a ticket about this. Did the EDP cloud instance face some issues? I am still waiting for the results of this investigation.
To answer your question, I have taken the available python examples from your API documentation and tutorials, and re written my application around it.
It is a real pity that the available python code examples you are providing do not handle the on_close case properly. What should that i do in this method to automatically reconnect?
def on_close(ws):
""" Called when websocket is closed """
global web_socket_open
print("WebSocket Closed")
web_socket_open = False0
Categories
- All Categories
- 3 Polls
- 6 AHS
- 36 Alpha
- 166 App Studio
- 6 Block Chain
- 4 Bot Platform
- 18 Connected Risk APIs
- 47 Data Fusion
- 34 Data Model Discovery
- 684 Datastream
- 1.4K DSS
- 615 Eikon COM
- 5.2K Eikon Data APIs
- 10 Electronic Trading
- Generic FIX
- 7 Local Bank Node API
- 3 Trading API
- 2.9K Elektron
- 1.4K EMA
- 249 ETA
- 554 WebSocket API
- 37 FX Venues
- 14 FX Market Data
- 1 FX Post Trade
- 1 FX Trading - Matching
- 12 FX Trading – RFQ Maker
- 5 Intelligent Tagging
- 2 Legal One
- 23 Messenger Bot
- 3 Messenger Side by Side
- 9 ONESOURCE
- 7 Indirect Tax
- 60 Open Calais
- 275 Open PermID
- 44 Entity Search
- 2 Org ID
- 1 PAM
- PAM - Logging
- 6 Product Insight
- Project Tracking
- ProView
- ProView Internal
- 22 RDMS
- 1.9K Refinitiv Data Platform
- 643 Refinitiv Data Platform Libraries
- 4 LSEG Due Diligence
- LSEG Due Diligence Portal API
- 4 Refinitiv Due Dilligence Centre
- Rose's Space
- 1.2K Screening
- 18 Qual-ID API
- 13 Screening Deployed
- 23 Screening Online
- 12 World-Check Customer Risk Screener
- 1K World-Check One
- 46 World-Check One Zero Footprint
- 45 Side by Side Integration API
- 2 Test Space
- 3 Thomson One Smart
- 10 TR Knowledge Graph
- 151 Transactions
- 143 REDI API
- 1.8K TREP APIs
- 4 CAT
- 26 DACS Station
- 121 Open DACS
- 1.1K RFA
- 104 UPA
- 192 TREP Infrastructure
- 228 TRKD
- 915 TRTH
- 5 Velocity Analytics
- 9 Wealth Management Web Services
- 90 Workspace SDK
- 11 Element Framework
- 5 Grid
- 18 World-Check Data File
- 1 Yield Book Analytics
- 46 中文论坛