CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cryptofeed

Cryptocurrency Exchange Websocket Data Feed Handler for normalized market data across 30+ exchanges

Pending
Overview
Eval results
Files

types.mddocs/

Data Types

Fast Cython-based data structures representing different types of market data with standardized formats across all exchanges. All data types provide consistent interfaces and automatic type conversion methods.

Capabilities

Core Market Data Types

Primary data structures for market data that are normalized across all exchanges.

class Trade:
    """Represents a completed trade/transaction."""
    exchange: str
    symbol: str
    side: str          # BUY or SELL
    amount: float
    price: float
    timestamp: float
    id: str
    type: str
    raw: dict
    
    @staticmethod
    def from_dict(data: dict): ...
    def to_dict(self, numeric_type=None, none_to=False): ...

class Ticker:
    """Represents ticker/quote data with best bid/ask."""
    exchange: str
    symbol: str
    bid: float
    ask: float
    timestamp: float
    raw: dict
    
    @staticmethod
    def from_dict(data: dict): ...
    def to_dict(self, numeric_type=None, none_to=False): ...

class OrderBook:
    """Represents order book data with bids and asks."""
    exchange: str
    symbol: str
    book: dict         # Contains bids and asks dictionaries
    delta: bool        # True if this is a delta update
    sequence_number: int
    checksum: int
    timestamp: float
    raw: dict
    
    @staticmethod
    def from_dict(data: dict): ...
    def to_dict(self, delta=False, numeric_type=None, none_to=False): ...

class L1Book:
    """Represents Level 1 order book (best bid/ask only)."""
    exchange: str
    symbol: str
    bid_price: float
    bid_size: float
    ask_price: float
    ask_size: float
    timestamp: float
    raw: dict
    
    def to_dict(self, numeric_type=None, none_to=False): ...

class Candle:
    """Represents OHLCV candlestick data."""
    exchange: str
    symbol: str
    start: float       # Start timestamp
    stop: float        # End timestamp  
    interval: str      # Time interval (1m, 5m, 1h, etc.)
    trades: int        # Number of trades in period
    open: float
    close: float
    high: float
    low: float
    volume: float
    closed: bool       # True if candle is closed/finalized
    timestamp: float
    raw: dict
    
    @staticmethod
    def from_dict(data: dict): ...
    def to_dict(self, numeric_type=None, none_to=False): ...

Derivatives and Advanced Data

Data types for futures, options, and advanced market data.

class Funding:
    """Represents funding rate data for perpetual contracts."""
    exchange: str
    symbol: str
    mark_price: float
    rate: float               # Current funding rate
    next_funding_time: float  # Next funding timestamp
    predicted_rate: float     # Predicted next funding rate
    timestamp: float
    raw: dict
    
    @staticmethod
    def from_dict(data: dict): ...
    def to_dict(self, numeric_type=None, none_to=False): ...

class OpenInterest:
    """Represents open interest data for derivatives."""
    exchange: str
    symbol: str
    open_interest: float
    timestamp: float
    raw: dict
    
    def to_dict(self, numeric_type=None, none_to=False): ...

class Liquidation:
    """Represents liquidation events."""
    exchange: str
    symbol: str
    side: str          # BUY or SELL
    quantity: float
    price: float
    id: str
    status: str
    timestamp: float
    raw: dict
    
    @staticmethod
    def from_dict(data: dict): ...
    def to_dict(self, numeric_type=None, none_to=False): ...

class Index:
    """Represents index price data."""
    exchange: str
    symbol: str
    price: float
    timestamp: float
    raw: dict
    
    def to_dict(self, numeric_type=None, none_to=False): ...

Account and Trading Data

Data types for authenticated account and trading information.

class Order:
    """Represents order placement data."""
    exchange: str
    symbol: str
    client_order_id: str
    side: str          # BUY or SELL
    type: str          # LIMIT, MARKET, etc.
    price: float
    amount: float
    account: str
    timestamp: float
    
    @staticmethod
    def from_dict(data: dict): ...
    def to_dict(self, numeric_type=None, none_to=False): ...

class OrderInfo:
    """Represents order status information."""
    exchange: str
    symbol: str
    id: str
    client_order_id: str
    side: str          # BUY or SELL
    status: str        # OPEN, FILLED, CANCELLED, etc.
    type: str          # LIMIT, MARKET, etc.
    price: float
    amount: float
    remaining: float   # Remaining amount to fill
    account: str
    timestamp: float
    raw: dict
    
    @staticmethod
    def from_dict(data: dict): ...
    def to_dict(self, numeric_type=None, none_to=False): ...
    def set_status(self, status: str): ...

class Fill:
    """Represents order fill/execution data."""
    exchange: str
    symbol: str
    price: float
    amount: float
    side: str          # BUY or SELL
    fee: float
    id: str
    order_id: str
    liquidity: str     # MAKER or TAKER
    type: str          # Order type
    account: str
    timestamp: float
    raw: dict
    
    def to_dict(self, numeric_type=None, none_to=False): ...

