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を実際のトークンに置き換えてください

on_message関数は購読中のすべての銘柄のリアルタイムデータを受信します

まだお困りですか

どのステップで詰まっているか教えてください。サポートいたします