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
Related
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'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.
I have server, where I need to keep connection with client as long as possible. I need to allow for multiple clients connect to this server. Code:
class LoginServer(BaseServer):
def __init__(self, host, port):
super().__init__(host, port)
async def handle_connection(self, reader: StreamReader, writer: StreamWriter):
peername = writer.get_extra_info('peername')
Logger.info('[Login Server]: Accepted connection from {}'.format(peername))
auth = AuthManager(reader, writer)
while True:
try:
await auth.process()
except TimeoutError:
continue
finally:
await asyncio.sleep(1)
Logger.warning('[Login Server]: closing...')
writer.close()
#staticmethod
def create():
Logger.info('[Login Server]: init')
return LoginServer(Connection.LOGIN_SERVER_HOST.value, Connection.LOGIN_SERVER_PORT.value)
The problem: currently only one client can connect to this server. It seems socket do not closing properly. And because of this even previous client cannot reconnect. I think this is because infinite loop exists. How to fix this problem?
The while loop is correct.
If you wanted a server that waits on data from a client you would have the following loop in your handle_connection.
while 1:
data = await reader.read(100)
# Do something with the data
See the example echo server here for more details on reading / writing.
https://asyncio.readthedocs.io/en/latest/tcp_echo.html
Your problem is likely that this function doesn't return and is looping itself without await'g anything. That would mean the asyncio loop would never regain control so new connections could not be made.
await auth.process()
I use websocket to make a long-live connection with the target wss-url successfully. But after receiving one message, the code caught an error named "rsv is not implemented, yet" and closed the connection.
It seems that few people have met this problem, which described as "rsv is not implemented, yet". And the API doc of websocket never mention this issue.
The main piece of my code:
def on_message(ws, message):
print(message)
def on_error(ws, error):
print("!!!find error!!!")
print(error)
def on_close(ws):
print("### why closed ???###")
websocket.enableTrace(True)
ws = websocket.WebSocketApp(url,
on_message = on_message,
on_error = on_error,
on_close = on_close,
header = header,
cookie = cookie,
)
ws.run_forever(origin = 'https://matters.news', skip_utf8_validation = True)
It will give me only one message, and then show that:
!!!find error!!!
rsv is not implemented, yet
send: b'\x88\x82\xd9\xe2\xcc\x8c\xda\n'
### why closed ???###
I received the same error and fixed it by removing:
'Sec-WebSocket-Extensions': 'permessage-deflate'
from my headers.
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()