Dennis
Dennis

Reputation: 79

Struggling with receiving data through WebSocket API

I'm trying to connect to exchange.blockchain.com server using their API. Here is the official documentation if you want to check it. I'm working on a simple python script to receive Bitcoin prices every x seconds. Note: the API has a limit of 1,200 request per minute. Here is the first part of my code:

from websocket import create_connection
options = {}
options['origin'] = 'https://exchange.blockchain.com'
url = "wss://ws.prod.blockchain.info/mercury-gateway/v1/ws"
ws = create_connection(url, **options)
msg = '{"token": "{API_SECRET}", "action": "subscribe", "channel": "auth"}'
ws.send(msg)
result =  ws.recv()
print(result)
ws.close()

I receive the following output:

{ "seqnum":0,
  "event":"subscribed",
  "channel":"auth",
  "readOnly":false }

So far everything is correct. Now the official documentation says that I have to suscribe to the channel prices to receive market data, so:

msg = {
     "action": "subscribe",
     "channel": "prices",
     "symbol": "BTC-USD",
     "granularity": 60
      }

ws.send(str(msg))
result =  ws.recv()
print(result)
ws.close()

Output is:

{
  "seqnum": 0,
  "event": "subscribed",
  "channel": "prices",
  "symbol": "BTC-USD"
}

Everything is fine but, according to the documentation I'm suppose to receive also the following output with the data requested through the channel

{
  "seqnum": 2,
  "event": "updated",
  "channel": "prices",
  "symbol": "BTC-USD",
  "price": [1559039640, 8697.24, 8700.98, 8697.27, 8700.98, 0.431]
}

Of course, my problem is that I'm not receiving the last and most important part of the output. I think this is because I don't know how an API and socket works. Therefore, I'm missing something in my code. What is it?

Upvotes: 0

Views: 453

Answers (1)

alt-f4
alt-f4

Reputation: 2326

I don't know about this API specifically, but it looks to me like you recieve the first response from the api, shown by:

{
  "seqnum": 0,
  "event": "subscribed",
  "channel": "prices",
  "symbol": "BTC-USD"
}

And then you exit before receiving the updates.

You need to keep the connection open to continue receiving the updates. Perhaps you can try something like:

import websockets as ws
import asyncio
async def givme_bitcoins(websocket): # takes in the ws connection object
    while True:
        try:
            data = await websocket.recv()
        except ws.ConnectionClosed:
            print(f"Terminated")
            break

        print(data)



async def main():
    try:
        await asyncio.wait([givme_bitcoins(URL)])
    except Exception as e:
        raise e


if __name__ == "__main__":
    asyncio.run(main())

To explain the previous snippet, the general idea is that we open an asynchronous connection through websockets, and we continue to send/receive data with the API.For this code to work, you still need to do the saem process in your code, as in: authenticated, subscribe to channels...etc.).

Upvotes: 1

Related Questions