or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

backends.mdconstants.mdexchanges.mdfeed-management.mdindex.mdtypes.md

types.mddocs/

0

# Data Types

1

2

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.

3

4

## Capabilities

5

6

### Core Market Data Types

7

8

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

9

10

```python { .api }

11

class Trade:

12

"""Represents a completed trade/transaction."""

13

exchange: str

14

symbol: str

15

side: str # BUY or SELL

16

amount: float

17

price: float

18

timestamp: float

19

id: str

20

type: str

21

raw: dict

22

23

@staticmethod

24

def from_dict(data: dict): ...

25

def to_dict(self, numeric_type=None, none_to=False): ...

26

27

class Ticker:

28

"""Represents ticker/quote data with best bid/ask."""

29

exchange: str

30

symbol: str

31

bid: float

32

ask: float

33

timestamp: float

34

raw: dict

35

36

@staticmethod

37

def from_dict(data: dict): ...

38

def to_dict(self, numeric_type=None, none_to=False): ...

39

40

class OrderBook:

41

"""Represents order book data with bids and asks."""

42

exchange: str

43

symbol: str

44

book: dict # Contains bids and asks dictionaries

45

delta: bool # True if this is a delta update

46

sequence_number: int

47

checksum: int

48

timestamp: float

49

raw: dict

50

51

@staticmethod

52

def from_dict(data: dict): ...

53

def to_dict(self, delta=False, numeric_type=None, none_to=False): ...

54

55

class L1Book:

56

"""Represents Level 1 order book (best bid/ask only)."""

57

exchange: str

58

symbol: str

59

bid_price: float

60

bid_size: float

61

ask_price: float

62

ask_size: float

63

timestamp: float

64

raw: dict

65

66

def to_dict(self, numeric_type=None, none_to=False): ...

67

68

class Candle:

69

"""Represents OHLCV candlestick data."""

70

exchange: str

71

symbol: str

72

start: float # Start timestamp

73

stop: float # End timestamp

74

interval: str # Time interval (1m, 5m, 1h, etc.)

75

trades: int # Number of trades in period

76

open: float

77

close: float

78

high: float

79

low: float

80

volume: float

81

closed: bool # True if candle is closed/finalized

82

timestamp: float

83

raw: dict

84

85

@staticmethod

86

def from_dict(data: dict): ...

87

def to_dict(self, numeric_type=None, none_to=False): ...

88

```

89

90

### Derivatives and Advanced Data

91

92

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

93

94

```python { .api }

95

class Funding:

96

"""Represents funding rate data for perpetual contracts."""

97

exchange: str

98

symbol: str

99

mark_price: float

100

rate: float # Current funding rate

101

next_funding_time: float # Next funding timestamp

102

predicted_rate: float # Predicted next funding rate

103

timestamp: float

104

raw: dict

105

106

@staticmethod

107

def from_dict(data: dict): ...

108

def to_dict(self, numeric_type=None, none_to=False): ...

109

110

class OpenInterest:

111

"""Represents open interest data for derivatives."""

112

exchange: str

113

symbol: str

114

open_interest: float

115

timestamp: float

116

raw: dict

117

118

def to_dict(self, numeric_type=None, none_to=False): ...

119

120

class Liquidation:

121

"""Represents liquidation events."""

122

exchange: str

123

symbol: str

124

side: str # BUY or SELL

125

quantity: float

126

price: float

127

id: str

128

status: str

129

timestamp: float

130

raw: dict

131

132

@staticmethod

133

def from_dict(data: dict): ...

134

def to_dict(self, numeric_type=None, none_to=False): ...

135

136

class Index:

137

"""Represents index price data."""

138

exchange: str

139

symbol: str

140

price: float

141

timestamp: float

142

raw: dict

143

144

def to_dict(self, numeric_type=None, none_to=False): ...

145

```

146

147

### Account and Trading Data

148

149

Data types for authenticated account and trading information.

150

151

```python { .api }

152

class Order:

153

"""Represents order placement data."""

154

exchange: str

155

symbol: str

156

client_order_id: str

157

side: str # BUY or SELL

158

type: str # LIMIT, MARKET, etc.

159

price: float

160

amount: float

161

account: str

162

timestamp: float

163

164

@staticmethod

165

def from_dict(data: dict): ...

166

def to_dict(self, numeric_type=None, none_to=False): ...

167

168

class OrderInfo:

169

"""Represents order status information."""

170

exchange: str

171

symbol: str

172

id: str

173

client_order_id: str

174

side: str # BUY or SELL

175

status: str # OPEN, FILLED, CANCELLED, etc.

176

type: str # LIMIT, MARKET, etc.

177

price: float

178

amount: float

179

remaining: float # Remaining amount to fill

180

account: str

181

timestamp: float

182

raw: dict

183

184

@staticmethod

185

def from_dict(data: dict): ...

186

def to_dict(self, numeric_type=None, none_to=False): ...

187

def set_status(self, status: str): ...

188

189

class Fill:

190

"""Represents order fill/execution data."""

191

exchange: str

192

symbol: str

193

price: float

194

amount: float

195

side: str # BUY or SELL

196

fee: float

197

id: str

198

order_id: str

199

liquidity: str # MAKER or TAKER

200

type: str # Order type

201

account: str

202

timestamp: float

203

raw: dict

204

205

def to_dict(self, numeric_type=None, none_to=False): ...

206

207

class Balance:

208

"""Represents account balance data."""

209

exchange: str

210

currency: str

211

balance: float # Total balance

212

reserved: float # Reserved/locked balance

213

raw: dict

214

215

def to_dict(self, numeric_type=None, none_to=False): ...

216

217

class Position:

218

"""Represents trading position data."""

219

exchange: str

220

symbol: str

221

position: float # Position size (positive for long, negative for short)

222

entry_price: float

223

side: str # LONG, SHORT, or BOTH

224

unrealised_pnl: float

225

timestamp: float

226

raw: dict

227

228

def to_dict(self, numeric_type=None, none_to=False): ...

229

230

class Transaction:

231

"""Represents account transactions (deposits/withdrawals)."""

232

exchange: str

233

currency: str

234

type: str # DEPOSIT, WITHDRAWAL, etc.

235

status: str # PENDING, COMPLETED, etc.

236

amount: float

237

timestamp: float

238

raw: dict

239

240

def to_dict(self, numeric_type=None, none_to=False): ...

241

```

