Python Example
WebSocket Integration Guide
Complete example of integrating real-time market data using websocket-client package.
1
Define Event Handlers
Import websocket package and define event handler functions
Event HandlersPython
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import websocket
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### Connection Closed ###")
def on_open(ws):
# 訂閱美股 AAPL
ws.send('{"event":"subscribe","data":{"symbol":"AAPL","provider":"US"}}')
# 訂閱台股 2330
ws.send('{"event":"subscribe","data":{"symbol":"2330","provider":"Taiwan"}}')
# 訂閱比特幣(現貨)
ws.send('{"event":"subscribe","data":{"symbol":"BTCUSDT","provider":"Binance","market":"Client"}}')2
Establish Connection
Create WebSocket connection and start listening
ConnectionPython
1
2
3
4
5
6
7
8
9
10
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp(
"wss://api.zzztech.com.tw/ws/v1/symbol/quote?wsToken=**********",
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.on_open = on_open
ws.run_forever()3
Complete Example
Combined code that can be directly executed
Full ExamplePython
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
import websocket
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### Connection Closed ###")
def on_open(ws):
# 訂閱美股 AAPL
ws.send('{"event":"subscribe","data":{"symbol":"AAPL","provider":"US"}}')
# 訂閱台股 2330
ws.send('{"event":"subscribe","data":{"symbol":"2330","provider":"Taiwan"}}')
# 訂閱比特幣(現貨)
ws.send('{"event":"subscribe","data":{"symbol":"BTCUSDT","provider":"Binance","market":"Client"}}')
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp(
"wss://api.zzztech.com.tw/ws/v1/symbol/quote?wsToken=**********",
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.on_open = on_open
ws.run_forever()Development Tips
Install package first: pip install websocket-client
Replace wsToken with your actual token
on_message function receives real-time data for all subscribed symbols
