Skip to content

holgern/pyccxt

Repository files navigation

pyccxt

A Python library for accessing cryptocurrency exchange data via CCXT. Get ticker prices and market volumes across different exchanges with aggregated analysis capabilities.

Python 3.9+ License: MIT Code style: ruff codecov

Overview

pyccxt provides a unified interface to access cryptocurrency market data from multiple exchanges. Built on top of the popular CCXT library, it offers:

  • Price aggregation across multiple exchanges
  • Volume analysis by market and currency
  • CLI tools for quick market data access
  • Market comparison and analysis
  • Exchange filtering by features and supported pairs

Installation

pip install pyccxt

Development Installation

git clone https://github.com/holgern/pyccxt.git
cd pyccxt
pip install -e .

Quick Start

Python API

from pyccxt import Exchange

# Initialize exchange
exchange = Exchange("binance")

# Get market volumes
volumes = exchange.get_market_volumes(
    filter_base="BTC",
    normalize_to="USD",
    limit=10,
)
for volume_data in volumes:
    print(
        f"{volume_data['symbol']}: "
        f"{volume_data['normalizedVolume']:.2f} "
        f"{volume_data['normalizedCurrency']}"
    )

# Get price for specific pair
market = exchange.get_market("BTC/USDT")
if market:
    ticker = market.get_ticker()
    print(f"BTC/USDT: ${ticker.last:.2f}")

Command Line Interface

# Get price for a trading pair
pyccxt price BTC USD --market binance

# Render an OHLCV-derived ASCII chart
pyccxt chart BTC USDT --market kraken --timeframe 1h --limit 60

# Fetch OHLCV candles and print the table
pyccxt ohlcv BTC USDT --market kraken --timeframe 4h --limit 90 --table

# Show market volumes
pyccxt volume --market binance --limit 10

# List available exchanges
pyccxt exchanges

# Filter exchanges by features
pyccxt exchanges --features --filter fetchOHLCV

Features

Exchange Data Access

  • Multiple Exchange Support: Access 100+ cryptocurrency exchanges
  • Unified API: Consistent interface across all exchanges
  • Market Data: Real-time prices, volumes, and market info
  • OHLC Data: Historical price data with multiple timeframes

Volume Analysis

from pyccxt import Exchange, get_market_volumes_for_pair

volumes = get_market_volumes_for_pair("BTC", "USDT", max_exchanges=5)
for vol in volumes:
    print(
        f"{vol['exchange']}: {vol['normalizedVolume']:.2f} "
        f"{vol['normalizedCurrency']}"
    )

Market Filtering

# Get markets by base currency
btc_markets = exchange.get_markets_by_base("BTC")

# Get markets by quote currency
usd_markets = exchange.get_markets_by_quote("USD")

# Filter by minimum volume
high_volume = exchange.get_market_volumes(normalize_to="USD", min_volume=1000000)

CLI Usage

Price Commands

# Basic price lookup
pyccxt price BTC USD

# Specify exchange
pyccxt price ETH EUR --market kraken

# Get detailed price info with spread and 24h change
pyccxt price BTC USDT --market binance

Volume Commands

# Show top volumes for an exchange
pyccxt volume --market binance --normalize-to USD --limit 20

# Filter by quote currency
pyccxt volume --market coinbase --quote USD --normalize-to USD --limit 15

# Compare volumes across exchanges
pyccxt volume --market binance,kraken,coinbase --base BTC --compare --normalize-to USD

Chart Commands

# Plot close prices derived from fetched OHLCV candles
pyccxt chart BTC USDT --market kraken --timeframe 1h --limit 60

# Plot a different OHLC-derived series and print the underlying price rows
pyccxt chart ETH USD --market coinbase --timeframe 15m --limit 80 --price-type high --table

# Fetch candles, render a close-price plot, and print OHLCV rows
pyccxt ohlcv BTC USDT --market kraken --timeframe 4h --limit 90 --table

# Plot the typical price while keeping candle output optional
pyccxt ohlcv ETH EUR --market kraken --timeframe 1d --limit 30 --plot-price typical
  • chart fetches OHLCV data first and plots one derived price series.
  • ohlcv uses the same OHLCV fetch path, plots one selected series, and can print full candle rows.
  • --table prints the underlying rows used by each command.

Exchange Commands

# List all exchanges
pyccxt exchanges

# Show exchange features
pyccxt exchanges --features

# Filter by supported features
pyccxt exchanges --filter fetchOHLCV,fetchTicker

# Filter by supported trading pairs
pyccxt exchanges --base BTC --quote USD

API Reference

Exchange Class

from pyccxt import Exchange

exchange = Exchange("binance")

