1
+ """
2
+ Detailed testing script for CoinGecko API that aggregates data from multiple endpoints.
3
+ Provides comprehensive token information including market data and historical volumes.
4
+
5
+ Usage:
6
+ python test_coingecko_detailed.py --num-tokens 10
7
+ python test_coingecko_detailed.py -n 5
8
+ """
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import List , Dict
15
+ import logging
16
+
17
+ # Configure logging
18
+ logging .basicConfig (
19
+ level = logging .INFO ,
20
+ format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
21
+ )
22
+ logger = logging .getLogger (__name__ )
23
+
24
+ # Add the parent directory to the Python path so we can import the utils
25
+ sys .path .append (str (Path (__file__ ).parent .parent .parent ))
26
+
27
+ from backend .utils .coingecko_api import (
28
+ fetch_all_coingecko_market_data ,
29
+ fetch_coingecko_historical_volume ,
30
+ fetch_all_coingecko_volumes
31
+ )
32
+
33
+ def parse_arguments ():
34
+ parser = argparse .ArgumentParser (description = 'Test CoinGecko API with detailed output' )
35
+ parser .add_argument ('-n' , '--num-tokens' , type = int , default = 10 ,
36
+ help = 'Number of top tokens to fetch (default: 10, max: 250)' )
37
+ return parser .parse_args ()
38
+
39
+ def format_token_data (market_data : Dict , volume_30d : float ) -> Dict :
40
+ """Format token data according to the specified structure."""
41
+ return {
42
+ "symbol" : market_data .get ('symbol' , '' ),
43
+ "coingecko_data" : {
44
+ "coingecko_name" : market_data .get ('name' ),
45
+ "coingecko_id" : market_data .get ('id' ),
46
+ "coingecko_image_url" : market_data .get ('image_url' ),
47
+ "coingecko_current_price" : market_data .get ('current_price' ),
48
+ "coingecko_market_cap_rank" : market_data .get ('market_cap_rank' ),
49
+ "coingecko_market_cap" : market_data .get ('market_cap' ),
50
+ "coingecko_fully_diluted_valuation" : market_data .get ('fully_diluted_valuation' ),
51
+ "coingecko_total_volume_24h" : market_data .get ('total_volume_24h' ),
52
+ "coingecko_mc_derived" : market_data .get ('market_cap' ), # Same as market_cap for now
53
+ "coingecko_circulating" : market_data .get ('circulating_supply' ),
54
+ "coingecko_total_supply" : market_data .get ('total_supply' ),
55
+ "coingecko_max_supply" : market_data .get ('max_supply' ),
56
+ "coingecko_ath_price" : market_data .get ('ath_price' ),
57
+ "coingecko_ath_change_percentage" : market_data .get ('ath_change_percentage' ),
58
+ "coingecko_volume_30d" : volume_30d
59
+ }
60
+ }
61
+
62
+ def run_detailed_test (num_tokens : int = 10 ) -> None :
63
+ """
64
+ Run a detailed test of CoinGecko API functionality.
65
+
66
+ Args:
67
+ num_tokens: Number of tokens to fetch data for (default: 10)
68
+ """
69
+ logger .info (f"Starting detailed test for { num_tokens } tokens" )
70
+
71
+ # Fetch market data for all tokens
72
+ market_data = fetch_all_coingecko_market_data ()
73
+ if not market_data or isinstance (market_data , dict ) and "error" in market_data :
74
+ logger .error ("Failed to fetch market data" )
75
+ return
76
+
77
+ # Convert dictionary to list and sort by market cap
78
+ tokens_list = []
79
+ for coin_id , token_data in market_data .items ():
80
+ token_data ['id' ] = coin_id # Add coin_id to the token data
81
+ tokens_list .append (token_data )
82
+
83
+ # Sort tokens by market cap and take top N
84
+ sorted_tokens = sorted (
85
+ tokens_list ,
86
+ key = lambda x : float (x .get ("market_cap" , 0 ) or 0 ), # Handle None values
87
+ reverse = True
88
+ )[:num_tokens ]
89
+
90
+ # Get list of coin IDs for volume fetch
91
+ coin_ids = [token .get ("id" ) for token in sorted_tokens ]
92
+ logger .info (f"Fetching 30d volume data for top { len (coin_ids )} tokens" )
93
+
94
+ # Fetch 30d volume data for all tokens at once
95
+ volume_data = fetch_all_coingecko_volumes (coin_ids )
96
+
97
+ results = []
98
+ total_tokens = len (sorted_tokens )
99
+
100
+ for idx , token in enumerate (sorted_tokens , 1 ):
101
+ coin_id = token .get ("id" )
102
+ symbol = token .get ("symbol" , "" ).upper ()
103
+
104
+ # Get the 30d volume from the volume data
105
+ total_volume = volume_data .get (coin_id , 0 )
106
+
107
+ results .append ({
108
+ "symbol" : symbol ,
109
+ "name" : token .get ("name" ),
110
+ "market_cap" : token .get ("market_cap" , 0 ),
111
+ "total_volume_30d" : total_volume
112
+ })
113
+
114
+ # Log progress
115
+ progress = (idx / total_tokens ) * 100
116
+ logger .info (f"Progress: { progress :.1f} % ({ idx } /{ total_tokens } )" )
117
+
118
+ # Format and display results
119
+ if results :
120
+ print ("\n Results:" )
121
+ print (f"{ 'Symbol' :<10} { 'Name' :<20} { 'Market Cap' :>15} { '30d Volume' :>20} " )
122
+ print ("-" * 65 )
123
+
124
+ for r in results :
125
+ print (
126
+ f"{ r ['symbol' ]:<10} "
127
+ f"{ r ['name' ][:20 ]:<20} "
128
+ f"${ r ['market_cap' ]:>14,.0f} "
129
+ f"${ r ['total_volume_30d' ]:>19,.0f} "
130
+ )
131
+ else :
132
+ logger .warning ("No results to display" )
133
+
134
+ if __name__ == "__main__" :
135
+ args = parse_arguments ()
136
+ print (f"Starting detailed CoinGecko API tests for { args .num_tokens } tokens..." )
137
+
138
+ run_detailed_test (args .num_tokens )
139
+
140
+ print ("\n Tests completed!" )
0 commit comments