Having trouble to get Binance's Websocket Market Streams - python

I am having a trouble getting some data from Binance Websocket.
The code is the following:
import websocket
import json
import pprint
SOCKET = "wss://stream.binance.com:9443/ws/ethusdt#kline_1m"
def on_open(ws):
print('opened connection')
def on_close(ws):
print('closed connection')
def on_message(ws, message):
print('received message')
json_message = json.loads(message)
pprint.pprint(json_message)
ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever()
In fact when I run the program there isn't any result printed on my screen.
I need help in spotting the mistake I have made in order for it to work properly.
Thanks!

Related

How can I send ping method in Binance websocket?

I want to take data from Binance by websocket. In a few minutes connection will be closed. How can I run ping/pong method in Binance websocket?
import json
import websocket
def on_message(ws, message):
print(message)
def on_error(ws, error):
print("Error Binance", error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
pass
def on_ping(ws, message):
pass
def on_pong(ws, message):
# ws.send(json.dumps({"method": "ping"}))
# ws.send({"method": "ping"})
pass
if __name__ == "__main__":
ws = websocket.WebSocketApp("wss://fstream.binance.com/stream?streams=btcusdt#depth",
on_message=on_message, on_error=on_error, on_close=on_close, on_ping=on_ping,
on_pong=on_pong, on_open=on_open)
ws.run_forever(ping_interval=10, ping_timeout=5)
As I said in the comments, I would suggest you to use websockets package, which allows to use the async paradigm instead of callbacks.
In your case, you want to use it as a client. Here is an example of a client that sends and receives a single message:
import asyncio
import websockets
async def hello():
async with websockets.connect("ws://localhost:8765") as websocket:
await websocket.send("Hello world!")
await websocket.recv()
asyncio.run(hello())
You can adapt it to your use case.

Binance Websocket API stuck on OPEN MESSAGE

I have this...
import websocket
SOCKET = "wss://stream.binance.com:9443/ws/ADABUSB#nav_kline_1m"
def on_open(ws):
print('opened connection')
def on_close(ws):
print('close connection')
def on_message(ws, message):
print('received message')
print(message)
ws = websocket.WebSocketApp(SOCKET, on_open = on_open, on_close = on_close, on_message = on_message)
ws.run_forever()
When I run it it sticks on OPENED CONNECTION and then does nothing??
Any ideas?
No error messages and I have left it for minutes!!
Cheers
Zak
No error messages
How do you know, you haven't defined the on_error-callback :) ?
Try adding it like below and see if it makes a difference (it does on my end):
import websocket
SOCKET = "wss://stream.binance.com:9443/ws/ADABUSB#nav_kline_1m"
def on_open(ws):
print('opened connection')
def on_close(ws):
print('close connection')
def on_message(ws, message):
print('received message')
print(message)
def on_error(ws, message):
print('error:', message)
ws = websocket.WebSocketApp(SOCKET, on_open = on_open, on_close = on_close, on_message = on_message, on_error = on_error)
ws.run_forever()
Found this and it worked!
I am on a Mac...
Spot on! removed ::1 from /etc/hosts and its connecting. localhost was resolving to ::1. Thanks for help.

How can I set max_queue or max_size in Python websocket.WebsocketApp

I am using the Python websocket-client library to create a long running websocket connection: https://pypi.org/project/websocket-client
When using a short connection with the websocket.WebSocket class I could add the max_queue and max_size parameters to the connect() method, however I have a long running connection.
How could I change the max_queue and max_size settings using the websocket.WebsocketApp class?
import websocket
import _thread
import time
import rel
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
def on_open(ws):
print("Opened connection")
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://api.gemini.com/v1/marketdata/BTCUSD",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever(dispatcher=rel) # Set dispatcher to automatic reconnection
rel.signal(2, rel.abort) # Keyboard Interrupt
rel.dispatch()
I hope somebody can help me out.

Connection WebSocket with Session

good morning.
I'm trying to make an API for Quotex.com brokerage where your communication is done via websocket --> wss://ws.qxbroker.com/socket.io/?EIO=3&transport=websocket
To connect to the broker I'm using Selenium. I can recover the session, but the difficulty is to send this data back to the websocket.
My code is this, where I try to connect and then send an order to broker.
Could someone help me please.
order = '42["orders/open",{"asset":"AUDCAD_otc","amount":6,"time":1637893200,"action":"put","isDemo":1,"requestId":1637892541,"optionType":1}]'
order2 = json.dumps(order)
try:
import thread
except ImportError:
import _thread as 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("""42["authorization",{"session":""" + session + ""","isDemo":1}]""")
time.sleep(1)
ws.send(order)
ws.send(order2)
ws.close()
print("thread terminating...")
thread.start_new_thread(run, ())
urlsocket = "wss://ws.qxbroker.com/socket.io/?EIO=3&transport=websocket"
ws = websocket.WebSocketApp(
urlsocket, on_message=on_message,
on_open=on_open)
ws.run_forever()
Example of analysis via google chrome devtools
Exemple Send Order for Broker

Subscribe to bitFlyer WebSocket

I have set up websocket connections to multiple cryptocurrency exchanges but I'm having difficulty connecting to bitFlyer's.
My code is as follows:
import websocket
import json
def on_message(ws, message):
msg = json.loads(message)
print(msg)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
ws.send(json.dumps({"method":"subscribe", "channel":"lightning_executions_FX_BTC_JPY"}))
while True:
if __name__ == "__main__":
#websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://ws.lightstream.bitflyer.com/json-rpc",
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()
I have tried many many variations of my on_open() message and most result in a ### closed ###
Invalid close opcode. error.
Unfortunately their documentation does not contain a Python sample located HERE.
Any help in sending the correct message is much appreciated.
I believe the format of message you sent was wrong, check the following reference from https://lightning.bitflyer.jp/docs/playgroundrealtime, guess it will solve.
# pip install websocket-client
import websocket
import json
CHANNEL = "lightning_board_snapshot_<productCode>"
def on_message(ws, message):
message = json.loads(message)
if message["method"] == "channelMessage":
print("{} {}".format(message["params"]["channel"], message["params"]["message"]))
def on_open(ws):
ws.send(json.dumps({"method": "subscribe", "params": {"channel": CHANNEL}}))
if __name__ == "__main__":
// note: reconnection handling needed.
ws = websocket.WebSocketApp("wss://ws.lightstream.bitflyer.com/json-rpc",
on_message = on_message, on_open = on_open)
ws.run_forever()

Categories

Resources