How save the messages from the websocket server using R?

I am using following file to connect to the Elektron service websocketr (1).txt This file is based on the following link https://github.com/Refinitiv/websocket-api/blob/master/Applications/Examples/R/market_price_authentication.R

I got a message (with bid and ask prices) with the output from the server like:


> ws$connect()
Connection opened
send login request
Got Message [{"ID":1,"Type":"Refresh","Domain":"Login","Key":{"Name":"","Elements":{"AllowSuspectData":1,"ApplicationId":"256","ApplicationName":"ADS","AuthenticationErrorCode":0,"AuthenticationErrorText":{"Type":"AsciiString","Data":null},"AuthenticationTTReissue":xxx,"Position":"xxx","ProvidePermissionExpressions":1,"ProvidePermissionProfile":0,"SingleOpen":1,"SupportEnhancedSymbolList":1,"SupportOMMPost":1,"SupportPauseResume":0,"SupportStandby":0,"SupportBatchRequests":7,"SupportViewRequests":1,"SupportOptimizedPauseResume":0}},"State":{"Stream":"Open","Data":"Ok","Text":"Login accepted by host ads-premium-az1-blue-15-main-prd.euw1-az1."},"Elements":{"PingTimeout":30,"MaxMsgSize":61430}}] 
Single Message 
{"ID":2,"Key":{"Name":"xxx"},"View":["BID","ASK"]}
Got Message [{"ID":2,"Type":"Refresh","Key":{"Service":"ELEKTRON_DD","Name":"xxx"},"State":{"Stream":"Open","Data":"Ok","Text":"*All is well"},"Qos":{"Timeliness":"Realtime","Rate":"JitConflated"},"PermData":"xxx","SeqNumber":xxx,"Fields":{"BID":16.300,"ASK":16.345}}] 
Single Message 
Got Message [{"Type":"Ping"}] 
Single Message


How can I save the output seen in the console to the datatrame/ or csv file, or better if for every refresh token(every 5 min) a file with the output is saved to the computer memory. it seems that ws$onMessage or process_message() functions should be slightly modified, but do not understand how. Could you help?

Best Answer

  • Gurpreet
    Answer ✓

    Hi @g.suhharukov,

    The messages from websocket API are in the JSON format, which is a nested message format unlike CSV. Your application you will have to parse the JSON and need to pick a branch which represents the tabular data that it needs. This tabular data can then be loaded into a Dataframe or written to a file as CSV. For e.g. in the data message you received, the Fields key contains this data.

    DataFrame(jMsg[0]['Fields'])

    See this question on loading JSON into DF: https://stackoverflow.com/questions/36454638/how-can-i-convert-json-to-data-frame-in-r

Answers