I want to use some websocket streams of the Binance API. I am posting this here because I think this isn't an issue with the API, but rather my understanding of websockets in general.
I try to subscribe to a stream as the official gorilla/websocket example describes:
conn, res, err := websocket.DefaultDialer.Dial("wss://stream.binance.com/ws/BTCUSD@markPrice", nil)
fmt.Println(conn)
fmt.Println(res)
fmt.Println(err)
for {
_, message, readErr := conn.ReadMessage()
if readErr != nil {
fmt.Println(readErr)
return
}
fmt.Println(message)
}
The connection is created without errors, but after that, no message gets read.
I think the problem is that the API demands me to subscribe to a stream like so:
{
"method": "SUBSCRIBE",
"params": [
"btcusdt@aggTrade",
"btcusdt@depth"
],
"id": 1
}
I am aware that a websocket connection starts out with one HTTP request where, as far as I understood, I send this data. But where and when am I supposed to do so? Dial doesn't give the option to send anything apart from HTTP headers.
UPDATE:
I managed to send the right request and get the right response as documented here by using Conn.WriteJSON:
type request struct {
Method string `json:"method"`
Params [1]string `json:"params"`
ID int `json:"id"`
}
markPriceReq := request{"SUBSCRIBE", [1]string{"btcusdt@markPrice"}, 1}
conn.WriteJSON(markPriceReq)
However, after the initial response no data gets read anymore. Where do I get the actual mark price data from?