or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

coins.mdexchanges.mdglobal.mdindex.mdnfts.mdprice-market.mdsearch.mdsystem-utils.md

system-utils.mddocs/

0

# System & Utilities

1

2

API status monitoring, account information, and utility functions for data processing. This module provides system-level functionality for API health checks, account management, and data preprocessing utilities.

3

4

## Capabilities

5

6

### API Status Monitoring

7

8

Check the health and availability of the CoinGecko API servers.

9

10

```python { .api }

11

def ping(**kwargs):

12

"""

13

Check API server status and connectivity.

14

15

Returns:

16

dict: Server status response with greeting message

17

"""

18

```

19

20

**Usage Example:**

21

22

```python

23

# Check if API is responding

24

try:

25

status = cg.ping()

26

print(status) # {'gecko_says': '(V3) To the Moon!'}

27

print("API is healthy and responding")

28

except Exception as e:

29

print(f"API is down or unreachable: {e}")

30

```

31

32

**Response Format:**

33

34

```python

35

{

36

"gecko_says": "(V3) To the Moon!"

37

}

38

```

39

40

### Account Management (Pro API)

41

42

Monitor API usage, rate limits, and account information for Pro API users.

43

44

```python { .api }

45

def key(**kwargs):

46

"""

47

Monitor your account's API usage including rate limits, monthly credits, and remaining credits.

48

49

Note: This endpoint is only available for Pro API users with valid API keys.

50

51

Returns:

52

dict: Account usage statistics, rate limits, and billing information

53

"""

54

```

55

56

**Usage Example:**

57

58

```python

59

# Initialize with Pro API key

60

cg_pro = CoinGeckoAPI(api_key='YOUR_PRO_API_KEY')

61

62

# Check account usage

63

try:

64

account_info = cg_pro.key()

65

print(f"Monthly credits used: {account_info['monthly_call_credit']}")

66

print(f"Remaining credits: {account_info['remaining_monthly_call_credit']}")

67

print(f"Rate limit: {account_info['current_total_monthly_calls']}")

68

except ValueError as e:

69

print(f"Pro API key required or invalid: {e}")

70

```

71

72

**Account Info Response Format:**

73

74

```python

75

{

76

"monthly_call_credit": 10000,

77

"current_total_monthly_calls": 2847,

78

"remaining_monthly_call_credit": 7153,

79

"rate_limit_request_per_minute": 500,

80

"rate_limit_request_per_second": 50,

81

"plan": "Analyst",

82

"is_active": True

83

}

84

```

85

86

## Utility Functions

87

88

Data preprocessing utilities that handle parameter conversion for API calls.

89

90

### Function Argument Preprocessing

91

92

Decorator that automatically preprocesses function arguments for API compatibility.

93

94

```python { .api }

95

def func_args_preprocessing(func):

96

"""

97

Decorator that converts list input arguments to comma-separated strings and handles boolean conversion.

98

99

Parameters:

100

- func: Function to wrap with preprocessing

101

102

Returns:

103

function: Wrapped function with automatic argument preprocessing

104

"""

105

```

106

107

**Usage Example:**

108

109

```python

110

from pycoingecko.utils import func_args_preprocessing

111

112

@func_args_preprocessing

113

def custom_api_call(ids, vs_currencies, include_market_cap=False):

114

# Lists and booleans are automatically preprocessed

115

# ids=['bitcoin', 'ethereum'] becomes 'bitcoin,ethereum'

116

# include_market_cap=True becomes 'true'

117

pass

118

```

119

120

### Individual Argument Preprocessing

121

122

Process individual arguments for API compatibility.

123

124

```python { .api }

125

def arg_preprocessing(arg_v):

126

"""

127

Return the values of an argument after preprocessing for API compatibility.

128

129

Parameters:

130

- arg_v: Argument value to preprocess (list, bool, or other type)

131

132

Returns:

133

str or original type: Preprocessed argument value

134

"""

135

```

136

137

**Usage Examples:**

138

139

```python

140

from pycoingecko.utils import arg_preprocessing

141

142

# Convert list to comma-separated string

143

coin_list = ['bitcoin', 'ethereum', 'litecoin']

144

processed = arg_preprocessing(coin_list)

145

print(processed) # 'bitcoin,ethereum,litecoin'

146

147

# Convert boolean to lowercase string

148

include_cap = True

149

processed = arg_preprocessing(include_cap)

150

print(processed) # 'true'

151

152

# Other types pass through unchanged

153

number = 42

154

processed = arg_preprocessing(number)

155

print(processed) # 42

156

```

157

158

### Comma-Separated Value Creation

159

160

Convert values to comma-separated strings for API parameters.

161

162

```python { .api }

163

def get_comma_separated_values(values):

164

"""

165

Return the values as a comma-separated string.

166

167

Parameters:

168

- values: Single value, list, or tuple to convert

169

170

Returns:

171

str: Comma-separated string representation

172

"""

173

```

174

175

**Usage Examples:**

176

177

