Trouble getting streaming data via https:// upgrade to wss://
lassehjorthmadsen opened this issue · 0 comments
I'm trying to use websocket
for getting streaming data in an API wrapper package that I'm working on.
My use case is to get stock prices from a streaming endpoint, using the common workflow of creating a subscriprtion, then receiving streams of data from that subscription.
My provider is Saxo Bank, their API documentation for streams is here, whith this section being the most relevant.
The idea is to send a GET request to an endpoint, including a contextId. With headers Connection: Upgrade
and Upgrade: WebSocket
, the connection upgrades to the WebSocket protocol, wss://
. However, I can't seem to implement that workflow using websocket
. Either I'm doing something wrong, there is a bug, or this is not implemented in websocket
?
Code snippet below produces a stream of error messages llike this:
[2022-12-02 10:35:30] [error] Server handshake response error: websocketpp.processor:20 (Invalid HTTP status.)
[2022-12-02 10:35:30] [info] asio async_shutdown error: asio.ssl.stream:1 (stream truncated)
[2022-12-02 10:37:46] [error] handle_read_frame error: asio.ssl.stream:1 (stream truncated)
[2022-12-02 10:37:46] [info] asio async_shutdown error: asio.ssl.stream:1 (stream truncated)
Any help much appreciated.
Code:
library(dplyr)
library(httr2)
library(websocket)
# 24 hour token for simulation environment
token24 <- MY_TOKEN
contextId <- "aUv1j3U-Or3" # Arbitrary string, for identification
# Create subscription for a specific stock
req <-
request("https://gateway.saxobank.com/sim/openapi/trade/v1/prices/subscriptions") %>%
req_body_json(data = list(
"Arguments" =
list("Uic" = 15611,
"AssetType" = "Stock"),
"ContextId" = ContextId,
"ReferenceId" = "5MolAro8Zz")) %>%
req_headers(Authorization = paste("BEARER", token24))
r <- req %>% req_perform() # Works so far, subscription created
# Using contextId, create wss connection:
endpoint <- "wss://streaming.saxobank.com/sim/openapi/streamingws/connect"
url <- paste0(endpoint, "?contextId=", contextId)
ws <- WebSocket$new(url)
{
ws <- WebSocket$new(url)
ws$onMessage(function(event) {
d <- event$data
if (d != "Connected") {
js = fromJSON(d)
print(js)
}
})
ws$onOpen(function(event) {
ws$send(paste0("\"contextId\":\"", contextId, "\"}"))
cat("Connection opened\n")
})
}