Metadata-Version: 2.4
Name: pyccxt
Version: 0.1.0
Summary: Python lib for accessing ccxt
Author-email: Holger Nahrstaedt <nahrstaedt@gmail.com>
License: MIT License
        
        Copyright (c) 2025 Holger Nahrstaedt
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/holgern/pyccxt
Keywords: price,ccxt,ticker
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: urllib3
Requires-Dist: typer
Requires-Dist: rich
Requires-Dist: requests
Requires-Dist: ccxt>=4.5.42
Requires-Dist: asciiplot
Dynamic: license-file

# 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+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Code style: ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)

## Overview

pyccxt provides a unified interface to access cryptocurrency market data from multiple
exchanges. Built on top of the popular [CCXT](https://github.com/ccxt/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

```bash
pip install pyccxt
```

### Development Installation

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

## Quick Start

### Python API

```python
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

```bash
# 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

```python
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

```python
# 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

```bash
# 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

```bash
# 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

```bash
# 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

```bash
# 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

```python
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

```python
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

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

## Examples

### Market Volume Analysis

```python
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

```python
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

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

## Development

### Setup

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

### Testing

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=pyccxt

# Run specific test
pytest -k "test_exchange"
```

### Code Quality

```bash
# 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](LICENSE) file for
details.

## Acknowledgments

- Built on top of [CCXT](https://github.com/ccxt/ccxt) - Cryptocurrency trading library
- CLI powered by [Typer](https://typer.tiangolo.com/) and
  [Rich](https://rich.readthedocs.io/)
- 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](https://github.com/holgern/pyccxt/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.
