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.
Related
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!
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
I have a WebSocket connection to a third party service in a websocket_service.py like below
import websocket
def on_message(ws, msg):
print("Message Arrived:" + msg)
def on_error(ws, error):
print(error)
def on_close(ws):
print("Connection Closed")
def on_open(ws):
print("Sending json")
data = '{"request":{"streaming_type":"quote", "data":data, "request_type":"subscribe", "response_format":"json"}}'
ws.send(data)
ws.send("\n")
headers = {'x-session-token': '12a8a2b304142425a1e52f109ff02cb2'}
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://stream.stocknote.com", on_open=on_open, on_message=on_message, on_error=on_error,
on_close=on_close, header=headers)
ws.run_forever()
If I run python websocket_service.py it starts. But what I want is to start it from another method which is in another file using discord
main.py
import discord
client = discord.Client()
#client.event
async def on_ready():
print(f'we have logged in as {client.user}')
#client.event
async def on_message(message):
if message.author==client.user:
return
if message.content.startswith('$start_websocket'):
#how can I start the websocket connection here???
await message.channel.send('websocket started')
client.run(TOKEN_ENV)
My suggestion is putting below code into a function.
headers = {'x-session-token': '12a8a2b304142425a1e52f109ff02cb2'}
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://stream.stocknote.com", on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close, header=headers)
ws.run_forever()
Then on the main file, put this statement at top "from websocket_service import the-funct-name". Now you can call the funct anywhere within the main file to start the socket.
I want to make one real-time chat application using websockets and the frontend is angular5.
So, I create websocket in purepython and backend is Django and frontend is angular5.
Myquestion is when i create websocket service in python. So, do i have to make websockets services in angular too?
this is my python websocket service
async def consumer_handler(websocket):
global glob_message
while True:
message = await websocket.recv()
await glob_message.put(message)
print("this went in glob_message: {}".format(message))
async def producer_handler(websocket):
global glob_message
while True:
message = await glob_message.get()
await websocket.send(message)
async def handler(websocket, path):
producer_task = asyncio.ensure_future(producer_handler(websocket))
consumer_task = asyncio.ensure_future(consumer_handler(websocket))
done, pending = await asyncio.wait(
[consumer_task, producer_task],
return_when=asyncio.FIRST_COMPLETED,
)
for task in pending:
task.cancel()
if __name__ == '__main__':
glob_message = asyncio.Queue()
start_server = websockets.serve(
handler,
'127.0.0.1', 8788)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
So, i want to create two user can send and receive messages.so must be design in angular ..
so i am asking that i already create one service in python so do i have to create websocket service(Observable subscribers) in angular too?
In your angular side, you should open a connection indeed.
This is how you can use Observables to communicate with your server :
Client side
// open the socket connection
const ws = new WebSocket('ws://127.0.0.1:8788')
// when opened, print all messages
ws.onopen = open => {
Observable.fromEvent(ws, 'message')
.subscribe(message => console.log(message))
}
To send a message, simply use :
ws.send('test')
Server Side
You can use the demo in https://pypi.org/project/websocket-client/ to build your websocket server.
to import WebSocket :
pip install websocket-client
Then :
import websocket
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("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://127.0.0.1:8788",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
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()