File size: 10,822 Bytes
2e62bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d76c3e
 
2e62bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d76c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e62bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
```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": <percentage 0-100>,
        "bearish": <percentage 0-100>,
        "neutral": <percentage 0-100>
    }}
    """
    
    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)
```