File size: 11,335 Bytes
b190b45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/env python3
"""

CoinGecko API Client - REAL DATA ONLY

Fetches real cryptocurrency market data from CoinGecko

NO MOCK DATA - All data from live CoinGecko API

"""

import httpx
import logging
from typing import Dict, Any, List, Optional
from datetime import datetime
from fastapi import HTTPException

logger = logging.getLogger(__name__)


class CoinGeckoClient:
    """

    Real CoinGecko API Client

    Primary source for real-time cryptocurrency market prices

    """
    
    def __init__(self):
        self.base_url = "https://api.coingecko.com/api/v3"
        self.timeout = 15.0
        
        # Symbol to CoinGecko ID mapping
        self.symbol_to_id = {
            "BTC": "bitcoin",
            "ETH": "ethereum",
            "BNB": "binancecoin",
            "XRP": "ripple",
            "ADA": "cardano",
            "DOGE": "dogecoin",
            "SOL": "solana",
            "TRX": "tron",
            "DOT": "polkadot",
            "MATIC": "matic-network",
            "LTC": "litecoin",
            "SHIB": "shiba-inu",
            "AVAX": "avalanche-2",
            "UNI": "uniswap",
            "LINK": "chainlink",
            "ATOM": "cosmos",
            "XLM": "stellar",
            "ETC": "ethereum-classic",
            "XMR": "monero",
            "BCH": "bitcoin-cash"
        }
        
        # Reverse mapping
        self.id_to_symbol = {v: k for k, v in self.symbol_to_id.items()}
    
    def _symbol_to_coingecko_id(self, symbol: str) -> str:
        """Convert crypto symbol to CoinGecko coin ID"""
        symbol = symbol.upper().replace("USDT", "").replace("USD", "")
        return self.symbol_to_id.get(symbol, symbol.lower())
    
    def _coingecko_id_to_symbol(self, coin_id: str) -> str:
        """Convert CoinGecko coin ID to symbol"""
        return self.id_to_symbol.get(coin_id, coin_id.upper())
    
    async def get_market_prices(

        self,

        symbols: Optional[List[str]] = None,

        limit: int = 100

    ) -> List[Dict[str, Any]]:
        """

        Fetch REAL market prices from CoinGecko

        

        Args:

            symbols: List of crypto symbols (e.g., ["BTC", "ETH"])

            limit: Maximum number of results

        

        Returns:

            List of real market data

        """
        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                if symbols:
                    # Get specific symbols using /simple/price endpoint
                    coin_ids = [self._symbol_to_coingecko_id(s) for s in symbols]
                    
                    response = await client.get(
                        f"{self.base_url}/simple/price",
                        params={
                            "ids": ",".join(coin_ids),
                            "vs_currencies": "usd",
                            "include_24hr_change": "true",
                            "include_24hr_vol": "true",
                            "include_market_cap": "true"
                        }
                    )
                    response.raise_for_status()
                    data = response.json()
                    
                    # Transform to standard format
                    prices = []
                    for coin_id, coin_data in data.items():
                        symbol = self._coingecko_id_to_symbol(coin_id)
                        prices.append({
                            "symbol": symbol,
                            "name": symbol,  # CoinGecko simple/price doesn't include name
                            "price": coin_data.get("usd", 0),
                            "change24h": coin_data.get("usd_24h_change", 0),
                            "changePercent24h": coin_data.get("usd_24h_change", 0),
                            "volume24h": coin_data.get("usd_24h_vol", 0),
                            "marketCap": coin_data.get("usd_market_cap", 0),
                            "source": "coingecko",
                            "timestamp": int(datetime.utcnow().timestamp() * 1000)
                        })
                    
                    logger.info(f"βœ… CoinGecko: Fetched {len(prices)} real prices for specific symbols")
                    return prices
                
                else:
                    # Get top coins by market cap using /coins/markets endpoint
                    response = await client.get(
                        f"{self.base_url}/coins/markets",
                        params={
                            "vs_currency": "usd",
                            "order": "market_cap_desc",
                            "per_page": min(limit, 250),
                            "page": 1,
                            "sparkline": "false",
                            "price_change_percentage": "24h"
                        }
                    )
                    response.raise_for_status()
                    data = response.json()
                    
                    # Transform to standard format
                    prices = []
                    for coin in data:
                        prices.append({
                            "symbol": coin.get("symbol", "").upper(),
                            "name": coin.get("name", ""),
                            "price": coin.get("current_price", 0),
                            "change24h": coin.get("price_change_24h", 0),
                            "changePercent24h": coin.get("price_change_percentage_24h", 0),
                            "volume24h": coin.get("total_volume", 0),
                            "marketCap": coin.get("market_cap", 0),
                            "source": "coingecko",
                            "timestamp": int(datetime.utcnow().timestamp() * 1000)
                        })
                    
                    logger.info(f"βœ… CoinGecko: Fetched {len(prices)} real market prices")
                    return prices
        
        except httpx.HTTPError as e:
            logger.error(f"❌ CoinGecko API HTTP error: {e}")
            raise HTTPException(
                status_code=503,
                detail=f"CoinGecko API temporarily unavailable: {str(e)}"
            )
        except Exception as e:
            logger.error(f"❌ CoinGecko API failed: {e}")
            raise HTTPException(
                status_code=503,
                detail=f"Failed to fetch real market data from CoinGecko: {str(e)}"
            )
    
    async def get_ohlcv(self, symbol: str, days: int = 7) -> Dict[str, Any]:
        """

        Fetch REAL OHLCV (price history) data from CoinGecko

        

        Args:

            symbol: Cryptocurrency symbol (e.g., "BTC", "ETH")

            days: Number of days of historical data (1, 7, 14, 30, 90, 180, 365, max)

        

        Returns:

            Dict with OHLCV data

        """
        try:
            coin_id = self._symbol_to_coingecko_id(symbol)
            
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                # Get market chart (OHLC) data
                response = await client.get(
                    f"{self.base_url}/coins/{coin_id}/market_chart",
                    params={
                        "vs_currency": "usd",
                        "days": str(days),
                        "interval": "daily" if days > 1 else "hourly"
                    }
                )
                response.raise_for_status()
                data = response.json()
                
                logger.info(f"βœ… CoinGecko: Fetched {days} days of OHLCV data for {symbol}")
                return data
        
        except httpx.HTTPError as e:
            logger.error(f"❌ CoinGecko OHLCV API HTTP error: {e}")
            raise HTTPException(
                status_code=503,
                detail=f"CoinGecko OHLCV API unavailable: {str(e)}"
            )
        except Exception as e:
            logger.error(f"❌ CoinGecko OHLCV API failed: {e}")
            raise HTTPException(
                status_code=503,
                detail=f"Failed to fetch OHLCV data from CoinGecko: {str(e)}"
            )
    
    async def get_trending_coins(self, limit: int = 10) -> List[Dict[str, Any]]:
        """

        Fetch REAL trending coins from CoinGecko

        

        Returns:

            List of real trending coins

        """
        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                # Get trending coins
                response = await client.get(f"{self.base_url}/search/trending")
                response.raise_for_status()
                data = response.json()
                
                trending = []
                coins = data.get("coins", [])[:limit]
                
                # Get price data for trending coins
                if coins:
                    coin_ids = [coin["item"]["id"] for coin in coins]
                    
                    # Fetch current prices
                    price_response = await client.get(
                        f"{self.base_url}/simple/price",
                        params={
                            "ids": ",".join(coin_ids),
                            "vs_currencies": "usd",
                            "include_24hr_change": "true"
                        }
                    )
                    price_response.raise_for_status()
                    price_data = price_response.json()
                    
                    for idx, coin_obj in enumerate(coins):
                        coin = coin_obj["item"]
                        coin_id = coin["id"]
                        prices = price_data.get(coin_id, {})
                        
                        trending.append({
                            "symbol": coin.get("symbol", "").upper(),
                            "name": coin.get("name", ""),
                            "rank": idx + 1,
                            "price": prices.get("usd", 0),
                            "change24h": prices.get("usd_24h_change", 0),
                            "marketCapRank": coin.get("market_cap_rank", 0),
                            "source": "coingecko",
                            "timestamp": int(datetime.utcnow().timestamp() * 1000)
                        })
                
                logger.info(f"βœ… CoinGecko: Fetched {len(trending)} real trending coins")
                return trending
        
        except httpx.HTTPError as e:
            logger.error(f"❌ CoinGecko trending API HTTP error: {e}")
            raise HTTPException(
                status_code=503,
                detail=f"CoinGecko trending API unavailable: {str(e)}"
            )
        except Exception as e:
            logger.error(f"❌ CoinGecko trending API failed: {e}")
            raise HTTPException(
                status_code=503,
                detail=f"Failed to fetch trending coins: {str(e)}"
            )


# Global instance
coingecko_client = CoinGeckoClient()


__all__ = ["CoinGeckoClient", "coingecko_client"]