import asyncio
import aiohttp
import json
from datetime import datetime

# Настройки
SYMBOL = 'ethfdusd'
STREAM_URL = f"wss://stream.binance.com:9443/stream?streams={SYMBOL}@aggTrade/{SYMBOL}@depth5@100ms"

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.ws_connect(STREAM_URL) as ws:
            print(f"🟢 Подключено к потоку: {SYMBOL.upper()}")
            print("----------------------------------------------------------------")
            
            counter = 0 # СЧЕТЧИК СООБЩЕНИЙ

            async for msg in ws:
                if msg.type == aiohttp.WSMsgType.TEXT:
                    data = json.loads(msg.data)
                    stream_type = data['stream']
                    payload = data['data']
                    
                    counter += 1
                    # Получаем точное время сейчас
                    now = datetime.now().strftime("%H:%M:%S.%f")[:-3]

                    # --- ВЕТКА 1: СДЕЛКА (aggTrade) ---
                    if 'aggTrade' in stream_type:
                        price = payload['p']
                        quantity = payload['q']
                        side = "🔴 SELL" if payload['m'] else "🟢 BUY"
                        
                        print(f"[{now}] #{counter} [TRADE] {side} | Цена: {price} | Объем: {quantity}")

                    # --- ВЕТКА 2: СТАКАН (depth5) ---
                    # Я раскомментировал вывод стакана, чтобы вы увидели СКОРОСТЬ.
                    # Он приходит каждые 100мс (10 раз в секунду), даже если сделок нет.
                    elif 'depth5' in stream_type:
                        best_bid = payload['bids'][0][0]
                        best_ask = payload['asks'][0][0]
                        print(f"[{now}] #{counter} [BOOK ] 📘 Bid: {best_bid} | 📙 Ask: {best_ask}")
                        
                elif msg.type == aiohttp.WSMsgType.ERROR:
                    print('🔴 Ошибка соединения')
                    break

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\n🛑 Стоп.")
