Skip to content

Commit 2ce30ca

Browse files
authored
feat: add ws example to repo (sammchardy#1451)
1 parent 40b73c4 commit 2ce30ca

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

examples/websocket.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import os
2+
import sys
3+
4+
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5+
sys.path.append(root)
6+
7+
from binance import ThreadedWebsocketManager
8+
9+
api_key = '<api_key>'
10+
api_secret = '<api_secret>'
11+
12+
def main():
13+
14+
symbol = 'BNBBTC'
15+
16+
twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret)
17+
# start is required to initialise its internal loop
18+
twm.start()
19+
20+
def handle_socket_message(msg):
21+
if msg.get('e') == 'error':
22+
print(f"WebSocket error: {msg.get('m', 'Unknown error')}")
23+
24+
return
25+
26+
# Process message normally
27+
print(msg)
28+
29+
# Store socket names for potential restart
30+
sockets = []
31+
32+
# Start kline socket
33+
kline_socket = twm.start_kline_socket(callback=handle_socket_message, symbol=symbol)
34+
sockets.append(('kline', kline_socket, symbol))
35+
36+
# Start depth socket
37+
depth_socket = twm.start_depth_socket(callback=handle_socket_message, symbol=symbol)
38+
sockets.append(('depth', depth_socket, symbol))
39+
40+
# Start multiplex socket
41+
streams = ['bnbbtc@miniTicker', 'bnbbtc@bookTicker']
42+
twm.start_multiplex_socket(callback=handle_socket_message, streams=streams)
43+
44+
twm.join()
45+
46+
47+
if __name__ == "__main__":
48+
main()

0 commit comments

Comments
 (0)