Methods

  • get_market(symbol) - Get Market instance for symbol
  • get_markets_by_base(currency) - Filter by base currency
  • get_markets_by_quote(currency) - Filter by quote currency
  • get_market_volumes(filter_base=None, filter_quote=None, normalize_to="USD", min_volume=0, limit=None, include_unconverted=True) - Get volume rows with explicit filters and normalization
  • fetch_all_tickers() - Get all ticker data
  • get_total_volume(filter_base=None, filter_quote=None, normalize_to="USD", min_volume=0, include_unconverted=False) - Get total normalized exchange volume
  • get_volume_by_quote_currency() - Get quote-native totals grouped by quote currency
  • get_volume_by_base_currency() - Get base-native totals grouped by base currency

Market Class

market = exchange.get_market("BTC/USDT")

Methods

  • get_ticker() - Get current price ticker
  • get_price() - Get current price
  • refresh() - Update market data
  • fetch_ohlc(timeframe, limit) - Get OHLC data

Ticker Class

ticker = market.get_ticker()
print(f"Price: {ticker.last}")
print(f"24h Change: {ticker.percentage}%")
print(f"Volume: {ticker.quoteVolume}")

Examples

Market Volume Analysis

from pyccxt import Exchange

def analyze_btc_markets():
    """Analyze BTC trading volumes across top exchanges."""

    # Top exchanges by volume
    exchanges = ["binance", "coinbase", "kraken", "huobi", "okx"]

    total_volumes = {}

    for exchange_name in exchanges:
        try:
            exchange = Exchange(exchange_name)
            btc_volumes = exchange.get_market_volumes(
                filter_base="BTC",
                normalize_to="USD",
                limit=10,
            )

            total_vol = sum(vol["normalizedVolume"] or 0 for vol in btc_volumes)
            total_volumes[exchange_name] = total_vol

            print(f"{exchange_name}: {total_vol:.2f} USD normalized volume")

        except Exception as e:
            print(f"Error with {exchange_name}: {e}")

    # Sort by volume
    sorted_exchanges = sorted(
        total_volumes.items(),
        key=lambda x: x[1],
        reverse=True
    )

    print("\\nTop exchanges by normalized BTC market volume:")
    for exchange, volume in sorted_exchanges:
        print(f"{exchange}: {volume:.2f} USD")

if __name__ == "__main__":
    analyze_btc_markets()

Price Comparison

from pyccxt import Exchange, get_market_volumes_for_pair

def compare_prices(base="BTC", quote="USDT"):
    """Compare prices across multiple exchanges."""

    volumes = get_market_volumes_for_pair(base, quote, max_exchanges=10)

    prices = []
    for vol_data in volumes:
        exchange_name = vol_data["exchange"]
        try:
            exchange = Exchange(exchange_name)
            market = exchange.get_market(f"{base}/{quote}")
            if market:
                ticker = market.get_ticker()
                if ticker and ticker.last:
                    prices.append(
                        {
                            "exchange": exchange_name,
                            "price": ticker.last,
                            "normalizedVolume": vol_data["normalizedVolume"],
                            "normalizedCurrency": vol_data["normalizedCurrency"],
                        }
                    )
        except Exception as e:
            print(f"Error getting price from {exchange_name}: {e}")

    # Sort by price
    prices.sort(key=lambda x: x["price"])

    print(f"\\n{base}/{quote} Price Comparison:")
    for price_data in prices:
        print(
            f"{price_data['exchange']}: ${price_data['price']:.2f} "
            f"(Vol: {price_data['normalizedVolume']:.2f} "
            f"{price_data['normalizedCurrency']})"
        )

if __name__ == "__main__":
    compare_prices("BTC", "USDT")
    compare_prices("ETH", "USD")

Configuration

Exchange Construction

# Supported constructor options
exchange = Exchange("binance", min_refresh_time=60, timeout=30000)

Development

Setup

git clone https://github.com/holgern/pyccxt.git
cd pyccxt
pip install -e .
pip install -r requirements-test.txt

Testing

# Run all tests
pytest

# Run with coverage
pytest --cov=pyccxt

# Run specific test
pytest -k "test_exchange"

Code Quality

# Format and lint
ruff check .
ruff format .

# Run pre-commit hooks
pre-commit run --all-files

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Make your changes and add tests
  4. Run the test suite: pytest
  5. Run linting: ruff check .
  6. Commit your changes: git commit -am 'Add feature'
  7. Push to the branch: git push origin feature-name
  8. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Built on top of CCXT - Cryptocurrency trading library
  • CLI powered by Typer and Rich
  • Inspired by the need for unified cryptocurrency market analysis

Changelog

Latest Changes

  • Modern Python type hints with X | None syntax
  • Comprehensive CLI with market filtering
  • Volume aggregation across exchanges
  • Market comparison tools
  • Improved error handling and logging

Support

  • Issues: GitHub Issues
  • Documentation: This README and inline code documentation
  • Examples: See the examples/ directory for usage examples

Note: This library is for informational purposes only. Always verify data from multiple sources before making trading decisions.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages