Python 範例

WebSocket 串接教學

使用 websocket-client 套件串接即時行情數據的完整範例。

1

定義事件處理

引入 websocket 套件並定義各種事件的處理函數

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

建立連線

建立 WebSocket 連線並啟動監聽

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

完整範例

將上述代碼整合為可直接執行的完整程式

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

開發提示

需先安裝套件:pip install websocket-client

請將 wsToken 替換為您的實際 Token

on_message 函數會接收所有訂閱標的的即時數據

還是卡住了嗎

留言告訴我們你卡在哪一步,我們會協助你