-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrealtime_api.py
75 lines (65 loc) · 2.18 KB
/
realtime_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import json
import websocket
from time import sleep
from logging import getLogger,INFO,StreamHandler
logger = getLogger(__name__)
handler = StreamHandler()
handler.setLevel(INFO)
logger.setLevel(INFO)
logger.addHandler(handler)
"""
This program calls Bitflyer real time API JSON-RPC2.0 over Websocket
"""
class RealtimeAPI(object):
def __init__(self, url, channel):
self.url = url
self.channel = channel
#Define Websocket
self.ws = websocket.WebSocketApp(self.url,header=None,on_open=self.on_open, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close)
websocket.enableTrace(True)
self.ws.keep_running = True
def run(self):
#ws has loop. To break this, press occur Keyboard Interruption.
self.ws.run_forever()
logger.info('Web Socket process ended.')
"""
Below are callback functions of websocket.
"""
# when we get message
def on_message(self, ws, message):
output = json.loads(message)['params']
logger.info(output)
# when error occurs
def on_error(self, ws, error):
logger.error(error)
# when websocket closed.
def on_close(self, ws):
logger.info('disconnected streaming server')
# when websocket opened.
def on_open(self, ws):
logger.info('connected streaming server')
output_json = json.dumps(
{'method' : 'subscribe',
'params' : {'channel' : self.channel}
}
)
ws.send(output_json)
if __name__ == '__main__':
#API endpoint
url = 'wss://ws.lightstream.bitflyer.com/json-rpc'
"""
Bitflyer board channel
list :
lightning_board_snapshot_<productCode>
lightning_board_<productCode>
lightning_ticker_<productCode>
lightning_executions_<product_code>
for detail see
https://lightning.bitflyer.jp/docs?lang=en
https://lightning.bitflyer.jp/docs?lang=ja
product code of spot_trading is "BTC_JPY"
"""
channel = 'lightning_board_snapshot_BTC_JPY'
json_rpc = RealtimeAPI(url=url, channel=channel)
#press ctrl+c to stop
json_rpc.run()