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 함수는 구독한 모든 심볼의 실시간 데이터를 수신합니다

아직 막히셨나요?

어느 단계에서 막혔는지 알려주시면 도와드리겠습니다