The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Monitor cryptocurrency prices with Python

Monitoring cryptocurrency prices with Python can be done efficiently using several APIs and libraries. Below is a detailed guide and example to help you build a Python script that tracks live crypto prices, including fetching, processing, and displaying data.


Setting Up Your Environment

First, ensure you have Python installed (Python 3.6+ recommended). You’ll also need some libraries:

  • requests for API calls

  • pandas for data handling (optional, but useful)

  • time for scheduling updates

Install these with:

bash
pip install requests pandas

Choosing a Cryptocurrency API

Several APIs provide real-time crypto price data, such as:

  • CoinGecko API (free, no API key required)

  • CoinMarketCap API (requires API key)

  • Binance API (for exchange-specific data)

For simplicity, this example uses the CoinGecko API since it’s free and easy to use.


Example: Monitoring Prices with CoinGecko API

python
import requests import time import pandas as pd def fetch_price(crypto_id='bitcoin', currency='usd'): url = f'https://api.coingecko.com/api/v3/simple/price?ids={crypto_id}&vs_currencies={currency}' try: response = requests.get(url) response.raise_for_status() data = response.json() return data[crypto_id][currency] except requests.RequestException as e: print(f"Error fetching price: {e}") return None def monitor_prices(crypto_list, currency='usd', interval=60, duration=600): """ Monitors crypto prices over time. :param crypto_list: List of cryptocurrency IDs (as per CoinGecko) :param currency: Currency to convert into (e.g., 'usd') :param interval: Seconds between fetches :param duration: Total monitoring time in seconds """ start_time = time.time() records = [] while (time.time() - start_time) < duration: prices = {} timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) for crypto in crypto_list: price = fetch_price(crypto, currency) prices[crypto] = price print(f"{timestamp} | {crypto.capitalize()}: {price} {currency.upper()}") records.append({'timestamp': timestamp, **prices}) time.sleep(interval) # Convert to DataFrame for analysis or saving df = pd.DataFrame(records) print("nSummary of recorded prices:") print(df) # Optionally, save to CSV df.to_csv('crypto_price_log.csv', index=False) if __name__ == '__main__': cryptos_to_track = ['bitcoin', 'ethereum', 'dogecoin'] monitor_prices(cryptos_to_track, currency='usd', interval=30, duration=300)

Explanation

  • fetch_price: Fetches the current price for a given cryptocurrency ID and fiat currency using CoinGecko’s /simple/price endpoint.

  • monitor_prices: Repeatedly fetches prices for multiple cryptocurrencies at fixed intervals (default every 60 seconds) over a total duration.

  • The data is printed with timestamps and collected into a pandas DataFrame, which can be analyzed or saved to CSV.


Extending the Script

  1. Multiple fiat currencies: Modify the API call to include more than one currency.

  2. Alerts: Add conditions to notify you via email or SMS if prices hit certain thresholds.

  3. Visualization: Use matplotlib or plotly to plot price changes over time.

  4. More detailed data: Use endpoints that provide volume, market cap, or historical data.

  5. Web dashboard: Integrate with Flask/Django for a live web interface.


Handling Rate Limits and API Restrictions

  • CoinGecko’s free tier has generous limits but avoid excessive calls.

  • For production, consider caching and limiting requests.

  • For other APIs (e.g., CoinMarketCap), register and use API keys responsibly.


This approach provides a straightforward and flexible way to monitor cryptocurrency prices with Python, suitable for beginners and advanced users alike.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About