```python from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware import httpx import os from typing import Dict, Any from datetime import datetime, timedelta from newspaper import Article import openai import requests import logging import json from typing import List app = FastAPI() # Configure CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Configuration COINGECKO_API_URL = "https://api.coingecko.com/api/v3" COINMARKETCAP_API_KEY = os.getenv("COINMARKETCAP_API_KEY") NEWSAPI_KEY = os.getenv("NEWSAPI_KEY") OPENAI_KEY = os.getenv("OPENAI_KEY") TWITTER_BEARER_TOKEN = os.getenv("TWITTER_BEARER_TOKEN") # Initialize services openai.api_key = OPENAI_KEY logging.basicConfig(level=logging.INFO) @app.get("/pair-analysis") async def analyze_pair(base: str, quote: str = "USDT"): """ Get comprehensive analysis for a crypto pair """ try: # Get market data from CoinGecko coingecko_data = await get_coingecko_data(base, quote) # Get additional market data from CoinMarketCap if needed coinmarketcap_data = await get_coinmarketcap_data(base, quote) # Get social sentiment and news analysis sentiment = await get_market_sentiment(base) news = await get_crypto_news(base) # Generate AI-powered analysis analysis = await generate_ai_analysis( base=base, quote=quote, market_data=coingecko_data, sentiment=sentiment, news=news ) return { "base_symbol": base, "quote_symbol": quote, "current_price": coingecko_data["current_price"], "price_change_percentage_24h": coingecko_data["price_change_percentage_24h"], "market_cap": coingecko_data["market_cap"], "total_volume": coingecko_data["total_volume"], "circulating_supply": coingecko_data["circulating_supply"], "ath": coingecko_data["ath"], "sentiment": sentiment, "news": news, "analysis": analysis } except Exception as e: logging.error(f"Error analyzing pair {base}/{quote}: {str(e)}") raise HTTPException(status_code=500, detail="Error fetching pair analysis") async def get_coingecko_data(base: str, quote: str) -> Dict[str, Any]: """Fetch data from CoinGecko API""" try: # Find coin ID async with httpx.AsyncClient() as client: res = await client.get(f"{COINGECKO_API_URL}/coins/list") coins = res.json() coin_id = next((c["id"] for c in coins if c["symbol"].upper() == base.upper()), None) if not coin_id: logging.warning(f"Coin {base} not found in CoinGecko") return await get_coinmarketcap_data(base, quote) # Get market data res = await client.get( f"{COINGECKO_API_URL}/coins/{coin_id}", params={ "localization": "false", "tickers": "false", "market_data": "true", "community_data": "false", "developer_data": "false", "sparkline": "false" } ) data = res.json() quote = quote.lower() return { "current_price": data["market_data"]["current_price"][quote], "price_change_percentage_24h": data["market_data"]["price_change_percentage_24h"], "market_cap": data["market_data"]["market_cap"][quote], "total_volume": data["market_data"]["total_volume"][quote], "circulating_supply": data["market_data"]["circulating_supply"], "ath": data["market_data"]["ath"][quote] } except Exception as e: logging.error(f"Error fetching CoinGecko data: {str(e)}") raise async def get_coinmarketcap_data(base: str, quote: str) -> Dict[str, Any]: """Fetch data from CoinMarketCap API as fallback""" try: if not COINMARKETCAP_API_KEY: return {} headers = { 'X-CMC_PRO_API_KEY': COINMARKETCAP_API_KEY, 'Accept': 'application/json' } async with httpx.AsyncClient() as client: # First get coin ID res = await client.get( "https://pro-api.coinmarketcap.com/v1/cryptocurrency/map", headers=headers, params={"symbol": base} ) coin_data = res.json() if not coin_data.get('data'): return {} coin_id = coin_data['data'][0]['id'] # Get market data res = await client.get( "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest", headers=headers, params={ "id": coin_id, "convert": quote } ) data = res.json() quote_data = data['data'][str(coin_id)]['quote'][quote.upper()] return { "current_price": quote_data['price'], "price_change_percentage_24h": quote_data['percent_change_24h'], "market_cap": quote_data['market_cap'], "total_volume": quote_data['volume_24h'], "circulating_supply": data['data'][str(coin_id)]['circulating_supply'], "ath": 0 # CMC doesn't provide ATH in quotes endpoint } except Exception as e: logging.error(f"CoinMarketCap API error: {str(e)}") return {} async def get_market_sentiment(base: str) -> Dict[str, float]: """Analyze social media sentiment for a cryptocurrency""" # Get Twitter sentiment tweets = await get_twitter_sentiment(base) # Analyze with OpenAI system_prompt = f""" Analyze the sentiment of these cryptocurrency (coin: {base}) related tweets. Return a JSON response with the following structure: {{ "bullish": , "bearish": , "neutral": }} """ response = openai.ChatCompletion.create( model="gpt-4", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": "\n".join(tweets[:20])} # Analyze first 20 tweets ], response_format={ "type": "json_object" } ) return json.loads(response.choices[0].message.content) async def get_twitter_sentiment(base: str) -> List[str]: """Fetch recent tweets about the cryptocurrency""" async with httpx.AsyncClient() as client: res = await client.get( "https://api.twitter.com/2/tweets/search/recent", headers={"Authorization": f"Bearer {TWITTER_BEARER_TOKEN}"}, params={ "query": f"{base} lang:en -is:retweet", "max_results": 20, "tweet.fields": "text" } ) data = res.json() return [tweet["text"] for tweet in data.get("data", [])] async def get_crypto_news(base: str) -> List[Dict[str, str]]: """Fetch relevant news articles for the cryptocurrency""" try: async with httpx.AsyncClient() as client: # Get news from NewsAPI res = await client.get( "https://newsapi.org/v2/everything", params={ "q": base + " cryptocurrency", "sortBy": "publishedAt", "pageSize": 5, "apiKey": NEWSAPI_KEY } ) news_data = res.json() processed_news = [] for article in news_data.get("articles", [])[:5]: try: news_article = Article(article["url"]) news_article.download() news_article.parse() processed_news.append({ "title": article["title"], "source": article["source"]["name"], "url": article["url"], "image_url": article.get("urlToImage", ""), "published_at": article["publishedAt"], "summary": news_article.text[:200] + "..." if news_article.text else "" }) except Exception as e: logging.warning(f"Error processing article {article['url']}: {str(e)}") continue return processed_news except Exception as e: logging.error(f"Error fetching crypto news: {str(e)}") return [] async def generate_ai_analysis(base: str, quote: str, market_data: Dict, sentiment: Dict, news: List) -> Dict[str, Any]: """Generate AI-powered trading analysis using GPT-4""" prompt = f""" Analyze the following cryptocurrency market data for {base}/{quote}: Current Price: {market_data['current_price']} {quote} 24h Change: {market_data['price_change_percentage_24h']}% Market Cap: {market_data['market_cap']} {quote} 24h Volume: {market_data['total_volume']} {quote} Market Sentiment: - Bullish: {sentiment['bullish']}% - Bearish: {sentiment['bearish']}% - Neutral: {sentiment['neutral']}% Recent News Highlights: {[n['title'] for n in news]} Based on this data, provide trading analysis with: - Probability of profitable day trades - Probability of profitable long-term hold - Recommended trading strategy - Optimal entry and exit points Return response as JSON with these fields: {{ "day_trade": {{"probability": number, "confidence": string}}, "long_term": {{"probability": number, "confidence": string}}, "recommended_strategy": string, "entry_points": string, "exit_points": string }} """ response = openai.ChatCompletion.create( model="gpt-4", messages=[ {"role": "system", "content": "You are an expert cryptocurrency trading analyst"}, {"role": "user", "content": prompt} ], temperature=0.7, response_format={ "type": "json_object" } ) return json.loads(response.choices[0].message.content) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) ```