is this bot correct import asyncio
import json
import websockets
import logging
from binance.client import Client
from binance.exceptions import BinanceAPIException

# Set up your Binance API keys (replace with your keys)
api_key = 'your_binance_api_key'
api_secret = 'your_binance_api_secret'

# Initialize the Binance client
client = Client(api_key, api_secret)

# Constants
LIQUIDITY_THRESHOLD = 100000  # 100,000 USDT
TRADE_AMOUNT = 20  # 20 USDT trade size
MIN_PROFIT_THRESHOLD = 0.2  # Minimum profit threshold in USDT
TRADING_FEE = 0.00078  # 0.078% trading fee
DRY_RUN = True  # Set to True for testing without live trading

# Global variables
spot_prices = {}

# Initialize logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


# Function to get tradable pairs
def get_liquid_pairs():
    logging.info("Fetching tradable pairs with liquidity over $100,000...")
    pairs = []
    try:
        exchange_info = client.get_exchange_info()
        symbols = exchange_info['symbols']
        for symbol in symbols:
            if symbol['quoteAsset'] == 'USDT' and symbol['status'] == 'TRADING':
                order_book = client.get_order_book(symbol=symbol['symbol'])
                total_liquidity = sum([float(order[0]) * float(order[1]) for order in order_book['bids']])
                if total_liquidity >= LIQUIDITY_THRESHOLD:
                    pairs.append(symbol['symbol'])
        logging.info(f"Found {len(pairs)} pairs with liquidity over {LIQUIDITY_THRESHOLD} USDT")
        return pairs
    except Exception as e:
        logging.error(f"Error fetching pairs: {e}")
        return []


# WebSocket connection for price updates
async def handle_socket_message(pairs):
    global spot_prices
    streams = '/'.join([f'{pair.lower()}@ticker' for pair in pairs])
    socket_url = f"wss://stream.binance.com:9443/ws/{streams}"

    async with websockets.connect(socket_url) as websocket:
        logging.info("Connected to WebSocket for real-time price updates...")
        while True:
            try:
                message = await websocket.recv()
                data = json.loads(message)
                symbol = data['s']
                price = float(data['c'])
                spot_prices[symbol] = price
            except Exception as e:
                logging.error(f"Error receiving WebSocket message: {e}")
                await asyncio.sleep(5)


# Function to calculate arbitrage opportunities
def calculate_arbitrage(pair, trade_amount):
    try:
        if pair not in spot_prices:
            return -1

        bid_price = spot_prices[pair]  # Use spot prices from WebSocket updates
        ask_price = spot_prices[pair]  # You can modify this to get the bid/ask separately if needed

        # Profit Calculation
        buy_cost = trade_amount * ask_price
        sell_revenue = trade_amount * bid_price
        fee_cost = trade_amount * ask_price * TRADING_FEE * 2  # Apply fee for both buy and sell
        profit = (sell_revenue - buy_cost) - fee_cost

        return profit
    except Exception as e:
        logging.error(f"Error calculating arbitrage for {pair}: {e}")
        return -1


# Main loop for arbitrage detection
async def main_arbitrage_loop():
    pairs = get_liquid_pairs()
    if not pairs:
        logging.error("No tradable pairs available. Exiting.")
        return

    # Start the WebSocket for price updates
    asyncio.create_task(handle_socket_message(pairs))

    logging.info("Starting triangular arbitrage detection loop...")
    while True:
        try:
            logging.info(f"Checking for arbitrage opportunities across {len(pairs)} pairs...")

            best_pair = None
            best_profit = -1

            for pair in pairs:
                profit = calculate_arbitrage(pair, TRADE_AMOUNT)
                if profit > best_profit:
                    best_profit = profit
                    best_pair = pair

            if best_profit > MIN_PROFIT_THRESHOLD:
                logging.info(f"Most profitable arbitrage opportunity found: {best_pair} with profit {best_profit:.2f} USDT")
            else:
                logging.info("No profitable arbitrage found.")

            await asyncio.sleep(1)
        except Exception as e:
            logging.error(f"Error in main loop: {e}")
            await asyncio.sleep(5)


if __name__ == "__main__":
    logging.info("Triangular Arbitrage Bot Starting...")
    logging.info(f"Minimum Liquidity: {LIQUIDITY_THRESHOLD} USDT")
    logging.info(f"Trade Amount: {TRADE_AMOUNT} USDT")
    logging.info(f"Dry Run Mode: {'Yes' if DRY_RUN else 'No'}")
    asyncio.run(main_arbitrage_loop())