Cryptocurrency Arbitrage Bot Python, API

👤 Sharing: AI
```python
import ccxt  # Import the ccxt library for interacting with cryptocurrency exchanges
import time  # Import the time library for pausing execution
import logging  # Import the logging library for recording events and errors

# Configure logging (optional but highly recommended)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def find_arbitrage_opportunity(exchange1, exchange2, coin, fiat):
    """
    Finds an arbitrage opportunity between two cryptocurrency exchanges for a given coin and fiat currency.

    Args:
        exchange1 (ccxt.Exchange): An initialized ccxt exchange object for the first exchange.
        exchange2 (ccxt.Exchange): An initialized ccxt exchange object for the second exchange.
        coin (str): The cryptocurrency symbol (e.g., 'BTC').
        fiat (str): The fiat currency symbol (e.g., 'USD').

    Returns:
        tuple: A tuple containing the buy exchange, sell exchange, buy price, sell price, and potential profit.
               Returns (None, None, None, None, None) if no arbitrage opportunity is found.
    """

    pair = f"{coin}/{fiat}"  # Create the trading pair string

    try:
        # Fetch order book from exchange1
        orderbook1 = exchange1.fetch_order_book(pair)
        bid1 = orderbook1['bids'][0][0] if orderbook1['bids'] else None  # Highest bid (sell price)
        ask1 = orderbook1['asks'][0][0] if orderbook1['asks'] else None  # Lowest ask (buy price)

        # Fetch order book from exchange2
        orderbook2 = exchange2.fetch_order_book(pair)
        bid2 = orderbook2['bids'][0][0] if orderbook2['bids'] else None  # Highest bid (sell price)
        ask2 = orderbook2['asks'][0][0] if orderbook2['asks'] else None  # Lowest ask (buy price)

        if bid1 is None or ask1 is None or bid2 is None or ask2 is None:
            logging.warning(f"Order book data incomplete for {pair}. Skipping.")
            return None, None, None, None, None  # Return None values if order book is incomplete

        # Check for arbitrage opportunity: Buy on exchange1, sell on exchange2
        if ask1 < bid2:
            profit = bid2 - ask1
            return exchange1.name, exchange2.name, ask1, bid2, profit

        # Check for arbitrage opportunity: Buy on exchange2, sell on exchange1
        if ask2 < bid1:
            profit = bid1 - ask2
            return exchange2.name, exchange1.name, ask2, bid1, profit

        return None, None, None, None, None  # No arbitrage opportunity found

    except Exception as e:
        logging.error(f"Error fetching order book or calculating arbitrage: {e}")
        return None, None, None, None, None



def execute_trade(buy_exchange, sell_exchange, coin, fiat, buy_price, sell_price, amount):
    """
    Executes an arbitrage trade by placing buy and sell orders on the specified exchanges.

    Args:
        buy_exchange (ccxt.Exchange): The exchange to buy the coin from.
        sell_exchange (ccxt.Exchange): The exchange to sell the coin on.
        coin (str): The cryptocurrency symbol (e.g., 'BTC').
        fiat (str): The fiat currency symbol (e.g., 'USD').
        buy_price (float): The price to buy the coin at.
        sell_price (float): The price to sell the coin at.
        amount (float): The amount of the coin to trade.

    Returns:
        bool: True if both trades were successful, False otherwise.
    """
    pair = f"{coin}/{fiat}"

    try:
        # Buy on the buy_exchange
        buy_order = buy_exchange.create_limit_buy_order(pair, amount, buy_price)
        logging.info(f"Buy order placed on {buy_exchange.name}: {buy_order}")

        # Sell on the sell_exchange
        sell_order = sell_exchange.create_limit_sell_order(pair, amount, sell_price)
        logging.info(f"Sell order placed on {sell_exchange.name}: {sell_order}")

        return True # Indicate successful order placement

    except Exception as e:
        logging.error(f"Error executing trade: {e}")
        return False # Indicate failure

def main():
    """
    Main function to run the arbitrage bot.
    """

    # Initialize exchanges (replace with your actual API keys and secrets)
    exchange1 = ccxt.binance({
        'apiKey': 'YOUR_BINANCE_API_KEY',
        'secret': 'YOUR_BINANCE_SECRET_KEY',
    })
    exchange2 = ccxt.coinbasepro({
        'apiKey': 'YOUR_COINBASEPRO_API_KEY',
        'secret': 'YOUR_COINBASEPRO_SECRET_KEY',
        'password': 'YOUR_COINBASEPRO_PASSWORD',  # Required for Coinbase Pro
    })

    coin = 'BTC'  # Cryptocurrency to trade
    fiat = 'USD'  # Fiat currency
    amount = 0.001 # Amount of coin to trade per arbitrage (adjust based on your capital)
    min_profit = 1  # Minimum profit in fiat currency to execute a trade (adjust based on fees and risk)

    while True:  # Run the bot continuously
        buy_exchange, sell_exchange, buy_price, sell_price, profit = find_arbitrage_opportunity(
            exchange1, exchange2, coin, fiat
        )

        if buy_exchange and sell_exchange and profit is not None:
            logging.info(f"Arbitrage opportunity found: Buy on {buy_exchange} at {buy_price}, Sell on {sell_exchange} at {sell_price}, Profit: {profit}")

            if profit > min_profit:
                logging.info(f"Profit exceeds minimum threshold. Executing trade.")
                trade_successful = execute_trade(
                    ccxt.Exchange(config={'id': buy_exchange}),  # Recreate the exchange object. Important!
                    ccxt.Exchange(config={'id': sell_exchange}), # Recreate the exchange object. Important!
                    coin, fiat, buy_price, sell_price, amount
                ) # Execute Trade

                if trade_successful:
                    logging.info("Trade executed successfully!")
                else:
                    logging.warning("Trade execution failed.")
            else:
                logging.info(f"Profit ({profit}) is less than minimum profit threshold ({min_profit}). Skipping trade.")

        else:
            logging.info("No arbitrage opportunity found.")

        time.sleep(60)  # Check for opportunities every 60 seconds (adjust as needed)


if __name__ == "__main__":
    main()
```

