import asyncio
import websockets
import json

latest_prices = {
    "BTCUSDC": None,
    "ETHBTC": None,
    "ETHUSDC": None
}

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
            print(f"{symbol} Best Bid: {bid}")

async def monitor_triangular():
    threshold_pct = 0.3
    while True:
        btc = latest_prices["BTCUSDC"]
        ethbtc = latest_prices["ETHBTC"]
        ethusdc = latest_prices["ETHUSDC"]

        if btc and ethbtc and ethusdc:
            theoretical = ethbtc * btc
            pct_diff = ((ethusdc - theoretical) / theoretical) * 100

            print(f"ETHUSDC real: {ethusdc:.2f} | teórico: {theoretical:.2f} | Δ: {pct_diff:.2f}%")

            if abs(pct_diff) > threshold_pct:
                print(f"🚨 Desfase triangular detectado: {pct_diff:.2f}%")

        await asyncio.sleep(0.5)

async def main():
    await asyncio.gather(
        listen_order_book("BTCUSDC"),
        listen_order_book("ETHBTC"),
        listen_order_book("ETHUSDC"),
        monitor_triangular()
    )

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