pycoder
pycoder

Reputation: 23

web-socket client will not connect to an API

After searching the web for hours and asking the same question on Reddit with no success, I have decided to sign up to Stack Overflow and ask the question here.

I am currently following a tutorial to learn more about APIs. This specific tutorial is working with the Binance API to try to collect data about the BTC price in USD once every minute. To do this I have imported WebSocket-client to keep a steady connection and collect new data points once every minute, however whenever I run my code nothing happens. The console prints "Process finished with exit code 0", instead of actually connecting to the server and collecting data.

Here's my code:

import websocket

SOCKET = "wss://stream.binance.com:9443/ws/btcusdt@kline_1m"

def on_open(ws):
    print('connection: successful')

def on_close(ws):
    print('connection: lost')

def on_message(ws, message):
    print('message')

ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever()

At first, I thought I had the wrong WebSocket library installed (instead of WebSocket-client I thought I was using. the regular WebSocket library) however, I did not. Then I thought that maybe there was something wrong with PyCharm, so I ran the code in Visual Studio Code, Sublime Text, the Terminal, and Jupyter notebook, but none of them worked either.

Is there anything wrong with my code? I've attempted numerous edits but none of them have worked so far.

Binance API docs: https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md

The tutorial I am following: https://youtu.be/GdlFhF6gjKo?t=1112 (go to around 18:32 to see his code).

ps. I am a new programmer and just finished my first project (a* pathfinding algorithm) so don't be too harsh :).

Upvotes: 2

Views: 670

Answers (1)

user2668284
user2668284

Reputation:

Assuming this is the ubiquitous SSL error then do this:-

import websocket
import ssl

SOCKET = "wss://stream.binance.com:9443/ws/btcusdt@kline_1m"


def on_open(ws):
    print('connection: successful')

def on_close(ws, *args):
    print('connection: lost')

def on_message(ws, message):
    print('message')

def on_error(ws, message):
    print(message)

ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message, on_error=on_error)
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

Upvotes: 4

Related Questions