파이썬/바이낸스 선물 웹소켓

[선물 WS] 실시간 체결 확인하기

Eluv 2024. 12. 1. 08:41
import asyncio
import websockets
import json
import pprint

async def aggTrade():
    symbol = 'btcusdt'
    uri = f'wss://fstream.binance.com/ws/{symbol}@aggTrade'

    async with websockets.connect(uri) as websocket:
        try:
            while True:
                message = await websocket.recv()
                data = json.loads(message)
                pprint.pprint(data)
        except asyncio.CancelledError:
            print("aggTrade 작업이 취소되었습니다.")
        except Exception as e:
            print(f"aggTrade에서 예외가 발생했습니다: {e}")
        finally:
            print("aggTrade 웹소켓 연결을 종료합니다.")
            await websocket.close()

async def main():
    tasks = [asyncio.create_task(aggTrade())]
    try:
        await asyncio.gather(*tasks)
    except asyncio.CancelledError:
        print("메인 작업이 취소되었습니다.")
        for task in tasks:
            task.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)
    except Exception as e:
        print(f"메인 함수에서 예외가 발생했습니다: {e}")
    finally:
        print("메인 함수의 작업이 종료되었습니다.")

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("프로그램을 종료합니다.")

 

 

출력 결과

{'E': 1733009332890, # 이벤트 시간
 'T': 1733009332736, # 거래 시간
 'a': 2441755452, # 거래 식별 ID
 'e': 'aggTrade', # 이벤트 타입
 'f': 5663848067, # 첫번째 거래 식별 ID
 'l': 5663848068, # 마지막 거래 식별 ID
 'm': True, # 매도주문 여부, 매도는 True, 매수는 False
 'p': '96396.40', # 거래 가격
 'q': '0.005', # 거래 수량
 's': 'BTCUSDT'} # 종목 이름

 

아쉽지만 전체 시장의 체결을 한번에 보는 것은 제공되지 않습니다.

해당 코드를 통해서 특정 종목의 실시간 체결을 볼 수 있습니다.