or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdcryptocurrency.mdindex.mdmarket-data.mdstreaming.mdtrading-operations.md

cryptocurrency.mddocs/

0

# Cryptocurrency Data

1

2

Specialized market data operations for cryptocurrency trading pairs including trades, quotes, bars, and orderbook data. Supports multiple crypto exchanges with location-based data access.

3

4

## Capabilities

5

6

### Crypto Historical Data

7

8

Access historical cryptocurrency market data with exchange-specific data sources.

9

10

```python { .api }

11

def get_crypto_bars(

12

symbol: Union[str, List[str]],

13

timeframe: TimeFrame,

14

start: str,

15

end: str,

16

limit: int = None,

17

sort: Sort = None,

18

loc: str = "us"

19

) -> BarsV2:

20

"""Get historical crypto bars."""

21

22

def get_crypto_bars_iter(

23

symbol: Union[str, List[str]],

24

timeframe: TimeFrame,

25

start: str,

26

end: str,

27

limit: int = None,

28

sort: Sort = None,

29

loc: str = "us",

30

raw: bool = False

31

) -> Iterator[Union[BarV2, dict]]:

32

"""Get historical crypto bars as an iterator."""

33

34

def get_crypto_trades(

35

symbol: Union[str, List[str]],

36

start: str,

37

end: str,

38

limit: int = None,

39

sort: Sort = None,

40

loc: str = "us"

41

) -> TradesV2:

42

"""Get historical crypto trades."""

43

44

def get_crypto_trades_iter(

45

symbol: Union[str, List[str]],

46

start: str,

47

end: str,

48

limit: int = None,

49

sort: Sort = None,

50

loc: str = "us",

51

raw: bool = False

52

) -> Iterator[Union[TradeV2, dict]]:

53

"""Get historical crypto trades as an iterator."""

54

55

def get_crypto_quotes(

56

symbol: Union[str, List[str]],

57

start: str,

58

end: str,

59

limit: int = None,

60

sort: Sort = None,

61

loc: str = "us"

62

) -> QuotesV2:

63

"""Get historical crypto quotes."""

64

65

def get_crypto_quotes_iter(

66

symbol: Union[str, List[str]],

67

start: str,

68

end: str,

69

limit: int = None,

70

sort: Sort = None,

71

loc: str = "us",

72

raw: bool = False

73

) -> Iterator[Union[QuoteV2, dict]]:

74

"""Get historical crypto quotes as an iterator."""

75

```

76

77

**Usage Examples:**

78

79

```python

80

# Get Bitcoin daily bars

81

btc_bars = api.get_crypto_bars(

82

'BTC/USD',

83

TimeFrame.Day,

84

'2023-01-01',

85

'2023-01-31'

86

)

87

88

# Convert to DataFrame for analysis

89

df = btc_bars.df

90

print(f"BTC Price Range: ${df['low'].min():.2f} - ${df['high'].max():.2f}")

91

print(f"Average Daily Volume: {df['volume'].mean():.2f} BTC")

92

93

# Get Ethereum trades with location filter

94

eth_trades = api.get_crypto_trades(

95

'ETH/USD',

96

'2023-01-15T00:00:00',

97

'2023-01-15T23:59:59',

98

loc='us' # US exchanges only

99

)

100

101

# Analyze trade sizes

102

df = eth_trades.df

103

large_trades = df[df['size'] >= 10] # 10+ ETH trades

104

print(f"Large trades: {len(large_trades)} out of {len(df)} total trades")

105

```

106

107

### Latest Crypto Data

108

109

Get the most recent cryptocurrency market data across multiple exchanges.

110

111

```python { .api }

112

def get_latest_crypto_bars(symbols: List[str], loc: str = None) -> LatestBarsV2:

113

"""Get latest crypto bars for multiple symbols."""

114

115

def get_latest_crypto_trades(symbols: List[str], loc: str = None) -> LatestTradesV2:

116

"""Get latest crypto trades for multiple symbols."""

117

118

def get_latest_crypto_quotes(symbols: List[str], loc: str = None) -> LatestQuotesV2:

119

"""Get latest crypto quotes for multiple symbols."""

120

```

121

122

**Usage Examples:**

123

124