class Balance:
    """Represents account balance data."""
    exchange: str
    currency: str
    balance: float     # Total balance
    reserved: float    # Reserved/locked balance
    raw: dict
    
    def to_dict(self, numeric_type=None, none_to=False): ...

class Position:
    """Represents trading position data."""
    exchange: str
    symbol: str
    position: float    # Position size (positive for long, negative for short)
    entry_price: float
    side: str          # LONG, SHORT, or BOTH
    unrealised_pnl: float
    timestamp: float
    raw: dict
    
    def to_dict(self, numeric_type=None, none_to=False): ...

class Transaction:
    """Represents account transactions (deposits/withdrawals)."""
    exchange: str
    currency: str
    type: str          # DEPOSIT, WITHDRAWAL, etc.
    status: str        # PENDING, COMPLETED, etc.
    amount: float
    timestamp: float
    raw: dict
    
    def to_dict(self, numeric_type=None, none_to=False): ...

Usage Examples

Working with Trade Data

from cryptofeed.types import Trade

# Create trade from dictionary (typically from exchange API)
trade_data = {
    'exchange': 'coinbase',
    'symbol': 'BTC-USD',
    'side': 'buy',
    'amount': 0.1,
    'price': 50000.0,
    'timestamp': 1640995200.0,
    'id': 'trade-123'
}

trade = Trade.from_dict(trade_data)
print(f'Trade: {trade.side} {trade.amount} {trade.symbol} @ {trade.price}')

# Convert to dictionary for storage
trade_dict = trade.to_dict()
print(trade_dict)

Order Book Processing

from cryptofeed.types import OrderBook

def book_handler(book):
    """Process order book updates."""
    if book.delta:
        print(f'Book delta for {book.symbol}')
    else:
        print(f'Full book snapshot for {book.symbol}')
    
    # Access bids and asks
    bids = book.book['bids']  # Price -> Size mapping
    asks = book.book['asks']  # Price -> Size mapping
    
    if bids and asks:
        best_bid = max(bids.keys())
        best_ask = min(asks.keys())
        spread = best_ask - best_bid
        print(f'Best bid: {best_bid}, Best ask: {best_ask}, Spread: {spread}')

Candle Data Analysis

from cryptofeed.types import Candle

def candle_handler(candle):
    """Process candlestick data."""
    if candle.closed:
        # Only process completed candles
        price_change = candle.close - candle.open
        price_change_pct = (price_change / candle.open) * 100
        
        print(f'{candle.symbol} {candle.interval} candle:')
        print(f'  OHLCV: {candle.open}/{candle.high}/{candle.low}/{candle.close}/{candle.volume}')
        print(f'  Change: {price_change:.2f} ({price_change_pct:.2f}%)')
        print(f'  Trades: {candle.trades}')

Account Data Processing

from cryptofeed.types import Fill, Balance, OrderInfo

def fill_handler(fill):
    """Process trade fills."""
    fee_rate = (fill.fee / (fill.price * fill.amount)) * 100
    print(f'Fill: {fill.side} {fill.amount} {fill.symbol} @ {fill.price}')
    print(f'Fee: {fill.fee} ({fee_rate:.4f}%), Liquidity: {fill.liquidity}')

def balance_handler(balance):
    """Process balance updates."""
    available = balance.balance - balance.reserved
    print(f'{balance.currency}: {available:.6f} available, {balance.reserved:.6f} reserved')

def order_handler(order_info):
    """Process order status updates."""
    filled_pct = ((order_info.amount - order_info.remaining) / order_info.amount) * 100
    print(f'Order {order_info.id}: {order_info.status} ({filled_pct:.1f}% filled)')

Data Type Conversion

from cryptofeed.types import Trade
from decimal import Decimal

# Convert to different numeric types
trade = Trade.from_dict({...})

# Default (float)
dict_float = trade.to_dict()

# Using Decimal for precision
dict_decimal = trade.to_dict(numeric_type=Decimal)

# Convert None values to empty strings
dict_no_none = trade.to_dict(none_to='')

# Custom serialization function
def custom_serialize(obj):
    return trade.to_dict(numeric_type=str)  # Convert numbers to strings

Type Checking and Validation

from cryptofeed.types import Trade, Ticker, OrderBook

def data_handler(data):
    """Generic handler that processes different data types."""
    if isinstance(data, Trade):
        print(f'Processing trade: {data.symbol} {data.amount}@{data.price}')
    elif isinstance(data, Ticker):
        print(f'Processing ticker: {data.symbol} bid:{data.bid} ask:{data.ask}')
    elif isinstance(data, OrderBook):
        print(f'Processing book: {data.symbol} {"delta" if data.delta else "snapshot"}')
    else:
        print(f'Unknown data type: {type(data)}')

Install with Tessl CLI

npx tessl i tessl/pypi-cryptofeed

docs

backends.md

constants.md

exchanges.md

feed-management.md

index.md

types.md

tile.json