```python

178

from pycoingecko.utils import get_comma_separated_values

179

180

# Convert list to comma-separated string

181

coins = ['bitcoin', 'ethereum', 'cardano']

182

csv_string = get_comma_separated_values(coins)

183

print(csv_string) # 'bitcoin,ethereum,cardano'

184

185

# Convert tuple

186

currencies = ('usd', 'eur', 'gbp')

187

csv_string = get_comma_separated_values(currencies)

188

print(csv_string) # 'usd,eur,gbp'

189

190

# Single value becomes single-item string

191

single = 'bitcoin'

192

csv_string = get_comma_separated_values(single)

193

print(csv_string) # 'bitcoin'

194

```

195

196

## Error Handling and Diagnostics

197

198

### API Error Responses

199

200

The API returns structured error information that can help with debugging:

201

202

```python

203

try:

204

# Invalid API call

205

result = cg.get_price(ids='invalid_coin', vs_currencies='usd')

206

except ValueError as e:

207

print(f"API Error: {e}")

208

# May contain JSON error details from CoinGecko

209

except requests.exceptions.HTTPError as e:

210

print(f"HTTP Error: {e}")

211

# HTTP status codes like 404, 429 (rate limit), 500

212

except requests.exceptions.RequestException as e:

213

print(f"Network Error: {e}")

214

# Connection timeouts, DNS resolution, etc.

215

```

216

217

### Rate Limit Handling

218

219

CoinGecko enforces rate limits that vary by API tier:

220

221

- **Public API**: 10-50 calls/minute (varies by endpoint)

222

- **Demo API**: Enhanced rate limits with demo key

223

- **Pro API**: 500+ calls/minute with professional key

224

225

```python

226

import time

227

228

def safe_api_call(func, *args, **kwargs):

229

"""Example of rate limit aware API calling."""

230

max_retries = 3

231

for attempt in range(max_retries):

232

try:

233

return func(*args, **kwargs)

234

except requests.exceptions.HTTPError as e:

235

if e.response.status_code == 429: # Rate limit exceeded

236

wait_time = 2 ** attempt # Exponential backoff

237

print(f"Rate limited, waiting {wait_time} seconds...")

238

time.sleep(wait_time)

239

else:

240

raise

241

except Exception as e:

242

if attempt == max_retries - 1:

243

raise

244

time.sleep(1)

245

246

raise Exception("Max retries exceeded")

247

248

# Usage

249

result = safe_api_call(cg.get_price, ids='bitcoin', vs_currencies='usd')

250

```

251

252

### Connection Configuration

253

254

The CoinGeckoAPI class provides configuration options for robust API interaction:

255

256

```python

257

# Initialize with custom retry configuration

258

cg = CoinGeckoAPI(retries=10) # Increase retry attempts

259

260

# The client automatically handles:

261

# - Connection pooling and keep-alive

262

# - Automatic retries on 502, 503, 504 errors

263

# - 120-second request timeout

264

# - Exponential backoff between retries

265

```

266

267

### API Endpoint Selection

268

269

The client automatically selects the appropriate endpoint based on provided keys:

270

271

```python

272

# Public API (free tier)

273

cg_free = CoinGeckoAPI()

274

# Uses: https://api.coingecko.com/api/v3/

275

276

# Demo API (enhanced free tier)

277

cg_demo = CoinGeckoAPI(demo_api_key='demo_key')

278

# Uses: https://api.coingecko.com/api/v3/ with demo key header

279

280

# Pro API (paid tier)

281

cg_pro = CoinGeckoAPI(api_key='pro_key')

282

# Uses: https://pro-api.coingecko.com/api/v3/

283

```

284

285

## Health Check Best Practices

286

287

### API Availability Monitoring

288

289

```python

290

def check_api_health():

291

"""Check if CoinGecko API is available and responding."""

292

try:

293

cg = CoinGeckoAPI()

294

response = cg.ping()

295

296

if 'gecko_says' in response:

297

return {

298

'status': 'healthy',

299

'message': response['gecko_says'],

300

'timestamp': time.time()

301

}

302

else:

303

return {

304

'status': 'unhealthy',

305

'message': 'Unexpected response format',

306

'timestamp': time.time()

307

}

308

309

except Exception as e:

310

return {

311

'status': 'error',

312

'message': str(e),

313

'timestamp': time.time()

314

}

315

316

# Periodic health checks

317

health_status = check_api_health()

318

print(f"API Status: {health_status['status']}")

319

```

320

321

### Performance Monitoring

322

323

```python

324

import time

325

326

def timed_api_call(func, *args, **kwargs):

327

"""Measure API call performance."""

328

start_time = time.time()

329

try:

330

result = func(*args, **kwargs)

331

end_time = time.time()

332

return {

333

'success': True,

334

'result': result,

335

'duration': end_time - start_time,

336

'timestamp': start_time

337

}

338

except Exception as e:

339

end_time = time.time()

340

return {

341

'success': False,

342

'error': str(e),

343

'duration': end_time - start_time,

344

'timestamp': start_time

345

}

346

347

# Monitor API performance

348

perf = timed_api_call(cg.get_price, ids='bitcoin', vs_currencies='usd')

349

print(f"API call took {perf['duration']:.2f} seconds")

350

```

351

352

This system and utilities module provides the foundation for robust, production-ready applications using pycoingecko.