or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authenticated-client.mdindex.mdorder-book.mdpublic-client.mdwebsocket-client.md

public-client.mddocs/

0

# Public Market Data

1

2

The PublicClient provides access to all public Coinbase Pro endpoints for market data, product information, and historical data without requiring authentication. This is the foundation for market analysis, price monitoring, and data gathering applications.

3

4

## Capabilities

5

6

### Client Initialization

7

8

Create a public client instance for accessing market data endpoints.

9

10

```python { .api }

11

class PublicClient:

12

def __init__(self, api_url: str = 'https://api.pro.coinbase.com', timeout: int = 30):

13

"""

14

Create cbpro API public client.

15

16

Parameters:

17

- api_url (str): API URL. Defaults to cbpro API.

18

- timeout (int): Request timeout in seconds.

19

"""

20

```

21

22

**Usage Example:**

23

```python

24

import cbpro

25

26

# Use production API (default)

27

client = cbpro.PublicClient()

28

29

# Use sandbox API for testing

30

client = cbpro.PublicClient(api_url='https://api-public.sandbox.pro.coinbase.com')

31

```

32

33

### Product Information

34

35

Get information about available trading pairs and supported currencies.

36

37

```python { .api }

38

def get_products(self) -> list:

39

"""

40

Get a list of available currency pairs for trading.

41

42

Returns:

43

list: Info about all currency pairs. Each item contains:

44

- id: Product identifier (e.g., "BTC-USD")

45

- display_name: Human-readable name (e.g., "BTC/USD")

46

- base_currency: Base currency code (e.g., "BTC")

47

- quote_currency: Quote currency code (e.g., "USD")

48

- base_min_size: Minimum order size for base currency

49

- base_max_size: Maximum order size for base currency

50

- quote_increment: Minimum price increment

51

"""

52

53

def get_currencies(self) -> list:

54

"""

55

List known currencies.

56

57

Returns:

58

list: List of currencies. Each item contains:

59

- id: Currency code (e.g., "BTC")

60

- name: Full currency name (e.g., "Bitcoin")

61

- min_size: Minimum transaction size

62

"""

63

```

64

65

**Usage Example:**

66

```python

67

# Get all trading pairs

68

products = client.get_products()

69

btc_products = [p for p in products if 'BTC' in p['id']]

70

71

# Get all supported currencies

72

currencies = client.get_currencies()

73

crypto_currencies = [c for c in currencies if c['id'] != 'USD']

74

```

75

76

### Order Book Data

77

78

Access current market depth and order book information at different levels of detail.

79

80

```python { .api }

81

def get_product_order_book(self, product_id: str, level: int = 1) -> dict:

82

"""

83

Get a list of open orders for a product.

84

85

The amount of detail shown can be customized with the level parameter:

86

- 1: Only the best bid and ask

87

- 2: Top 50 bids and asks (aggregated)

88

- 3: Full order book (non aggregated)

89

90

Level 1 and Level 2 are recommended for polling. Level 3 should only be

91

used with websocket streaming to avoid being rate limited.

92

93

Parameters:

94

- product_id (str): Product identifier (e.g., "BTC-USD")

95

- level (int): Order book level (1, 2, or 3). Default is 1.

96

97

Returns:

98

dict: Order book data containing:

99

- sequence: Message sequence number

100

- bids: List of [price, size, num-orders] for buy orders

101

- asks: List of [price, size, num-orders] for sell orders

102

"""

103

```

104

105

**Usage Example:**

106

```python

107

# Get best bid/ask only

108

level1 = client.get_product_order_book('BTC-USD', level=1)

109

best_bid = level1['bids'][0][0] # Best buy price

110

best_ask = level1['asks'][0][0] # Best sell price

111

spread = float(best_ask) - float(best_bid)

112

113

# Get top 50 levels for deeper analysis

114

level2 = client.get_product_order_book('BTC-USD', level=2)

115

total_bid_volume = sum(float(bid[1]) for bid in level2['bids'])

116

```

117

118

### Current Market Data

119

120

Get real-time ticker information and 24-hour statistics.

121

122

```python { .api }

123

def get_product_ticker(self, product_id: str) -> dict:

124

"""

125

Snapshot about the last trade (tick), best bid/ask and 24h volume.

126

127

Polling is discouraged in favor of connecting via websocket stream.

128

129

Parameters:

130

- product_id (str): Product identifier

131

132

Returns:

133

dict: Ticker info containing:

134

- trade_id: ID of the last trade

135

- price: Last trade price

136

- size: Last trade size

137

- bid: Best bid price

138

- ask: Best ask price

139

- volume: 24-hour volume in base currency

140

- time: Timestamp of last trade

141

"""

142

143

def get_product_24hr_stats(self, product_id: str) -> dict:

144

"""

145

Get 24 hr stats for the product.

146

147

Parameters:

148

- product_id (str): Product identifier

149

150

Returns:

151

dict: 24 hour stats. Volume is in base currency units.

152

- open: Opening price 24 hours ago

153

- high: Highest price in last 24 hours

154

- low: Lowest price in last 24 hours

155

- volume: Volume in base currency units

156

- last: Last trade price

157

- volume_30day: 30-day volume

158

"""

159

```

