import asyncio
import websockets
import json
from collections import deque

ticks = 20
basepair = "ETHUSDC"

# Configuración central de los pares
pairs_config = [
    {"base": basepair, "alt": "ZECUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "XMRUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "ADAUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "DOGEUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "BANANAUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "SYNUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "HYPERUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "RAYUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "SOPHUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "FLOKIUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "ENAUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "INITUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "TRUMPUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "NEIROUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "NXPCUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "WCTUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "VIRTUALUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "SUIUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "WIFUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "CATIUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "HUMAUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "BTOUSDC", "history": deque(maxlen=ticks)},
    {"base": basepair, "alt": "VANRYUSDC", "history": deque(maxlen=ticks)},
]


# Memoria de precios y últimos bids
latest_prices = {}
last_printed_bid = {}

# Inicializar claves automáticamente
for config in pairs_config:
    latest_prices[config["base"]] = None
    latest_prices[config["alt"]] = None
    last_printed_bid[config["base"]] = None
    last_printed_bid[config["alt"]] = None

threshold_pct = 0.5  # % de desfase para alerta

async def listen_order_book(symbol):
    uri = f"wss://stream.binance.com:9443/ws/{symbol.lower()}@bookTicker"
    async with websockets.connect(uri) as websocket:
        print(f"🔄 Conectado a {symbol}")
        async for message in websocket:
            data = json.loads(message)
            bid = float(data["b"])
            latest_prices[symbol] = bid

            if bid != last_printed_bid[symbol]:
                print(f"{symbol} Best Bid: {bid}")
                last_printed_bid[symbol] = bid

async def monitor_ratios():
    while True:
        for config in pairs_config:
            base_price = latest_prices.get(config["base"])
            alt_price = latest_prices.get(config["alt"])

            if base_price and alt_price:
                ratio = base_price / alt_price
                config["history"].append(ratio)

                if len(config["history"]) < 5:
                    # Espera acumular algunos datos
                    continue

                mean_ratio = sum(config["history"]) / len(config["history"])
                pct_diff = ((ratio - mean_ratio) / mean_ratio) * 100

                print(f"RATIO {config['base']}/{config['alt']}: {ratio:.2f} | Media: {mean_ratio:.2f} | Δ: {pct_diff:.2f}%")

                if abs(pct_diff) > threshold_pct:
                    print(f"🚨 Desfase detectado en {config['alt']} ({pct_diff:.2f}%)")

        await asyncio.sleep(1)

async def main():
    unique_symbols = set()
    for config in pairs_config:
        unique_symbols.add(config["base"])
        unique_symbols.add(config["alt"])

    listeners = [listen_order_book(symbol) for symbol in unique_symbols]
    listeners.append(monitor_ratios())

    await asyncio.gather(*listeners)

if __name__ == "__main__":
    asyncio.run(main())
