Subscribe to bitFlyer WebSocket - python

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()

Related

Having trouble to get Binance's Websocket Market Streams

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!

Failed to use websocket : websocket._exceptions.WebSocketConnectionClosedException: socket is already closed

Thank you for checking in! I've got a question about the websocket connection.
Here's a websocket class I use to subscribe to an exchange's websocket, where the connection is established in self.connectWS_public() function.
from datetime import datetime as dt
import threading
import websocket
import json
import time
class Bybit_WS_test():
def __init__ (self):
self.api_url_public = 'wss://stream.bybit.com/realtime_public'
self.api_url_private = 'wss://stream-testnet.bybit.com/realtime_private'
self.api_key = ''
self.api_secret = ''
self.ping_interval = 20
self.ping_timeout = 10
self.ws_public = None
self.ws_private = None
return
def on_message(self, ws, message):
data = json.loads(message)
print('Received message:')
print(data)
def on_error(self, ws, error):
print(f'webscoket error: {error}')
def on_close(self, ws):
print("Closing websocket connection...")
def on_pong(self, ws, message):
print('Received pong')
print(message)
def on_open(self, ws):
print('Websocket opened')
def on_ping(self, message):
dt_string = dt.now().strftime("%d/%m/%Y %H:%M:%S")
print(message)
print(f'Received ping # {dt_string}')
def connectWS_public(self):
self.ws_public = websocket.WebSocketApp(
url = self.api_url_public,
on_message = self.on_message,
on_error = self.on_error,
on_ping= self.on_ping,
on_pong= self.on_pong,
on_open= self.on_open
)
self.wst_public = threading.Thread(target=lambda: self.ws_public.run_forever(ping_interval=self.ping_interval, ping_timeout=self.ping_timeout))
self.wst_public.daemon = True
self.wst_public.start()
However, when I test the connection in another file called test.py, I always encounter the following error:
File "/Users/rickycheng/Desktop/pair-trading-bot/venv/lib/python3.7/site-packages/websocket/_socket.py", line 143, in send
raise WebSocketConnectionClosedException("socket is already closed.")
websocket._exceptions.WebSocketConnectionClosedException: socket is already closed.
Below is my test.py used to test the websocket connection:
from Bybit_api.Bybit_ws import Bybit_WS_test
import json
if __name__ == '__main__':
x = Bybit_WS_test()
x.connectWS_public()
while (x.ws_public.sock):
print(True)
topic = "orderBookL2_25.BTCUSD"
x.ws_public.send(json.dumps({"op": "subscribe",'args':[topic]}))
You may check the exchange API documentation via
https://bybit-exchange.github.io/docs/linear/#t-heartbeat
Guys I have got the solution:
In general, if you have encountered a similar error like me, it's possible that you didn't sleep the program after establishing the connection.
Try to add: time.sleep(5) after calling ws.run_forever()
This allows the websocket connection to be successfully connected before sending any request to it.

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.

Python WebSocketApp info

I'm trying to wrap my head around the usage of websocket. Here's my code:
import websocket
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print('Websocket: closed')
def on_open(ws):
print('Websocket: open')
ws = websocket.WebSocketApp('ws://echo.websocket.org/',
on_message = on_message,
on_error = on_error,
on_close = on_close,
on_open = on_open)
ws.run_forever()
First, why would I put
ws.on_open = on_open
instead of passing it while defining ws? (As I did in the code)
Moreoever, how can I send a message? I could include
ws.send(json.dumps("Hello")) under
def on_open(ws), is there some other way?
Finally, I'm not able to close the connection given that ws.run_forever() never stops, how can I do it? I tried to include ws.close() under def on_open(ws) but then I don't receive any message.
What I'm trying to get is how I can transpose this:
ws = ws.create_connection('ws://echo.websocket.org/')
ws.send(json.dumps("Hello"))
result = json.loads(ws.recv())
print(result)
using WebSocketApp, that is having the messages pushed printed directly, without having to request the result.

chat app using websocket python+django+angular

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()

Categories

Resources