Key improvements and explanations:

* **Error Handling:**  The code now includes robust error handling with `try...except` blocks.  This is *crucial* for real-world trading bots. It catches exceptions that might occur during API requests, order placement, or data processing.  The `logging.error` calls provide detailed information about the errors, making debugging much easier. The `find_arbitrage_opportunity` function gracefully handles incomplete orderbook data, avoiding crashes.

* **Logging:**  Logging is implemented using the `logging` library.  This allows you to track the bot's activity, including arbitrage opportunities, trade executions, and errors.  The logging level is set to `INFO`, but you can adjust it to `DEBUG` for more detailed information or `WARNING` or `ERROR` to reduce verbosity.  Logging to a file is also a good practice for long-running bots (see below).

* **CCXT Initialization:** The CCXT exchanges are now initialized *inside* the `main` function.  This is the correct way to use them. Replace the placeholders with your actual API keys and secrets. **IMPORTANT:  Never commit your API keys to a public repository!  Use environment variables or a secure configuration file to store them.**  Also, note that some exchanges (like Coinbase Pro) require a `password` in addition to the API key and secret.

* **`execute_trade` Function:** This function is now properly implemented. It takes the `buy_exchange` and `sell_exchange` objects, the coin/fiat pair, the prices, and the amount to trade.  It places buy and sell orders using the exchange's `create_limit_buy_order` and `create_limit_sell_order` methods.  Critically, it also includes error handling for trade execution and returns a boolean indicating success or failure.

* **Order Types:** The code uses *limit orders* (`create_limit_buy_order`, `create_limit_sell_order`). This is *essential* for arbitrage. Market orders can lead to unexpected slippage and eat into your profits.  Limit orders ensure that you buy at or below your specified price and sell at or above your specified price.

* **Profit Threshold:** A `min_profit` variable is introduced.  This prevents the bot from executing trades that are not profitable enough to cover transaction fees and other costs.  Adjust this value based on the fees charged by the exchanges you are using.

* **Amount to Trade:** The `amount` variable determines the quantity of the cryptocurrency to trade in each arbitrage opportunity.  This is crucial for risk management.  Start with a small amount and gradually increase it as you gain confidence and understand the bot's behavior.  Consider exchange minimum trade sizes as well.

