How to Build a Python Crypto Arbitrage Bot (Python Guide)
July 15, 2024 | by stockcoin.net
![how-to-build-a-python-crypto-arbitrage-bot-python-guide](https://i0.wp.com/stockcoin.net/wp-content/uploads/2024/07/how-to-build-a-python-crypto-arbitrage-bot-python-guide.png?resize=1110%2C540&ssl=1)
![How to Build a Python Crypto Arbitrage Bot (Python Guide) 1 Crash game 400x200 1](https://i0.wp.com/stockcoin.net/wp-content/uploads/2024/08/Crash_game_400x200-1.gif?resize=400%2C200&ssl=1)
In the intricate realm of cryptocurrency trading, arbitrage plays a pivotal role by exploiting price discrepancies across multiple exchanges to generate profit. This Python guide meticulously details the construction of a crypto arbitrage bot capable of identifying real-time arbitrage opportunities. Using demo endpoints from the CoinGecko API, the guide outlines the retrieval of various data points, such as crypto prices and exchange volumes, which are vital for an effective arbitrage strategy. Essential Python libraries like Pandas and Numpy are employed to streamline data handling and visualization, ensuring traders can efficiently monitor and capitalize on lucrative arbitrage scenarios. This tutorial is a comprehensive resource for fintech enthusiasts aiming to enhance their trading toolkit with Python-based automation, all while maintaining a clear disclaimer on the inherent risks of trading. What is arbitrage, and how can it be leveraged within the realm of cryptocurrencies?
Arbitrage, a well-known strategy in traditional finance, involves the simultaneous purchase and sale of an asset across different markets to exploit price variances and generate profit. In the cryptocurrency space, this strategy becomes even more intriguing, given the 24/7 trading environment and the multitude of exchanges available worldwide. This constant and decentralized trading leads to price discrepancies that can be profitable for those equipped to take advantage of them.
Introduction
In this professional guide, we’ll walk you through the steps needed to build a Python-based arbitrage bot. This bot will help identify arbitraging opportunities by tracking crypto prices and other useful metrics across exchanges. Please keep in mind that this guide focuses on identifying arbitrage opportunities and does not delve into the complexities of executing trades on exchanges.
We’ll utilize the CoinGecko API to gather necessary data. The API is free to access but does require keyed authentication.
Prerequisites
To get started, there are several prerequisites you’ll need to satisfy:
Software and Libraries
You’ll need Python 3. Additionally, the following Python packages must be installed:
-
jupyterlab
-
pandas
-
numpy
-
pytz
You can install these packages using pip:
pip install jupyterlab pip install pandas pip install numpy pip install pytz
Setting Up Jupyter Notebook
To start coding in a new notebook, execute the following command:
jupyter lab
This will launch a Jupyter notebook interface within a new tab of your default web browser.
Setting Up the Project Environment and API Access
In your Jupyter notebook, start by loading the necessary Python libraries and setting up your environment. Here is a sample code snippet to get you started:
import pandas as pd import numpy as np import requests from datetime import datetime from pytz import timezone import time from IPython.display import clear_output
pd.set_option(‘display.max_rows’, 100) pd.set_option(‘display.max_columns’, 20) pd.set_option(‘display.width’, 1000)
API Key Access
To access the CoinGecko API, you first need to generate an API key. Save this key locally and read it in your notebook:
with open(‘coingecko_api_key.txt’, ‘r’) as file: api_key = file.read().strip()
Define a helper function for making API requests:
def get_response(endpoint, params=None): headers = { ‘accept’: ‘application/json’, ‘x-cg-pro-api-key’: api_key } response = requests.get(endpoint, headers=headers, params=params) if response.status_code == 200: return response.json() else: print(f”Error: “) return None
Retrieving Data from CoinGecko API
Listing All Crypto Exchanges
To get the list of all crypto exchanges, use the /exchanges
endpoint:
endpoint = “https://api.coingecko.com/api/v3/exchanges” params = {‘per_page’: 250, ‘page’: 1} data = get_response(endpoint, params=params) exchanges_df = pd.DataFrame(data)
Filtering and Sorting Exchanges
You can sort exchanges by trading volume or filter them based on their country of operation. Here’s how to filter US-based exchanges:
us_exchanges = exchanges_df[exchanges_df[‘country’] == ‘United States’] us_exchanges = us_exchanges.sort_values(by=’trade_volume_24h_btc’, ascending=False)
This will give you a DataFrame with exchanges in the US, sorted by their trading volume in BTC over the last 24 hours.
Fetching Exchange Tickers
For each exchange, you can fetch trading pairs (tickers) using the /exchanges//tickers
endpoint:
def get_ticker_data(exchange_id): endpoint = f”https://api.coingecko.com/api/v3/exchanges//tickers” data = get_response(endpoint) return data.get(‘tickers’, [])
By combining these steps, you can gather data on a specific trading pair across multiple exchanges. For example, to get the price for the ETH-USD pair on Coinbase:
tickers = get_ticker_data(‘gdax’) # id for Coinbase eth_usd_ticker = next((ticker for ticker in tickers if ticker[‘base’] == ‘ETH’ and ticker[‘target’] == ‘USD’), {}) print(eth_usd_ticker)
Time Conversion
Data from APIs often comes in UTC. Use the pytz
library to convert timestamps to your local timezone:
utc_time = datetime.strptime(eth_usd_ticker[‘timestamp’], ‘%Y-%m-%dT%H:%M:%S+00:00’) local_time = utc_time.replace(tzinfo=timezone(‘UTC’)).astimezone(timezone(‘Europe/Amsterdam’)) print(local_time)
Monitoring Multiple Exchanges
Gathering Ticker Data
Extend the logic to gather ticker data across multiple exchanges. For enhanced analysis, you can filter exchanges by country and monitor specific trading pairs.
selected_exchanges = us_exchanges[‘id’].tolist() ticker_data = []
for exchange_id in selected_exchanges: tickers = get_ticker_data(exchange_id) eth_usd_ticker = next((t for t in tickers if t[‘base’] == ‘ETH’ and t[‘target’] == ‘USD’), {}) if eth_usd_ticker: eth_usd_ticker[‘exchange’] = exchange_id ticker_data.append(eth_usd_ticker) else: print(f”Ticker not found on “)
tickers_df = pd.DataFrame(ticker_data)
Calculating the Spread
Calculate the bid-ask spread and other relevant metrics:
tickers_df[‘spread’] = (tickers_df[‘ask’] – tickers_df[‘bid’]) / tickers_df[‘ask’] * 100 tickers_df = tickers_df.sort_values(by=’spread’)
Conversion of Volume Data
Convert volume data from BTC to another currency using the /exchange_rates
endpoint:
btc_to_usd_rate = get_response(“https://api.coingecko.com/api/v3/exchange_rates”).get(‘rates’).get(‘usd’).get(‘value’) tickers_df[‘converted_volume’] = tickers_df[‘trade_volume_24h_btc’] * btc_to_usd_rate
Historical Exchange Volume
Access historical volume data to understand trading trends and liquidity:
def get_historical_volume(exchange_id, days=30): endpoint = f”https://api.coingecko.com/api/v3/exchanges//volume_chart” params = {‘days’: days} data = get_response(endpoint, params=params) return pd.DataFrame(data, columns=[“timestamp”, “volume”])
kraken_volume_df = get_historical_volume(“kraken”)
Calculate a moving average of volume:
kraken_volume_df[‘volume_ma’] = kraken_volume_df[‘volume’].rolling(window=7).mean()
Aggregating and Displaying Data
Aggregation Over Time
When running an arbitrage bot, aggregating data over trading intervals is crucial. Group the data by exchange and calculate relevant statistics:
agg_data = tickers_df.groupby(‘exchange’).agg({ ‘last’: ‘mean’, ‘bid’: ‘mean’, ‘ask’: ‘mean’, ‘spread’: ‘mean’, ‘volume’: ‘sum’, ‘converted_volume’: ‘sum’ }).reset_index()
Highlight exchanges with maximum and minimum prices:
def highlight_extremes(data, col): if col == ‘last’: high = data[‘last’].max() low = data[‘last’].min() data[‘highlight’] = data[‘last’].apply(lambda x: ‘background-color: green’ if x == low else (‘background-color: red’ if x == high else ”)) return data
highlighted_df = highlight_extremes(agg_data, ‘last’) highlighted_df.style.applymap(lambda x: x, subset=[‘highlight’])
Running the Crypto Exchange Arbitrage Bot
Continuous Monitoring
For continuous monitoring, use a loop to update the data at specified intervals:
while True: ticker_data = []
for exchange_id in selected_exchanges: tickers = get_ticker_data(exchange_id) eth_usd_ticker = next((t for t in tickers if t['base'] == 'ETH' and t['target'] == 'USD'), {}) if eth_usd_ticker: eth_usd_ticker['exchange'] = exchange_id ticker_data.append(eth_usd_ticker) else: print(f"Ticker not found on ") tickers_df = pd.DataFrame(ticker_data) tickers_df['spread'] = (tickers_df['ask'] - tickers_df['bid']) / tickers_df['ask'] * 100 agg_data = tickers_df.groupby('exchange').agg({ 'last': 'mean', 'bid': 'mean', 'ask': 'mean', 'spread': 'mean', 'volume': 'sum', 'converted_volume': 'sum' }).reset_index() clear_output(wait=True) display(agg_data.sort_values(by='spread')) time.sleep(60) # delay in seconds
Stopping the Bot
To halt the bot’s execution, simply interrupt the kernel within Jupyter by navigating to the “Kernel” tab and selecting “Interrupt Kernel”.
Conclusion
Leveraging Python and CoinGecko’s API within a Jupyter notebook, you can efficiently monitor multiple crypto exchanges to identify arbitrage opportunities. While this guide does not cover trade execution, it forms a solid foundation upon which more comprehensive trading strategies can be built.
If you found this guide useful, be sure to explore our extensive collection of other API guides and resources. Happy trading!
![How to Build a Python Crypto Arbitrage Bot (Python Guide) 1 Crash game 400x200 1](https://i0.wp.com/stockcoin.net/wp-content/uploads/2024/08/Crash_game_400x200-1.gif?resize=400%2C200&ssl=1)
RELATED POSTS
View all