```python

125

# Get latest data for major crypto pairs

126

crypto_symbols = ['BTC/USD', 'ETH/USD', 'LTC/USD', 'BCH/USD']

127

latest_bars = api.get_latest_crypto_bars(crypto_symbols)

128

129

for symbol, bar in latest_bars.items():

130

print(f"{symbol}: ${bar.close:,.2f} (24h Vol: {bar.volume:,.2f})")

131

132

# Get latest quotes for spread analysis

133

latest_quotes = api.get_latest_crypto_quotes(['BTC/USD', 'ETH/USD'])

134

for symbol, quote in latest_quotes.items():

135

spread = quote.ask_price - quote.bid_price

136

spread_bps = (spread / quote.bid_price) * 10000

137

print(f"{symbol} Spread: ${spread:.2f} ({spread_bps:.1f} bps)")

138

```

139

140

### Crypto Market Snapshots

141

142

Comprehensive market snapshots for cryptocurrency pairs with latest trade, quote, and bar data.

143

144

```python { .api }

145

def get_crypto_snapshot(symbol: str, loc: str = "us") -> SnapshotV2:

146

"""Get crypto market snapshot for a symbol."""

147

148

def get_crypto_snapshots(symbols: List[str], loc: str = "us") -> SnapshotsV2:

149

"""Get crypto market snapshots for multiple symbols."""

150

```

151

152

**Usage Examples:**

153

154

```python

155

# Get comprehensive crypto market overview

156

crypto_pairs = ['BTC/USD', 'ETH/USD', 'ADA/USD', 'SOL/USD']

157

snapshots = api.get_crypto_snapshots(crypto_pairs)

158

159

for symbol, snapshot in snapshots.items():

160

current_price = snapshot.latest_trade.price

161

daily_open = snapshot.daily_bar.open

162

change_pct = ((current_price - daily_open) / daily_open) * 100

163

164

print(f"{symbol}:")

165

print(f" Price: ${current_price:,.2f} ({change_pct:+.2f}%)")

166

print(f" 24h High: ${snapshot.daily_bar.high:,.2f}")

167

print(f" 24h Low: ${snapshot.daily_bar.low:,.2f}")

168

print(f" 24h Volume: {snapshot.daily_bar.volume:,.2f}")

169

```

170

171

### Crypto Orderbook Data

172

173

Access level-2 orderbook data for cryptocurrency pairs showing bid/ask depth.

174

175

```python { .api }

176

def get_latest_crypto_orderbook(symbol: str, loc: str = "us") -> OrderbookV2:

177

"""Get latest crypto orderbook for a symbol."""

178

179

def get_latest_crypto_orderbooks(symbols: List[str], loc: str = "us") -> OrderbooksV2:

180

"""Get latest crypto orderbooks for multiple symbols."""

181

```

182

183

**Usage Examples:**

184

185

```python

186

# Get Bitcoin orderbook depth

187

btc_orderbook = api.get_latest_crypto_orderbook('BTC/USD')

188

189

print("BTC/USD Orderbook:")

190

print("Bids:")

191

for bid in btc_orderbook.bids[:5]: # Top 5 bid levels

192

print(f" ${bid.price:,.2f} x {bid.size:.4f} BTC")

193

194

print("Asks:")

195

for ask in btc_orderbook.asks[:5]: # Top 5 ask levels

196

print(f" ${ask.price:,.2f} x {ask.size:.4f} BTC")

197

198

# Calculate orderbook imbalance

199

total_bid_size = sum(bid.size for bid in btc_orderbook.bids[:10])

200

total_ask_size = sum(ask.size for ask in btc_orderbook.asks[:10])

201

imbalance = (total_bid_size - total_ask_size) / (total_bid_size + total_ask_size)

202

print(f"Orderbook imbalance: {imbalance:.3f} ({'buy pressure' if imbalance > 0 else 'sell pressure'})")

203

```

204

205

### Crypto Streaming

206

207

Real-time streaming for cryptocurrency market data including trades, quotes, bars, and orderbook updates.

208

209

```python { .api }

210

def subscribe_crypto_trades(handler: Callable, *symbols: str) -> None:

211

"""Subscribe to crypto trade streams."""

212

213

def subscribe_crypto_quotes(handler: Callable, *symbols: str) -> None:

214

"""Subscribe to crypto quote streams."""

215

216

def subscribe_crypto_bars(handler: Callable, *symbols: str) -> None:

217

"""Subscribe to crypto bar streams."""

218

219

def subscribe_crypto_updated_bars(handler: Callable, *symbols: str) -> None:

220

"""Subscribe to crypto updated bar streams."""

221

222

def subscribe_crypto_daily_bars(handler: Callable, *symbols: str) -> None:

223

"""Subscribe to crypto daily bar streams."""

224

225

def subscribe_crypto_orderbooks(handler: Callable, *symbols: str) -> None:

226

"""Subscribe to crypto orderbook streams."""

227

228

def on_crypto_trade(*symbols: str) -> Callable:

229

"""Decorator for crypto trade handlers."""

230

231

def on_crypto_quote(*symbols: str) -> Callable:

232

"""Decorator for crypto quote handlers."""

233

234

def on_crypto_bar(*symbols: str) -> Callable:

235

"""Decorator for crypto bar handlers."""

236

237

def on_crypto_updated_bar(*symbols: str) -> Callable:

238

"""Decorator for crypto updated bar handlers."""

239

240

def on_crypto_daily_bar(*symbols: str) -> Callable:

241

"""Decorator for crypto daily bar handlers."""

242

243

def on_crypto_orderbook(*symbols: str) -> Callable:

244

"""Decorator for crypto orderbook handlers."""

245

```

