0
# Constants and Configuration
1
2
Standard constants for exchanges, channels, trading sides, and other enumerations, plus configuration management for feeds and authentication across all supported exchanges.
3
4
## Capabilities
5
6
### Market Data Channels
7
8
Constants for different types of market data feeds available across exchanges.
9
10
```python { .api }
11
# Order Book Channels
12
L1_BOOK: str # Top of book (best bid/ask)
13
L2_BOOK: str # Price aggregated order book
14
L3_BOOK: str # Full order book with individual orders
15
16
# Market Data Channels
17
TRADES: str # Trade/transaction data
18
TICKER: str # Ticker/quote data
19
FUNDING: str # Funding rate data (perpetual contracts)
20
OPEN_INTEREST: str # Open interest data (derivatives)
21
LIQUIDATIONS: str # Liquidation events
22
INDEX: str # Index price data
23
CANDLES: str # Candlestick/OHLCV data
24
UNSUPPORTED: str # Placeholder for unsupported channels
25
```
26
27
### Account Data Channels
28
29
Constants for authenticated account and trading data channels.
30
31
```python { .api }
32
# Account Information
33
ORDER_INFO: str # Order status updates
34
FILLS: str # User trade fills/executions
35
TRANSACTIONS: str # Account deposits/withdrawals
36
BALANCES: str # Account balance updates
37
POSITIONS: str # Position updates (derivatives)
38
39
# Trading Operations
40
PLACE_ORDER: str # Order placement
41
CANCEL_ORDER: str # Order cancellation
42
ORDERS: str # Order list/history
43
ORDER_STATUS: str # Order status queries
44
TRADE_HISTORY: str # User trade history
45
```
46
47
### Exchange Constants
48
49
String constants for all supported cryptocurrency exchanges.
50
51
```python { .api }
52
# Major Spot Exchanges
53
COINBASE: str
54
BINANCE: str
55
KRAKEN: str
56
BITFINEX: str
57
BITSTAMP: str
58
GEMINI: str
59
KUCOIN: str
60
HITBTC: str
61
POLONIEX: str
62
63
# Futures and Derivatives
64
BINANCE_FUTURES: str
65
BINANCE_DELIVERY: str
66
KRAKEN_FUTURES: str
67
DERIBIT: str
68
BITMEX: str
69
BYBIT: str
70
OKX: str
71
PHEMEX: str
72
DELTA: str
73
74
# Regional Exchanges
75
BINANCE_US: str
76
BINANCE_TR: str
77
BITHUMB: str
78
UPBIT: str
79
INDEPENDENT_RESERVE: str
80
81
# Additional Exchanges
82
ASCENDEX: str
83
ASCENDEX_FUTURES: str
84
BEQUANT: str
85
BITDOTCOM: str
86
BITFLYER: str
87
BITGET: str
88
BLOCKCHAIN: str
89
CRYPTODOTCOM: str
90
DYDX: str
91
EXX: str
92
FMFW: str
93
GATEIO: str
94
GATEIO_FUTURES: str
95
HUOBI: str
96
HUOBI_DM: str
97
HUOBI_SWAP: str
98
OKCOIN: str
99
PROBIT: str
100
```
101
102
### Trading Constants
103
104
Constants for trading sides, order types, and other trading-related enumerations.
105
106
```python { .api }
107
# Trading Sides
108
BUY: str # Buy side
109
SELL: str # Sell side
110
BID: str # Bid side (order book)
111
ASK: str # Ask side (order book)
112
UND: str # Undefined side
113
114
# Liquidity Types
115
MAKER: str # Maker liquidity
116
TAKER: str # Taker liquidity
117
118
# Position Types
119
LONG: str # Long position
120
SHORT: str # Short position
121
BOTH: str # Both long and short (hedge mode)
122
123
# Order Types
124
LIMIT: str # Limit order
125
MARKET: str # Market order
126
STOP_LIMIT: str # Stop limit order
127
STOP_MARKET: str # Stop market order
128
MAKER_OR_CANCEL: str # Maker-or-cancel order
129
FILL_OR_KILL: str # Fill-or-kill order
130
IMMEDIATE_OR_CANCEL: str # Immediate-or-cancel order
131
GOOD_TIL_CANCELED: str # Good-till-canceled order
132
TRIGGER_LIMIT: str # Trigger limit order
133
TRIGGER_MARKET: str # Trigger market order
134
MARGIN_LIMIT: str # Margin limit order
135
MARGIN_MARKET: str # Margin market order
136
```
137
138
### Order Status Constants
139
140
Constants for order status states across all exchanges.
141
142
```python { .api }
143
# Order Status
144
OPEN: str # Order is open/active
145
PENDING: str # Order is pending
146
FILLED: str # Order is completely filled
147
PARTIAL: str # Order is partially filled
148
CANCELLED: str # Order is cancelled
149
UNFILLED: str # Order is unfilled
150
EXPIRED: str # Order has expired
151
SUSPENDED: str # Order is suspended
152
FAILED: str # Order failed
153
SUBMITTING: str # Order is being submitted
154
CANCELLING: str # Order is being cancelled
155
CLOSED: str # Order is closed
156
```
157
158
### Instrument Types
159
160
Constants for different types of financial instruments.
161
162
```python { .api }
163
# Instrument Types
164
CURRENCY: str # Currency/spot pairs
165
FUTURES: str # Futures contracts
166
PERPETUAL: str # Perpetual contracts
167
OPTION: str # Options contracts
168
OPTION_COMBO: str # Option combinations
169
FUTURE_COMBO: str # Future combinations
170
SPOT: str # Spot trading
171
CALL: str # Call options
172
PUT: str # Put options
173
FX: str # Foreign exchange
174
```
175
176
### Configuration Management
177
178
Classes for managing feed configuration and settings.
179
180
```python { .api }
181
class Config:
182
"""Configuration management for feeds and exchanges."""
183
def __init__(self, config=None):
184
"""
185
Initialize configuration with file, dict, or defaults.
186
187
Args:
188
config (str, dict, optional):
189
- str: Path to YAML config file
190
- dict: Configuration dictionary
191
- None: Use default configuration
192
"""
193
194
@property
195
def log_msg(self) -> str:
196
"""Configuration loading log message."""
197
198
class AttrDict(dict):
199
"""Dictionary with attribute-style access for nested configurations."""
200
def __init__(self, d=None):
201
"""
202
Initialize with optional dictionary.
203
204
Args:
205
d (dict, optional): Initial dictionary data
206
"""
207
208
def __getattr__(self, key):
209
"""Get attribute using dot notation."""
210
211
def __setattr__(self, key, value):
212
"""Set attribute using dot notation."""
213
214
def __missing__(self, key):
215
"""Return empty AttrDict for missing keys."""
216
```
217
218
### Symbol Management
219
220
Classes and functions for managing symbol normalization across exchanges.
221
222
```python { .api }
223
class Symbol:
224
"""Represents trading symbols with normalization."""
225
def __init__(self, base, quote, type=SPOT, strike_price=None, option_type=None, expiry_date=None, expiry_normalize=True):
226
"""
227
Initialize symbol.
228
229
Args:
230
base (str): Base currency/asset
231
quote (str): Quote currency/asset
232
type (str): Instrument type (SPOT, FUTURES, etc.)
233
strike_price (float, optional): Strike price for options
234
option_type (str, optional): CALL or PUT for options
235
expiry_date (str, optional): Expiry date for derivatives
236
expiry_normalize (bool): Whether to normalize expiry format
237
"""
238
239
@property
240
def normalized(self) -> str:
241
"""Get normalized symbol string."""
242
243
@staticmethod
244
def month_code(month: int) -> str:
245
"""Get futures month code for month number."""
246
247
@staticmethod
248
def date_format(date: str) -> str:
249
"""Format date string for symbols."""
250
251
class Symbols:
252
"""Global symbol registry for exchange symbol mappings."""
253
def clear(self): ...
254
def load_all(self): ...
255
def set(self, exchange, normalized, exchange_info): ...
256
def get(self, exchange): ...
257
def populated(self, exchange): ...
258
def find(self, symbol): ...
259
260
def str_to_symbol(symbol: str) -> Symbol:
261
"""Convert string to Symbol object."""
262
```
263
264
## Usage Examples
265
266
### Using Channel Constants
267
268
```python
269
from cryptofeed import FeedHandler
270
from cryptofeed.exchanges import Coinbase
271
from cryptofeed.defines import TRADES, TICKER, L2_BOOK, FUNDING
272
273
def trade_handler(trade):
274
print(f'Trade: {trade}')
275
276
def ticker_handler(ticker):
277
print(f'Ticker: {ticker}')
278
279
fh = FeedHandler()
280
fh.add_feed(Coinbase(
281
symbols=['BTC-USD'],
282
channels=[TRADES, TICKER, L2_BOOK], # Use constants instead of strings
283
callbacks={
284
TRADES: trade_handler,
285
TICKER: ticker_handler
286
}
287
))
288
fh.run()
289
```
290
291
### Exchange Constants
292
293
```python
294
from cryptofeed.defines import COINBASE, BINANCE, KRAKEN
295
from cryptofeed.exchanges import EXCHANGE_MAP
296
297
# Get exchange class from constant
298
exchange_class = EXCHANGE_MAP[COINBASE]
299
exchange = exchange_class()
300
301
# Check supported exchanges
302
supported_exchanges = list(EXCHANGE_MAP.keys())
303
print(f'Supported exchanges: {supported_exchanges}')
304
```
305
306
### Configuration Files
307
308
```python
309
from cryptofeed import FeedHandler
310
from cryptofeed.config import Config
311
312
# YAML configuration file example (config.yaml):
313
"""
314
log:
315
filename: feed.log
316
level: INFO
317
318
feeds:
319
coinbase:
320
exchange: coinbase
321
symbols: [BTC-USD, ETH-USD]
322
channels: [trades, ticker]
323
324
binance:
325
exchange: binance
326
symbols: [BTCUSDT, ETHUSDT]
327
channels: [trades, book]
328
"""
329
330
# Load configuration
331
config = Config('config.yaml')
332
fh = FeedHandler(config=config)
333
fh.run()
334
```
335
336
### Trading Constants
337
338
```python
339
from cryptofeed.defines import BUY, SELL, LIMIT, MARKET, MAKER, TAKER
340
341
def order_handler(order):
342
"""Process order updates using constants."""
343
if order.side == BUY:
344
print(f'Buy order: {order.amount} @ {order.price}')
345
elif order.side == SELL:
346
print(f'Sell order: {order.amount} @ {order.price}')
347
348
if order.type == LIMIT:
349
print('Limit order')
350
elif order.type == MARKET:
351
print('Market order')
352
353
def fill_handler(fill):
354
"""Process fills using liquidity constants."""
355
if fill.liquidity == MAKER:
356
print('Maker fill (provided liquidity)')
357
elif fill.liquidity == TAKER:
358
print('Taker fill (took liquidity)')
359
```
360
361
### Symbol Management
362
363
```python
364
from cryptofeed.symbols import Symbol, str_to_symbol
365
from cryptofeed.defines import SPOT, FUTURES, CALL
366
367
# Create spot symbol
368
btc_usd = Symbol('BTC', 'USD', SPOT)
369
print(btc_usd.normalized) # BTC-USD
370
371
# Create futures symbol
372
btc_fut = Symbol('BTC', 'USD', FUTURES, expiry_date='2024-03-29')
373
print(btc_fut.normalized) # BTC-USD-29MAR24
374
375
# Create option symbol
376
btc_call = Symbol('BTC', 'USD', CALL, strike_price=50000, expiry_date='2024-03-29')
377
print(btc_call.normalized) # BTC-USD-29MAR24-50000-C
378
379
# Parse symbol string
380
symbol = str_to_symbol('BTC-USD')
381
print(f'Base: {symbol.base}, Quote: {symbol.quote}')
382
```
383
384
### Environment Variables
385
386
```python
387
import os
388
from cryptofeed import FeedHandler
389
from cryptofeed.exchanges import Coinbase
390
391
# Use environment variables for API credentials
392
config = {
393
'coinbase': {
394
'key_id': os.getenv('COINBASE_API_KEY'),
395
'secret': os.getenv('COINBASE_SECRET'),
396
'passphrase': os.getenv('COINBASE_PASSPHRASE')
397
}
398
}
399
400
fh = FeedHandler()
401
fh.add_feed(Coinbase(
402
symbols=['BTC-USD'],
403
channels=[TRADES],
404
config=config
405
))
406
fh.run()
407
```
408
409
### Exchange Information
410
411
```python
412
from cryptofeed.exchanges import Coinbase, Binance
413
from cryptofeed.defines import *
414
415
# Check what channels each exchange supports
416
coinbase = Coinbase()
417
info = coinbase.info()
418
419
print(f"Coinbase channels: {info.get('channels', [])}")
420
print(f"Requires authentication: {info.get('authenticated_channels', [])}")
421
422
# Check symbol support
423
symbols = coinbase.symbols()
424
print(f"Coinbase supports {len(symbols)} symbols")
425
426
# Get channel mapping
427
channel_map = coinbase.std_channel_to_exchange(TRADES)
428
print(f"TRADES maps to: {channel_map}")
429
```
430
431
### Exception Classes
432
433
Built-in exception classes for error handling and validation across the library.
434
435
```python { .api }
436
class MissingSequenceNumber(Exception):
437
"""Missing sequence number in data."""
438
439
class MissingMessage(Exception):
440
"""Missing expected message."""
441
442
class UnsupportedSymbol(Exception):
443
"""Symbol not supported by exchange."""
444
445
class UnsupportedDataFeed(Exception):
446
"""Data feed not supported."""
447
448
class UnsupportedTradingOption(Exception):
449
"""Trading option not supported."""
450
451
class UnsupportedType(Exception):
452
"""Type not supported."""
453
454
class ExhaustedRetries(Exception):
455
"""Retries exhausted."""
456
457
class BidAskOverlapping(Exception):
458
"""Bid/ask price overlap detected."""
459
460
class BadChecksum(Exception):
461
"""Checksum validation failed."""
462
463
class RestResponseError(Exception):
464
"""REST API response error."""
465
466
class ConnectionClosed(Exception):
467
"""Connection closed unexpectedly."""
468
469
class UnexpectedMessage(Exception):
470
"""Unexpected message received."""
471
```
472
473
### Order Status Handling
474
475
```python
476
from cryptofeed.defines import OPEN, FILLED, CANCELLED, PARTIAL
477
478
def order_status_handler(order_info):
479
"""Handle different order statuses."""
480
if order_info.status == OPEN:
481
print(f'Order {order_info.id} is open')
482
elif order_info.status == FILLED:
483
print(f'Order {order_info.id} is completely filled')
484
elif order_info.status == PARTIAL:
485
filled_amount = order_info.amount - order_info.remaining
486
print(f'Order {order_info.id} is partially filled: {filled_amount}/{order_info.amount}')
487
elif order_info.status == CANCELLED:
488
print(f'Order {order_info.id} was cancelled')
489
```