websocket深堀り4回シリーズ
- そもそもwebsocketとは
- ビットコインのデータをwebsoketで受信 → クラス化
- websocket受信クラス → threadingでマルチタスク化
- websocketクラスをマルチタスクでビットフライヤーとバイナンスの同時受信
URLとチャンネル(例:BTCJPY-約定データ)を指定してwebsoket関数を呼び出す
複数の取引所のデータを同時受信しながら取引のための準備データ受信編1
websoketは
pip install websocket-client
でインストールしたものを
import websoket で呼び出す。
#pip install websocket-client
import websocket
import json
from pprint import pprint
#import pandas as pd
CHANNEL = "lightning_executions_BTC_JPY"
def on_message(ws, message):
message = json.loads(message)
pprint(message)
def on_open(ws):
ws.send(json.dumps({"method": "subscribe",
"params": {"channel": CHANNEL}}))
if __name__ == "__main__":
ws = websocket.WebSocketApp("wss://ws.lightstream.bitflyer.com/json-rpc",
on_message=on_message, on_open=on_open)
ws.run_forever()
データ内容を理解するため、データ丸ごと表示してみる。
ここから必要なものを辞書のキーを指定して取り出す
{'jsonrpc': '2.0',
'method': 'channelMessage',
'params': {'channel': 'lightning_executions_BTC_JPY',
'message': [{'buy_child_order_acceptance_id': 'JRF20210516-210717-231265',
'exec_date': '2021-05-16T21:07:17.4793855Z',
'id': 2213681509,
'price': 4884761.0,
'sell_child_order_acceptance_id': 'JRF20210516-210717-314050',
'side': 'SELL',
'size': 0.0138},
{'buy_child_order_acceptance_id': 'JRF20210516-210702-341601',
'exec_date': '2021-05-16T21:07:17.4793855Z',
'id': 2213681510,
'price': 4884760.0,
'sell_child_order_acceptance_id': 'JRF20210516-210717-314050',
'side': 'SELL',
'size': 0.25145526}]}}
例えば、レスポンス['Params']['message'][0]['price']とすれば価格が抽出できる
上記をクラスにしてみる、関数をクラスの屋根に入れただけです。
データの出力は、目的の価格[‘price’]まで絞り込みます。
class BfWebSocket():
def __init__(self):
self.CHANNEL = "lightning_executions_BTC_JPY"
self.url = "wss://ws.lightstream.bitflyer.com/json-rpc"
def run(self):
# note: reconnection handling needed.
ws = websocket.WebSocketApp(self.url, on_message=self.on_message, on_open=self.on_open)
ws.run_forever()
def on_message(self,ws, message):
self.message = json.loads(message)
#目的のデータを抽出する
if self.message["method"] == "channelMessage":
self.last1=self.message["params"]["message"][0]
print(f'\nBitfler_BTC {self.last1["exec_date"][:19]} {int(self.last1["price"]):,.0f} {self.last1["side"]:4} {self.last1["size"]:.2f}\n')
def on_open(self,ws):
ws.send(json.dumps({"method": "subscribe",
"params": {"channel": self.CHANNEL}}))
stream=BfWebsocket()
stream.run_forever()
出力
BF_BTC 2021-05-18T10:50:27 4,936,442 SELL 0.01
BF_BTC 2021-05-18T10:50:34 4,937,563 BUY 0.01
次回はこの両方をマルチスレッドとして呼び出せるようthread化してみます
コメント