246

247

**Usage Examples:**

248

249

```python

250

# Subscribe to Bitcoin and Ethereum real-time data

251

@stream.on_crypto_trade('BTC/USD', 'ETH/USD')

252

def crypto_trade_handler(trade):

253

# Monitor large trades

254

if trade.symbol == 'BTC/USD' and trade.size >= 1.0:

255

print(f"Large BTC trade: {trade.size:.4f} BTC @ ${trade.price:,.2f}")

256

elif trade.symbol == 'ETH/USD' and trade.size >= 10.0:

257

print(f"Large ETH trade: {trade.size:.2f} ETH @ ${trade.price:,.2f}")

258

259

@stream.on_crypto_quote('BTC/USD')

260

def crypto_quote_handler(quote):

261

# Monitor tight spreads

262

spread_bps = ((quote.ask_price - quote.bid_price) / quote.bid_price) * 10000

263

if spread_bps < 5: # Very tight spread

264

print(f"Tight BTC spread: {spread_bps:.1f} bps")

265

266

@stream.on_crypto_orderbook('BTC/USD', 'ETH/USD')

267

def crypto_orderbook_handler(orderbook):

268

# Monitor orderbook depth

269

best_bid_size = orderbook.bids[0].size if orderbook.bids else 0

270

best_ask_size = orderbook.asks[0].size if orderbook.asks else 0

271

272

if best_bid_size > 5.0 or best_ask_size > 5.0: # Large size at best price

273

print(f"{orderbook.symbol} large size: Bid={best_bid_size:.2f}, Ask={best_ask_size:.2f}")

274

275

# Unsubscribe from crypto streams

276

stream.unsubscribe_crypto_trades('BTC/USD')

277

stream.unsubscribe_crypto_quotes('ETH/USD')

278

stream.unsubscribe_crypto_orderbooks('BTC/USD', 'ETH/USD')

279

```

280

281

### Crypto Exchange Support

282

283

The library supports multiple cryptocurrency exchanges through the `loc` parameter:

284

285

- **US exchanges**: Set `loc='us'` for US-based crypto exchanges

286

- **Global exchanges**: Leave `loc=None` or omit for global data aggregation

287

- **Exchange-specific**: Specify exchange codes for targeted data sources

288

289

**Usage Example:**

290

291

```python

292

# Compare prices across different locations

293

us_btc_bars = api.get_crypto_bars('BTC/USD', TimeFrame.Hour, '2023-01-15', '2023-01-16', loc='us')

294

global_btc_bars = api.get_crypto_bars('BTC/USD', TimeFrame.Hour, '2023-01-15', '2023-01-16')

295

296

us_avg_price = us_btc_bars.df['close'].mean()

297

global_avg_price = global_btc_bars.df['close'].mean()

298

price_diff = abs(us_avg_price - global_avg_price)

299

300

print(f"US Average: ${us_avg_price:,.2f}")

301

print(f"Global Average: ${global_avg_price:,.2f}")

302

print(f"Price Difference: ${price_diff:.2f}")

303

```

304

305

## Types

306

307

```python { .api }

308

class OrderbookV2:

309

@property

310

def symbol(self) -> str: ...

311

@property

312

def timestamp(self) -> pd.Timestamp: ...

313

@property

314

def exchange(self) -> str: ...

315

@property

316

def bids(self) -> List[BidOrAsk]: ...

317

@property

318

def asks(self) -> List[BidOrAsk]: ...

319

320

class BidOrAsk:

321

@property

322

def price(self) -> float: ...

323

@property

324

def size(self) -> float: ...

325

326

# Other types are the same as standard market data types:

327

# BarV2, TradeV2, QuoteV2, SnapshotV2, etc.

328

```