File size: 4,480 Bytes
320a0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc45523
320a0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc45523
320a0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc45523
320a0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc45523
320a0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Cryptocurrency Data Tools using CoinGecko API
No API key required - Free tier with generous limits
"""

from pycoingecko import CoinGeckoAPI
from typing import Dict, Any, List, Optional
import logging

logger = logging.getLogger(__name__)

# Initialize CoinGecko client
cg = CoinGeckoAPI()

def get_crypto_price(coin_id: str, vs_currency: str = "usd") -> Dict[str, Any]:
    """Get current crypto price. Example: get_crypto_price("bitcoin", vs_currency="usd")"""
    try:
        data = cg.get_price(
            ids=coin_id,
            vs_currencies=vs_currency,
            include_24hr_change=True,
            include_market_cap=True,
            include_24hr_vol=True
        )
        
        if not data or coin_id not in data:
            return {"error": f"Coin '{coin_id}' not found"}
            
        coin_data = data[coin_id]
        return {
            "coin": coin_id,
            "price": coin_data.get(vs_currency, 0),
            "market_cap": coin_data.get(f"{vs_currency}_market_cap", 0),
            "24h_volume": coin_data.get(f"{vs_currency}_24h_vol", 0),
            "24h_change": coin_data.get(f"{vs_currency}_24h_change", 0),
            "currency": vs_currency.upper()
        }
    except Exception as e:
        logger.error(f"CoinGecko error for {coin_id}: {e}")
        return {"error": str(e)}

def get_crypto_market_data(coin_id: str) -> str:
    """Get comprehensive crypto market data. Example: get_crypto_market_data("ethereum")"""
    try:
        data = cg.get_coin_by_id(
            id=coin_id,
            localization=False,
            tickers=False,
            market_data=True,
            community_data=False,
            developer_data=False
        )
        
        market = data.get("market_data", {})
        
        return f"""
Crypto Market Data: {data.get('name', coin_id).upper()}
Symbol: {data.get('symbol', 'N/A').upper()}
--------------------------------
Current Price: ${market.get('current_price', {}).get('usd', 0):,.2f}
Market Cap: ${market.get('market_cap', {}).get('usd', 0):,.0f}
24h Volume: ${market.get('total_volume', {}).get('usd', 0):,.0f}
--------------------------------
24h Change: {market.get('price_change_percentage_24h', 0):.2f}%
7d Change: {market.get('price_change_percentage_7d', 0):.2f}%
30d Change: {market.get('price_change_percentage_30d', 0):.2f}%
--------------------------------
All-Time High: ${market.get('ath', {}).get('usd', 0):,.2f}
ATH Date: {market.get('ath_date', {}).get('usd', 'N/A')[:10]}
All-Time Low: ${market.get('atl', {}).get('usd', 0):,.2f}
ATL Date: {market.get('atl_date', {}).get('usd', 'N/A')[:10]}
"""
    except Exception as e:
        logger.error(f"CoinGecko error for {coin_id}: {e}")
        return f"Error fetching market data for {coin_id}: {str(e)}"

def get_trending_crypto() -> str:
    """Get trending cryptocurrencies. Example: get_trending_crypto()"""
    try:
        data = cg.get_search_trending()
        coins = data.get('coins', [])
        
        if not coins:
            return "No trending coins data available"
            
        summary = ["=== TRENDING CRYPTOCURRENCIES (24h) ===\n"]
        
        for i, item in enumerate(coins[:10], 1):
            coin = item.get('item', {})
            summary.append(
                f"{i}. {coin.get('name')} ({coin.get('symbol', 'N/A').upper()})"
                f" - Rank #{coin.get('market_cap_rank', 'N/A')}"
            )
            
        return "\n".join(summary)
    except Exception as e:
        logger.error(f"CoinGecko error: {e}")
        return f"Error fetching trending coins: {str(e)}"

def search_crypto(query: str) -> str:
    """Search for cryptocurrency ID. Example: search_crypto("pepe")"""
    try:
        data = cg.search(query=query)
        coins = data.get('coins', [])
        
        if not coins:
            return f"No results found for '{query}'"
            
        summary = [f"=== SEARCH RESULTS FOR '{query}' ===\n"]
        
        for coin in coins[:10]:
            summary.append(
                f"• {coin.get('name')} ({coin.get('symbol', 'N/A').upper()})"
                f" - ID: {coin.get('id')} - Rank #{coin.get('market_cap_rank', 'N/A')}"
            )
            
        summary.append("\nUse the 'id' with get_crypto_market_data() for detailed info")
        return "\n".join(summary)
    except Exception as e:
        logger.error(f"CoinGecko search error: {e}")
        return f"Error searching for '{query}': {str(e)}"