160

161

**Usage Example:**

162

```python

163

# Get current market snapshot

164

ticker = client.get_product_ticker('BTC-USD')

165

current_price = float(ticker['price'])

166

daily_volume = float(ticker['volume'])

167

168

# Get 24-hour statistics

169

stats = client.get_product_24hr_stats('BTC-USD')

170

price_change = float(stats['last']) - float(stats['open'])

171

price_change_pct = (price_change / float(stats['open'])) * 100

172

```

173

174

### Trade History

175

176

Access recent trades and market activity with pagination support.

177

178

```python { .api }

179

def get_product_trades(self, product_id: str, before: str = '', after: str = '',

180

limit: int = None, result: list = None):

181

"""

182

List the latest trades for a product.

183

184

This method returns a generator which may make multiple HTTP requests

185

while iterating through it.

186

187

Parameters:

188

- product_id (str): Product identifier

189

- before (str): Start time in ISO 8601 format

190

- after (str): End time in ISO 8601 format

191

- limit (int): Maximum number of trades to return (automatically paginated)

192

- result (list): Internal parameter for pagination

193

194

Yields:

195

dict: Trade information containing:

196

- time: Trade timestamp in ISO 8601

197

- trade_id: Unique trade identifier

198

- price: Trade execution price

199

- size: Trade size in base currency

200

- side: Trade side ("buy" or "sell")

201

"""

202

```

203

204

**Usage Example:**

205

```python

206

# Get recent trades (generator)

207

trades = client.get_product_trades('BTC-USD')

208

recent_trades = list(islice(trades, 100)) # Get first 100 trades

209

210

# Calculate volume-weighted average price

211

total_volume = sum(float(trade['size']) for trade in recent_trades)

212

vwap = sum(float(trade['price']) * float(trade['size']) for trade in recent_trades) / total_volume

213

```

214

215

### Historical Price Data

216

217

Access candlestick/OHLCV data for technical analysis and charting.

218

219

```python { .api }

220

def get_product_historic_rates(self, product_id: str, start: str = None, end: str = None,

221

granularity: int = None) -> list:

222

"""

223

Historic rates for a product.

224

225

Rates are returned in grouped buckets based on requested granularity.

226

Historical rate data may be incomplete. No data is published for

227

intervals where there are no ticks.

228

229

The maximum number of data points for a single request is 200 candles.

230

For larger time ranges, multiple requests with different start/end times are needed.

231

232

Parameters:

233

- product_id (str): Product identifier

234

- start (str): Start time in ISO 8601 format

235

- end (str): End time in ISO 8601 format

236

- granularity (int): Desired time slice in seconds

237

Valid values: 60, 300, 900, 3600, 21600, 86400

238

(1m, 5m, 15m, 1h, 6h, 1d)

239

240

Returns:

241

list: Historic candle data. Each candle is:

242

[timestamp, low, high, open, close, volume]

243

244

Raises:

245

ValueError: If granularity is not in approved values

246

"""

247

```

248

249

**Usage Example:**

250

```python

251

from datetime import datetime, timedelta

252

253

# Get daily candles for last 30 days

254

end_time = datetime.utcnow()

255

start_time = end_time - timedelta(days=30)

256

257

candles = client.get_product_historic_rates(

258

product_id='BTC-USD',

259

start=start_time.isoformat(),

260

end=end_time.isoformat(),

261

granularity=86400 # Daily candles

262

)

263

264

# Extract OHLCV data

265

for candle in candles:

266

timestamp, low, high, open_price, close, volume = candle

267

print(f"Date: {datetime.fromtimestamp(timestamp)}")

268

print(f"OHLC: {open_price} / {high} / {low} / {close}")

269

print(f"Volume: {volume}")

270

```

271

272

### System Information

273

274

Get server time and system status information.

275

276

```python { .api }

277

def get_time(self) -> dict:

278

"""

279

Get the API server time.

280

281

Returns:

282

dict: Server time in both ISO and epoch format:

283

- iso: Time in ISO 8601 format

284

- epoch: Decimal seconds since Unix epoch

285

"""

286

```

287

288

**Usage Example:**

289

```python

290

# Get server time for synchronization

291

server_time = client.get_time()

292

server_timestamp = server_time['epoch']

293

local_timestamp = time.time()

294

time_drift = abs(server_timestamp - local_timestamp)

295

296

if time_drift > 30: # More than 30 seconds drift

297

print(f"Warning: Clock drift of {time_drift:.2f} seconds detected")

298

```

299

300

## Rate Limiting and Best Practices

301

302

- **Rate Limits**: Public endpoints have rate limits. Use websockets for real-time data instead of polling

303

- **Caching**: Cache product and currency information as it changes infrequently

304

- **Error Handling**: Always handle network errors and API rate limit responses

305

- **Pagination**: Use generators for trade data to handle large datasets efficiently

306

- **Time Synchronization**: Check server time periodically to ensure request timestamps are accurate