242

243

## Usage Examples

244

245

### Working with Trade Data

246

247

```python

248

from cryptofeed.types import Trade

249

250

# Create trade from dictionary (typically from exchange API)

251

trade_data = {

252

'exchange': 'coinbase',

253

'symbol': 'BTC-USD',

254

'side': 'buy',

255

'amount': 0.1,

256

'price': 50000.0,

257

'timestamp': 1640995200.0,

258

'id': 'trade-123'

259

}

260

261

trade = Trade.from_dict(trade_data)

262

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

263

264

# Convert to dictionary for storage

265

trade_dict = trade.to_dict()

266

print(trade_dict)

267

```

268

269

### Order Book Processing

270

271

```python

272

from cryptofeed.types import OrderBook

273

274

def book_handler(book):

275

"""Process order book updates."""

276

if book.delta:

277

print(f'Book delta for {book.symbol}')

278

else:

279

print(f'Full book snapshot for {book.symbol}')

280

281

# Access bids and asks

282

bids = book.book['bids'] # Price -> Size mapping

283

asks = book.book['asks'] # Price -> Size mapping

284

285

if bids and asks:

286

best_bid = max(bids.keys())

287

best_ask = min(asks.keys())

288

spread = best_ask - best_bid

289

print(f'Best bid: {best_bid}, Best ask: {best_ask}, Spread: {spread}')

290

```

291

292

### Candle Data Analysis

293

294

```python

295

from cryptofeed.types import Candle

296

297

def candle_handler(candle):

298

"""Process candlestick data."""

299

if candle.closed:

300

# Only process completed candles

301

price_change = candle.close - candle.open

302

price_change_pct = (price_change / candle.open) * 100

303

304

print(f'{candle.symbol} {candle.interval} candle:')

305

print(f' OHLCV: {candle.open}/{candle.high}/{candle.low}/{candle.close}/{candle.volume}')

306

print(f' Change: {price_change:.2f} ({price_change_pct:.2f}%)')

307

print(f' Trades: {candle.trades}')

308

```

309

310

### Account Data Processing

311

312

```python

313

from cryptofeed.types import Fill, Balance, OrderInfo

314

315

def fill_handler(fill):

316

"""Process trade fills."""

317

fee_rate = (fill.fee / (fill.price * fill.amount)) * 100

318

print(f'Fill: {fill.side} {fill.amount} {fill.symbol} @ {fill.price}')

319

print(f'Fee: {fill.fee} ({fee_rate:.4f}%), Liquidity: {fill.liquidity}')

320

321

def balance_handler(balance):

322

"""Process balance updates."""

323

available = balance.balance - balance.reserved

324

print(f'{balance.currency}: {available:.6f} available, {balance.reserved:.6f} reserved')

325

326

def order_handler(order_info):

327

"""Process order status updates."""

328

filled_pct = ((order_info.amount - order_info.remaining) / order_info.amount) * 100

329

print(f'Order {order_info.id}: {order_info.status} ({filled_pct:.1f}% filled)')

330

```

331

332

### Data Type Conversion

333

334

```python

335

from cryptofeed.types import Trade

336

from decimal import Decimal

337

338

# Convert to different numeric types

339

trade = Trade.from_dict({...})

340

341

# Default (float)

342

dict_float = trade.to_dict()

343

344

# Using Decimal for precision

345

dict_decimal = trade.to_dict(numeric_type=Decimal)

346

347

# Convert None values to empty strings

348

dict_no_none = trade.to_dict(none_to='')

349

350

# Custom serialization function

351

def custom_serialize(obj):

352

return trade.to_dict(numeric_type=str) # Convert numbers to strings

353

```

354

355

### Type Checking and Validation

356

357

```python

358

from cryptofeed.types import Trade, Ticker, OrderBook

359

360

def data_handler(data):

361

"""Generic handler that processes different data types."""

362

if isinstance(data, Trade):

363

print(f'Processing trade: {data.symbol} {data.amount}@{data.price}')

364

elif isinstance(data, Ticker):

365

print(f'Processing ticker: {data.symbol} bid:{data.bid} ask:{data.ask}')

366

elif isinstance(data, OrderBook):

367

print(f'Processing book: {data.symbol} {"delta" if data.delta else "snapshot"}')

368

else:

369

print(f'Unknown data type: {type(data)}')

370

```