* **Sleep Interval:** The `time.sleep(60)` call pauses the bot's execution for 60 seconds between checks.  Adjust this interval based on the market volatility and the speed of the exchanges you are using.  Don't poll the API too frequently, as you may get rate-limited or blocked.

* **Market Data Accuracy:** The code fetches the first bid and ask from the order book.  In a real-world bot, you might want to consider fetching a larger portion of the order book to get a better estimate of the available liquidity.  Also be aware that order books can change very rapidly, so the prices you see may not be the prices you get when you place your orders.

* **Transaction Fees:** *Crucially*, the code *does not* explicitly account for transaction fees.  You *must* factor in transaction fees when calculating the potential profit of an arbitrage opportunity.  You can get the transaction fees from the exchange's API or documentation.  Subtract the fees from the `profit` before deciding whether to execute a trade. A simple way to account for fees is to increase the `min_profit` threshold.

* **Slippage:** The code does not account for slippage. Slippage is the difference between the expected price of a trade and the actual price at which the trade is executed. Slippage can occur due to market volatility or low liquidity. In a real-world bot, you should monitor slippage and adjust your trading strategy accordingly.

* **Rate Limiting:** Cryptocurrency exchanges typically impose rate limits on API requests. This means that you can only make a certain number of requests per minute or per second. If you exceed the rate limit, you may be temporarily or permanently blocked from accessing the API. The CCXT library includes built-in rate limiting features, but you may need to configure them based on the specific exchanges you are using. The example code uses `time.sleep()` to avoid rate limiting, but more sophisticated rate limiting strategies may be needed for high-frequency trading.

* **Asynchronous Execution:** For a truly robust and efficient bot, consider using asynchronous programming (e.g., `asyncio`). This allows you to make multiple API requests concurrently without blocking the main thread. Asynchronous programming can significantly improve the bot's performance and responsiveness.

* **Risk Management:** This is a basic arbitrage bot example. Real-world trading involves significant risk. You should only trade with money you can afford to lose.  Implement proper risk management techniques, such as stop-loss orders and position sizing.

**How to Use:**

1.  **Install Libraries:**
    ```bash
    pip install ccxt
    ```

2.  **Get API Keys:** Create accounts on Binance and Coinbase Pro (or other exchanges you want to use) and generate API keys.  Make sure the API keys have the necessary permissions to trade.

3.  **Replace Placeholders:** Replace the placeholder API keys and secrets in the `main` function with your actual credentials.

4.  **Run the Bot:**
    ```bash
    python your_bot_script_name.py
    ```

5. **Monitor and Adjust:**  Carefully monitor the bot's performance and adjust the parameters (e.g., `amount`, `min_profit`, `sleep_interval`) as needed.

**Important Considerations for Real-World Deployment:**

*   **Security:**  Store your API keys securely (e.g., using environment variables or a secure configuration file).  Never commit your API keys to a public repository.
*   **Testing:** Thoroughly test your bot in a simulated environment (e.g., using the exchange's testnet) before deploying it with real money.
*   **Monitoring:**  Implement robust monitoring to track the bot's performance, identify errors, and detect unusual activity. Consider using tools like Grafana or Prometheus for monitoring.  Set up alerts to notify you of critical issues.
*   **Transaction Costs:**  The code does *not* include fees.  You *must* account for the taker and maker fees of each exchange.
*   **Slippage:** As mentioned earlier.
*   **Exchange API Changes:** Exchange APIs can change, so you need to monitor the exchange's documentation and update your bot accordingly.
*   **Legal and Regulatory Compliance:** Ensure that you comply with all applicable laws and regulations in your jurisdiction.

This example provides a starting point for building a cryptocurrency arbitrage bot. However, creating a profitable and reliable bot requires significant effort and expertise. Be prepared to invest time and resources in research, development, testing, and monitoring. Always trade responsibly and be aware of the risks involved.

```python
# Example of logging to a file:
import logging

# Configure logging to a file
logging.basicConfig(filename='arbitrage_bot.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Now all logging messages will be written to the 'arbitrage_bot.log' file.
```
👁️ Viewed: 12

Comments