import asyncio
import websockets
import json
import redis

r = redis.Redis(host='localhost', port=6379, db=0)

async def order_book_listener():
    uri = "wss://stream.binance.com:9443/ws/neirousdc@depth5@100ms"

    print(f"Conectando a {uri}...")
    async with websockets.connect(uri) as websocket:
        print("✅ Conectado al WebSocket de Binance.")

        async for message in websocket:
            try:
                data = json.loads(message)
                print("📩 Mensaje recibido:")
                print(json.dumps(data, indent=2))

                if 'bids' not in data or 'asks' not in data:
                    print("⚠️ El mensaje no contiene 'bids' o 'asks'. Ignorando.")
                    continue

                bids = data['bids']
                asks = data['asks']

                if not bids or not asks:
                    print("⚠️ Lista de bids o asks vacía. Ignorando.")
                    continue

                best_bid = float(bids[0][0])
                best_ask = float(asks[0][0])
                spread = best_ask - best_bid

                bid_volume = sum([float(bid[1]) for bid in bids[:5]])
                ask_volume = sum([float(ask[1]) for ask in asks[:5]])

                print(f"🔢 Volumen bid (top 5): {bid_volume}")
                print(f"🔢 Volumen ask (top 5): {ask_volume}")
                print(f"📊 Spread: {spread}")

                if bid_volume > ask_volume * 1.5:
                    signal = "buy"
                elif ask_volume > bid_volume * 1.5:
                    signal = "sell"
                else:
                    signal = "neutral"

                print(f"📤 Señal generada: {signal}")
                r.set("orderflow_signal", signal)

            except Exception as e:
                print(f"❌ Error procesando mensaje: {e}")

asyncio.run(order_book_listener())
