I'm trying to connect to the Binance stream but when I run the code it outputs: "closed connection". What can I do to join the stream?
import websocket
import json
socket = 'wss://fstream.binance.com/ws'
def on_open(ws):
subscribe_message = {"method": "SUBSCRIBE", "params":["btcusdt#trade"],"id": 1}
ws.send(json.dumps(subscribe_message))
def on_message(ws, message):
print("received a message")
print(json.loads(message))
def on_close(ws):
print("closed connection")
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message, on_close=on_close)
ws.run_forever()
Welcome to stackoverflow.
By looking at the wss://fstream.binance.com/ws, I can see that you are trying to connect to Futures API.
It clearly says in the API doc that any raw streams are accessed at /ws/<streamName>
you are not specifying the streamName in url that's why the error.
Just change the url to connect to correct stream & same code should work for you:
ws = websocket.WebSocketApp(socket + '/btcusdt#trade', on_open=on_open, on_message=on_message, on_close=on_close)
If it helps, please mark answer as accepted.
Related
I've successfully subscribed to the Bitstamp websocket and I'm now receiving live exchange data. Once I've parsed this data and assigned it to a variable (eg "asks"), how do I return this variable so that I can use it in other functions and other .py files?
Or do I have to do everything within the on_message() function? Thanks very much, code below:
import json
import requests
import websocket
SOCKET = "wss://ws.bitstamp.net/"
def on_open(ws):
print("opened connection")
subscription = {
"event": "bts:subscribe",
"data": {
"channel": "order_book_btcusd"
}
}
ws.send(json.dumps(subscription))
def on_close(ws):
print("closed connection")
def on_message(ws,message):
print(message)
data = json.loads(message)['data']
asks = float(bitstamp_data['asks'][0][0])
def on_error(ws,error):
print(error)
ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message,on_error=on_error)
ws.run_forever()
This is how I established a real-time price WebSocket price for Spot Market, but how do I get the real-time price for Futures BTCUSDT?
socket = f"wss://stream.binance.com:9443/ws/dotusdt#kline_1m"
def on_message(ws, message):
print(message)
def on_close(ws):
print("Connection closed")
ws = websocket.WebSocketApp(socket, on_message=on_message, on_close=on_close)
Looked for answers but couldn't find any favorable ones. Thanks!
socket = f"wss://fstream.binance.com:9443/ws/dotusdt#kline_1m"
you need to add "f" before "stream"
Add 'f' before 'stream' and remove the ':9443
I need to add some code to send keepalive request every 5 seconds to the following program which is using websocket-client
def on_open(wsapp):
wsapp.send(json.dumps(reqlogin))
wsapp.send(json.dumps(reqsub))
def on_message(wsapp, msg):
handle(msg)
wsapp = websocket.WebSocketApp(url, on_open=on_open, on_message=on_message)
wsapp.run_forever()
I've looked at documentation but couldn't find anything appropriate.
I managed to solve the issue using threading:
def on_open(wsapp):
wsapp.send(json.dumps(reqlogin))
wsapp.send(json.dumps(reqsub))
def on_message(wsapp, msg):
handle(msg)
wsapp = websocket.WebSocketApp(url, on_open=on_open, on_message=on_message)
wsappthread = threading.Thread(target=wsapp.run_forever,
daemon=True)
wsappthread.start()
while True:
time.sleep(5)
wsapp.send(json.dumps(reqkeepalive))
I am attempting to setup a websocket using the websocket-client library using python 3.7. The documentation from the API provider states that basic auth is required.
Below is the code I am using to try subscribing to their test channel. The test channel should send responses back nonstop until we close the socket.
email = b'myemail#domain.com'
pw = b'mypassword'
_str = (base64.b64encode(email + b':' + pw)).decode('ascii')
headerValue = 'Authorization: Basic {0}'.format(_str)
def on_message(ws, msg):
global msg_received
print("Message received: ", msg)
msg_received += 1
if msg_received > 10:
ws.send(json.dumps({"unsubscribe": "/test"}))
ws.close()
def on_error(ws, error):
print("ERROR: ", error)
def on_close(ws):
print("Closing websocket...")
def on_open(ws):
print("Opening...")
ws.send(json.dumps({'subscribe': '/test'}))
time.sleep(1)
if __name__ == '__main__':
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://api-ws.myurl.com/",
header=[headerValue],
on_message=on_message,
on_error=on_error,
on_close=on_close))
ws.on_open = on_open
ws.run_forever()
When I run this, I am able to see my request headers, and their response headers which show that the connection was upgraded to a websocket and I am assigned a Sec-Websocket-Accept. Then, the websocket immediately closes without any responses coming through.
I have tried first sending a post request to the login api and generating a sessionID and csrftoken, and then passing those as cookies in the websocketapp object. It didn't work. I have tried passing the headers as an actual dict but that doesn't work either. I've tried way too many variations of the b64 encoding and none of them work.
Any advice would be appreciated.
I'm trying to implement a REST client in python that reacts to messages received from the server received through an opened websocket with the concerned server.
Here is the scenario:
client opens a websocket with the server
from time to time, the server sends a message to the client
when the client receives the messages, it gets some information from
the server
The current client I have is able to open the websocket and to receive the message from the server. However, as soon as it receives the messages, it gets the information from the server then terminates while I'd like to keep it listening for other messages that will make it get a new content from the server.
Here is the piece of code I have:
def openWs(serverIp, serverPort):
##ws url setting
wsUrl = "ws://"+serverIp+":"+serverPort+"/websocket"
##open ws
ws = create_connection(wsUrl)
##send user id
print "Sending User ID..."
ws.send("user_1")
print "Sent"
##receiving data on ws
print "Receiving..."
result = ws.recv()
##getting new content
getUrl = "http://"+serverIp+":"+serverPort+"/"+result+"/entries"
getRest(getUrl)
I don't know if using threads is appropriate or not, I'm not expert in that.
If someone could help, it'll be great.
Thanks in advance.
I finished with this code, doing what I'm expecting. Git it from here
import websocket
import thread
import time
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
def run(*args):
for i in range(3):
time.sleep(1)
ws.send("Hello %d" % i)
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:5000/chat",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()