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

[선물 WS] 전체 시장 청산 주문 금액 1분마다 확인하기

Eluv 2024. 11. 24. 01:02
import asyncio
import websockets
import json
import time
from collections import defaultdict

async def All_Market_Liq_Order_Stream():
    uri = 'wss://fstream.binance.com/ws/!forceOrder@arr'
    try:
        async with websockets.connect(uri) as websocket:
            liquidation_by_symbol = defaultdict(float)
            start_time = int(time.strftime('%M'))

            while True:
                data = json.loads(await websocket.recv())

                symbol = data['o']['s']
                quantity = float(data['o']['q'])
                price = float(data['o']['ap'])
                liquidation_amount = quantity * price

                liquidation_by_symbol[symbol] += liquidation_amount

                # 1분이 지났는지 확인
                if start_time != int(time.strftime('%M')):
                    total_liquidation = sum(liquidation_by_symbol.values())
                    print(time.strftime('%H:%M'), f"지난 1분 동안의 총 청산 금액: {total_liquidation:.2f} USDT")

                    # 상위 3개 종목 출력
                    top_3 = sorted(liquidation_by_symbol.items(), key=lambda x: x[1], reverse=True)[:3]
                    for rank, (symbol, amount) in enumerate(top_3, 1):
                        print(f"{rank}위: {symbol} - {amount:.2f} USDT")

                    # 초기화
                    liquidation_by_symbol.clear()
                    start_time = int(time.strftime('%M'))

    except asyncio.CancelledError:
        print("Liq_Order_Stream 작업이 취소되었습니다.")
    except Exception as e:
        print(f"Liq_Order_Stream 예외가 발생했습니다: {e}")
    finally:
        print("Liq_Order_Stream 웹소켓 연결을 종료합니다.")
        await websocket.close()


async def main():
    tasks = [asyncio.create_task(All_Market_Liq_Order_Stream())]
    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("프로그램을 종료합니다.")

1분마다 발생한 청산 금액이 얼마인지,

가장 많은 청산이 발생한 종목은 무엇인지 출력합니다.

 

 

출력 결과

00:57 지난 1분 동안의 총 청산 금액: 152300.43 USDT
1위: ADAUSDT - 92284.53 USDT
2위: NEIROUSDT - 10505.95 USDT
3위: XRPUSDT - 7763.00 USDT

 

 

top_3 = sorted(liquidation_by_symbol.items(), key=lambda x: x[1], reverse=True)[:3]

해당 코드에서 마지막 [ :3]이 출력할 종목 수 입니다.

[ :5] 이렇게 바꾸면 5등 종목까지 나옵니다.

 

 

만약 위처럼 1분 단위 말고 그냥 실시간으로 보고 싶다면 

해당 함수 내의 내용을 전부 지우고  아래의 코드처럼

print 혹은 pprint로 바로 출력하면 됩니다.

async def All_Market_Liq_Order_Stream():
    uri = 'wss://fstream.binance.com/ws/!forceOrder@arr'
    try:
        async with websockets.connect(uri) as websocket:
            liquidation_by_symbol = defaultdict(float)
            start_time = int(time.strftime('%M'))

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

 

출력 결과

{'e': 'forceOrder', 'E': 1733005569381, 'o': {'s': 'XRPUSDT', 'S': 'SELL', 'o': 'LIMIT', 'f': 'IOC', 'q': '9.6', 'p': '1.9301', 'ap': '1.9393', 'X': 'FILLED', 'l': '9.6', 'z': '9.6', 'T': 1733005569380}}

{'e': 'forceOrder', 'E': 1733005571096, 'o': {'s': 'ENSUSDT', 'S': 'BUY', 'o': 'LIMIT', 'f': 'IOC', 'q': '3.7', 'p': '41.031', 'ap': '40.658', 'X': 'FILLED', 'l': '0.2', 'z': '3.7', 'T': 1733005571094}}

{'e': 'forceOrder', 'E': 1733005572253, 'o': {'s': 'SAGAUSDT', 'S': 'BUY', 'o': 'LIMIT', 'f': 'IOC', 'q': '100.0', 'p': '2.5432331', 'ap': '2.5193000', 'X': 'FILLED', 'l': '100.0', 'z': '100.0', 'T': 1733005572250}}