File size: 31,056 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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
#!/usr/bin/env python3
"""

Real API Clients - ZERO MOCK DATA

All clients fetch REAL data from external APIs

"""

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

logger = logging.getLogger(__name__)


class RealAPIConfiguration:
    """Real API keys - Loaded from environment variables"""
    
    import os
    
    # Blockchain Explorers
    TRONSCAN_API_KEY = os.getenv("TRONSCAN_API_KEY", "7ae72726-bffe-4e74-9c33-97b761eeea21")
    TRONSCAN_BASE_URL = "https://apilist.tronscan.org/api"
    
    BSCSCAN_API_KEY = os.getenv("BSCSCAN_API_KEY", "K62RKHGXTDCG53RU4MCG6XABIMJKTN19IT")
    BSCSCAN_BASE_URL = "https://api.bscscan.com/api"
    
    # Ϊ©Ω„ΫŒΨ― Ψ―ΩˆΩ… Etherscan (جدید)
    ETHERSCAN_API_KEY = os.getenv("ETHERSCAN_API_KEY", "T6IR8VJHX2NE6ZJW2S3FDVN1TYG4PYYI45")
    ETHERSCAN_BASE_URL = "https://api.etherscan.io/api"
    
    # Market Data - Ϊ©Ω„ΫŒΨ―Ω‡Ψ§ΫŒ جدید
    COINMARKETCAP_API_KEY = os.getenv("COINMARKETCAP_API_KEY", "a35ffaec-c66c-4f16-81e3-41a717e4822f")
    COINMARKETCAP_BASE_URL = "https://pro-api.coinmarketcap.com/v1"
    
    # News - Ϊ©Ω„ΫŒΨ― جدید
    NEWSAPI_API_KEY = os.getenv("NEWSAPI_API_KEY", "968a5e25552b4cb5ba3280361d8444ab")
    NEWSAPI_BASE_URL = "https://newsapi.org/v2"
    
    # HuggingFace Space - Ϊ©Ω„ΫŒΨ― جدید
    # IMPORTANT: Strip whitespace to avoid "Illegal header value" errors
    HF_API_TOKEN = os.getenv("HF_API_TOKEN", "").strip()
    HF_SPACE_BASE_URL = os.getenv("HF_SPACE_BASE_URL", "https://really-amin-datasourceforcryptocurrency.hf.space").strip()
    HF_SPACE_WS_URL = os.getenv("HF_SPACE_WS_URL", "wss://really-amin-datasourceforcryptocurrency.hf.space/ws").strip()
    
    # Ω…Ω†Ψ§Ψ¨ΨΉ اآافی جدید
    # TronGrid (Ω…Ω†Ψ¨ΨΉ Ψ―ΩˆΩ… برای Tron)
    TRONGRID_API_KEY = os.getenv("TRONGRID_API_KEY", "7ae72726-bffe-4e74-9c33-97b761eeea21")  # Ω‡Ω…Ψ§Ω† Ϊ©Ω„ΫŒΨ― TronScan
    TRONGRID_BASE_URL = "https://api.trongrid.io/v1"
    
    # Blockchair (برای Ϊ†Ω†Ψ―ΫŒΩ† Ψ¨Ω„Ψ§Ϊ©Ϊ†ΫŒΩ†)
    BLOCKCHAIR_API_KEY = os.getenv("BLOCKCHAIR_API_KEY", "YOUR_BLOCKCHAIR_KEY")
    BLOCKCHAIR_BASE_URL = "https://api.blockchair.com"
    
    # Alternative.me برای Fear & Greed Index
    ALTERNATIVE_ME_BASE_URL = "https://api.alternative.me"
    
    # CoinGecko (Ψ¨Ψ―ΩˆΩ† Ω†ΫŒΨ§Ψ² Ψ¨Ω‡ Ϊ©Ω„ΫŒΨ―)
    COINGECKO_BASE_URL = "https://api.coingecko.com/api/v3"
    
    # Binance Public API (Ψ¨Ψ―ΩˆΩ† Ω†ΫŒΨ§Ψ² Ψ¨Ω‡ Ϊ©Ω„ΫŒΨ―)
    BINANCE_BASE_URL = "https://api.binance.com/api/v3"
    
    # CryptoCompare 
    CRYPTOCOMPARE_API_KEY = os.getenv("CRYPTOCOMPARE_API_KEY", "YOUR_CRYPTOCOMPARE_KEY")
    CRYPTOCOMPARE_BASE_URL = "https://min-api.cryptocompare.com/data"
    
    # Reddit API (برای Ψ§Ψ­Ψ³Ψ§Ψ³Ψ§Ψͺ Ψ§Ψ¬ΨͺΩ…Ψ§ΨΉΫŒ)
    REDDIT_BASE_URL = "https://www.reddit.com/r"


class CoinMarketCapClient:
    """

    Real CoinMarketCap API Client

    Fetches REAL market data - NO MOCK DATA

    """
    
    def __init__(self):
        self.api_key = RealAPIConfiguration.COINMARKETCAP_API_KEY
        self.base_url = RealAPIConfiguration.COINMARKETCAP_BASE_URL
        self.headers = {
            "X-CMC_PRO_API_KEY": self.api_key,
            "Accept": "application/json"
        }
    
    async def get_latest_listings(self, limit: int = 100) -> Dict[str, Any]:
        """

        Fetch REAL latest cryptocurrency listings

        """
        try:
            async with httpx.AsyncClient(timeout=15.0) as client:
                response = await client.get(
                    f"{self.base_url}/cryptocurrency/listings/latest",
                    headers=self.headers,
                    params={
                        "limit": limit,
                        "convert": "USD"
                    }
                )
                response.raise_for_status()
                data = response.json()
                
                logger.info(f"βœ… CoinMarketCap: Fetched {len(data.get('data', []))} real listings")
                return {
                    "success": True,
                    "data": data.get("data", []),
                    "meta": {
                        "source": "coinmarketcap",
                        "timestamp": datetime.utcnow().isoformat(),
                        "cached": False
                    }
                }
        except Exception as e:
            logger.error(f"❌ CoinMarketCap API failed: {e}")
            raise HTTPException(status_code=503, detail=f"Failed to fetch real market data: {str(e)}")
    
    async def get_quotes(self, symbols: List[str]) -> Dict[str, Any]:
        """

        Fetch REAL price quotes for specific symbols

        """
        try:
            async with httpx.AsyncClient(timeout=15.0) as client:
                response = await client.get(
                    f"{self.base_url}/cryptocurrency/quotes/latest",
                    headers=self.headers,
                    params={
                        "symbol": ",".join(symbols),
                        "convert": "USD"
                    }
                )
                response.raise_for_status()
                data = response.json()
                
                logger.info(f"βœ… CoinMarketCap: Fetched real quotes for {len(symbols)} symbols")
                return {
                    "success": True,
                    "data": data.get("data", {}),
                    "meta": {
                        "source": "coinmarketcap",
                        "timestamp": datetime.utcnow().isoformat()
                    }
                }
        except Exception as e:
            logger.error(f"❌ CoinMarketCap quotes failed: {e}")
            raise HTTPException(status_code=503, detail=f"Failed to fetch real quotes: {str(e)}")
    
    async def get_ohlc(self, symbol: str, interval: str = "1h", limit: int = 100) -> Dict[str, Any]:
        """

        Fetch REAL OHLC data from CoinMarketCap

        """
        try:
            async with httpx.AsyncClient(timeout=15.0) as client:
                response = await client.get(
                    f"{self.base_url}/cryptocurrency/quotes/historical",
                    headers=self.headers,
                    params={
                        "symbol": symbol,
                        "count": limit,
                        "interval": interval
                    }
                )
                response.raise_for_status()
                data = response.json()
                
                logger.info(f"βœ… CoinMarketCap: Fetched real OHLC for {symbol}")
                return {
                    "success": True,
                    "data": data.get("data", {}),
                    "meta": {
                        "source": "coinmarketcap",
                        "timestamp": datetime.utcnow().isoformat()
                    }
                }
        except Exception as e:
            logger.error(f"❌ CoinMarketCap OHLC failed: {e}")
            # Try alternative source if CMC fails
            return await self._get_ohlc_fallback(symbol, interval, limit)
    
    async def _get_ohlc_fallback(self, symbol: str, interval: str, limit: int) -> Dict[str, Any]:
        """

        Fallback chain for OHLC data with at least 3 providers

        Priority: Binance β†’ CoinGecko β†’ CoinPaprika β†’ CoinCap β†’ CryptoCompare

        """
        fallback_providers = [
            ("binance", self._fetch_binance_ohlc),
            ("coingecko", self._fetch_coingecko_ohlc),
            ("coinpaprika", self._fetch_coinpaprika_ohlc),
            ("coincap", self._fetch_coincap_ohlc),
            ("cryptocompare", self._fetch_cryptocompare_ohlc)
        ]
        
        last_error = None
        for provider_name, fetch_func in fallback_providers:
            try:
                logger.info(f"πŸ”„ Trying OHLC fallback: {provider_name}")
                result = await fetch_func(symbol, interval, limit)
                if result and result.get("success"):
                    logger.info(f"βœ… {provider_name} fallback succeeded: {len(result.get('data', []))} candles")
                    return result
            except Exception as e:
                logger.warning(f"⚠️ {provider_name} fallback failed: {e}")
                last_error = e
                continue
        
        logger.error(f"❌ All OHLC fallback providers failed. Last error: {last_error}")
        raise HTTPException(status_code=503, detail=f"All OHLC sources failed. Tried: {[p[0] for p in fallback_providers]}")
    
    async def _fetch_binance_ohlc(self, symbol: str, interval: str, limit: int) -> Dict[str, Any]:
        """Fallback 1: Binance"""
        interval_map = {"1m": "1m", "5m": "5m", "15m": "15m", "1h": "1h", "4h": "4h", "1d": "1d"}
        binance_interval = interval_map.get(interval, "1h")
        
        async with httpx.AsyncClient(timeout=15.0) as client:
            response = await client.get(
                "https://api.binance.com/api/v3/klines",
                params={
                    "symbol": f"{symbol}USDT",
                    "interval": binance_interval,
                    "limit": limit
                }
            )
            response.raise_for_status()
            klines = response.json()
            
            ohlc_data = []
            for kline in klines:
                ohlc_data.append({
                    "ts": int(kline[0]),
                    "open": float(kline[1]),
                    "high": float(kline[2]),
                    "low": float(kline[3]),
                    "close": float(kline[4]),
                    "volume": float(kline[5])
                })
            
            return {
                "success": True,
                "data": ohlc_data,
                "meta": {"source": "binance", "timestamp": datetime.utcnow().isoformat(), "fallback": True}
            }
    
    async def _fetch_coingecko_ohlc(self, symbol: str, interval: str, limit: int) -> Dict[str, Any]:
        """Fallback 2: CoinGecko"""
        # Map interval to CoinGecko format
        days_map = {"1h": 1, "4h": 7, "1d": 30}
        days = days_map.get(interval, 1)
        
        # Get coin ID from symbol
        coin_id_map = {"BTC": "bitcoin", "ETH": "ethereum", "BNB": "binancecoin", "USDT": "tether"}
        coin_id = coin_id_map.get(symbol.upper(), symbol.lower())
        
        async with httpx.AsyncClient(timeout=15.0) as client:
            response = await client.get(
                f"{RealAPIConfiguration.COINGECKO_BASE_URL}/coins/{coin_id}/ohlc",
                params={"vs_currency": "usd", "days": days}
            )
            response.raise_for_status()
            data = response.json()
            
            ohlc_data = []
            for item in data[:limit]:
                ohlc_data.append({
                    "ts": item[0],
                    "open": item[1],
                    "high": item[2],
                    "low": item[3],
                    "close": item[4],
                    "volume": 0  # CoinGecko doesn't provide volume in OHLC endpoint
                })
            
            return {
                "success": True,
                "data": ohlc_data,
                "meta": {"source": "coingecko", "timestamp": datetime.utcnow().isoformat(), "fallback": True}
            }
    
    async def _fetch_coinpaprika_ohlc(self, symbol: str, interval: str, limit: int) -> Dict[str, Any]:
        """Fallback 3: CoinPaprika"""
        # Get coin ID
        coin_id_map = {"BTC": "btc-bitcoin", "ETH": "eth-ethereum", "BNB": "bnb-binance-coin"}
        coin_id = coin_id_map.get(symbol.upper(), f"{symbol.lower()}-{symbol.lower()}")
        
        # Map interval
        quote_map = {"1h": "1h", "4h": "4h", "1d": "1d"}
        quote = quote_map.get(interval, "1h")
        
        async with httpx.AsyncClient(timeout=15.0) as client:
            response = await client.get(
                f"https://api.coinpaprika.com/v1/coins/{coin_id}/ohlcv/historical",
                params={"quote": "usd", "interval": quote}
            )
            response.raise_for_status()
            data = response.json()
            
            ohlc_data = []
            for item in data[-limit:]:  # Get last N items
                ohlc_data.append({
                    "ts": int(item["time_open"]),
                    "open": float(item["open"]),
                    "high": float(item["high"]),
                    "low": float(item["low"]),
                    "close": float(item["close"]),
                    "volume": float(item["volume"])
                })
            
            return {
                "success": True,
                "data": ohlc_data,
                "meta": {"source": "coinpaprika", "timestamp": datetime.utcnow().isoformat(), "fallback": True}
            }
    
    async def _fetch_coincap_ohlc(self, symbol: str, interval: str, limit: int) -> Dict[str, Any]:
        """Fallback 4: CoinCap"""
        coin_id_map = {"BTC": "bitcoin", "ETH": "ethereum", "BNB": "binance-coin"}
        coin_id = coin_id_map.get(symbol.upper(), symbol.lower())
        
        async with httpx.AsyncClient(timeout=15.0) as client:
            response = await client.get(
                f"https://api.coincap.io/v2/assets/{coin_id}/history",
                params={"interval": interval, "limit": limit}
            )
            response.raise_for_status()
            data = response.json()
            
            ohlc_data = []
            for item in data.get("data", []):
                price = float(item.get("priceUsd", 0))
                ohlc_data.append({
                    "ts": int(item["time"]),
                    "open": price,
                    "high": price,
                    "low": price,
                    "close": price,
                    "volume": float(item.get("volumeUsd", 0))
                })
            
            return {
                "success": True,
                "data": ohlc_data,
                "meta": {"source": "coincap", "timestamp": datetime.utcnow().isoformat(), "fallback": True}
            }
    
    async def _fetch_cryptocompare_ohlc(self, symbol: str, interval: str, limit: int) -> Dict[str, Any]:
        """Fallback 5: CryptoCompare"""
        interval_map = {"1h": "histohour", "4h": "histohour", "1d": "histoday"}
        endpoint = interval_map.get(interval, "histohour")
        
        async with httpx.AsyncClient(timeout=15.0) as client:
            response = await client.get(
                f"https://min-api.cryptocompare.com/data/v2/{endpoint}",
                params={
                    "fsym": symbol.upper(),
                    "tsym": "USD",
                    "limit": limit
                }
            )
            response.raise_for_status()
            data = response.json()
            
            ohlc_data = []
            for item in data.get("Data", {}).get("Data", []):
                ohlc_data.append({
                    "ts": item["time"] * 1000,
                    "open": float(item["open"]),
                    "high": float(item["high"]),
                    "low": float(item["low"]),
                    "close": float(item["close"]),
                    "volume": float(item["volumefrom"])
                })
            
            return {
                "success": True,
                "data": ohlc_data,
                "meta": {"source": "cryptocompare", "timestamp": datetime.utcnow().isoformat(), "fallback": True}
            }


class NewsAPIClient:
    """

    Real NewsAPI Client

    Fetches REAL crypto news - NO MOCK DATA

    """
    
    def __init__(self):
        self.api_key = RealAPIConfiguration.NEWSAPI_API_KEY
        self.base_url = RealAPIConfiguration.NEWSAPI_BASE_URL
    
    async def get_crypto_news(self, symbol: str = "BTC", limit: int = 20) -> Dict[str, Any]:
        """

        Fetch REAL crypto news from NewsAPI

        """
        try:
            search_query = f"{symbol} OR cryptocurrency OR crypto OR bitcoin"
            
            async with httpx.AsyncClient(timeout=10.0) as client:
                response = await client.get(
                    f"{self.base_url}/everything",
                    params={
                        "q": search_query,
                        "apiKey": self.api_key,
                        "language": "en",
                        "sortBy": "publishedAt",
                        "pageSize": limit
                    }
                )
                response.raise_for_status()
                data = response.json()
            
            articles = []
            for article in data.get("articles", []):
                article_id = hashlib.md5(article["url"].encode()).hexdigest()
                articles.append({
                    "id": article_id,
                    "title": article["title"],
                    "summary": article.get("description", ""),
                    "url": article["url"],
                    "source": article["source"]["name"],
                    "published_at": article["publishedAt"],
                    "image_url": article.get("urlToImage"),
                    "author": article.get("author")
                })
            
            logger.info(f"βœ… NewsAPI: Fetched {len(articles)} real articles")
            return {
                "success": True,
                "articles": articles,
                "meta": {
                    "total": len(articles),
                    "source": "newsapi",
                    "query": search_query,
                    "timestamp": datetime.utcnow().isoformat()
                }
            }
        except Exception as e:
            logger.error(f"❌ NewsAPI failed: {e}")
            raise HTTPException(status_code=503, detail=f"Failed to fetch real news: {str(e)}")
    
    async def get_top_headlines(self, limit: int = 10) -> Dict[str, Any]:
        """

        Fetch REAL top crypto headlines

        """
        try:
            async with httpx.AsyncClient(timeout=10.0) as client:
                response = await client.get(
                    f"{self.base_url}/top-headlines",
                    params={
                        "q": "cryptocurrency OR bitcoin",
                        "apiKey": self.api_key,
                        "language": "en",
                        "pageSize": limit
                    }
                )
                response.raise_for_status()
                data = response.json()
            
            articles = []
            for article in data.get("articles", []):
                article_id = hashlib.md5(article["url"].encode()).hexdigest()
                articles.append({
                    "id": article_id,
                    "title": article["title"],
                    "summary": article.get("description", ""),
                    "url": article["url"],
                    "source": article["source"]["name"],
                    "published_at": article["publishedAt"]
                })
            
            logger.info(f"βœ… NewsAPI: Fetched {len(articles)} real headlines")
            return {
                "success": True,
                "articles": articles,
                "meta": {
                    "source": "newsapi",
                    "timestamp": datetime.utcnow().isoformat()
                }
            }
        except Exception as e:
            logger.error(f"❌ NewsAPI headlines failed: {e}")
            raise HTTPException(status_code=503, detail=f"Failed to fetch headlines: {str(e)}")


class BlockchainExplorerClient:
    """

    Real Blockchain Explorer Clients

    Fetches REAL blockchain data - NO MOCK DATA

    """
    
    def __init__(self):
        self.etherscan_key = RealAPIConfiguration.ETHERSCAN_API_KEY
        self.bscscan_key = RealAPIConfiguration.BSCSCAN_API_KEY
        self.tronscan_key = RealAPIConfiguration.TRONSCAN_API_KEY
    
    async def get_ethereum_transactions(self, address: Optional[str] = None, limit: int = 20) -> Dict[str, Any]:
        """

        Fetch REAL Ethereum transactions

        """
        try:
            # Use a known whale address if none provided
            if not address:
                address = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"  # Binance Hot Wallet
            
            async with httpx.AsyncClient(timeout=10.0) as client:
                response = await client.get(
                    RealAPIConfiguration.ETHERSCAN_BASE_URL,
                    params={
                        "module": "account",
                        "action": "txlist",
                        "address": address,
                        "startblock": 0,
                        "endblock": 99999999,
                        "page": 1,
                        "offset": limit,
                        "sort": "desc",
                        "apikey": self.etherscan_key
                    }
                )
                response.raise_for_status()
                data = response.json()
            
            transactions = data.get("result", [])[:limit]
            
            logger.info(f"βœ… Etherscan: Fetched {len(transactions)} real transactions")
            return {
                "success": True,
                "chain": "ethereum",
                "transactions": transactions,
                "meta": {
                    "total": len(transactions),
                    "source": "etherscan",
                    "timestamp": datetime.utcnow().isoformat()
                }
            }
        except Exception as e:
            logger.error(f"❌ Etherscan failed: {e}")
            raise HTTPException(status_code=503, detail=f"Failed to fetch Ethereum data: {str(e)}")
    
    async def get_bsc_transactions(self, address: Optional[str] = None, limit: int = 20) -> Dict[str, Any]:
        """

        Fetch REAL BSC transactions

        """
        try:
            if not address:
                address = "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3"  # Binance BSC Hot Wallet
            
            async with httpx.AsyncClient(timeout=10.0) as client:
                response = await client.get(
                    RealAPIConfiguration.BSCSCAN_BASE_URL,
                    params={
                        "module": "account",
                        "action": "txlist",
                        "address": address,
                        "startblock": 0,
                        "endblock": 99999999,
                        "page": 1,
                        "offset": limit,
                        "sort": "desc",
                        "apikey": self.bscscan_key
                    }
                )
                response.raise_for_status()
                data = response.json()
            
            transactions = data.get("result", [])[:limit]
            
            logger.info(f"βœ… BSCScan: Fetched {len(transactions)} real transactions")
            return {
                "success": True,
                "chain": "bsc",
                "transactions": transactions,
                "meta": {
                    "total": len(transactions),
                    "source": "bscscan",
                    "timestamp": datetime.utcnow().isoformat()
                }
            }
        except Exception as e:
            logger.error(f"❌ BSCScan failed: {e}")
            raise HTTPException(status_code=503, detail=f"Failed to fetch BSC data: {str(e)}")
    
    async def get_tron_transactions(self, limit: int = 20) -> Dict[str, Any]:
        """

        Fetch REAL Tron transactions

        """
        try:
            async with httpx.AsyncClient(timeout=10.0) as client:
                response = await client.get(
                    f"{RealAPIConfiguration.TRONSCAN_BASE_URL}/transaction",
                    params={
                        "sort": "-timestamp",
                        "limit": limit
                    },
                    headers={
                        "TRON-PRO-API-KEY": self.tronscan_key
                    }
                )
                response.raise_for_status()
                data = response.json()
            
            transactions = data.get("data", [])
            
            logger.info(f"βœ… Tronscan: Fetched {len(transactions)} real transactions")
            return {
                "success": True,
                "chain": "tron",
                "transactions": transactions,
                "meta": {
                    "total": len(transactions),
                    "source": "tronscan",
                    "timestamp": datetime.utcnow().isoformat()
                }
            }
        except Exception as e:
            logger.error(f"❌ Tronscan failed: {e}")
            raise HTTPException(status_code=503, detail=f"Failed to fetch Tron data: {str(e)}")
    
    async def get_gas_prices(self, chain: str = "ethereum") -> Dict[str, Any]:
        """

        Fetch REAL gas prices

        """
        try:
            if chain.lower() == "ethereum":
                async with httpx.AsyncClient(timeout=10.0) as client:
                    response = await client.get(
                        RealAPIConfiguration.ETHERSCAN_BASE_URL,
                        params={
                            "module": "gastracker",
                            "action": "gasoracle",
                            "apikey": self.etherscan_key
                        }
                    )
                    response.raise_for_status()
                    data = response.json()
                
                result = data.get("result", {})
                
                logger.info(f"βœ… Etherscan: Fetched real gas prices")
                return {
                    "success": True,
                    "chain": "ethereum",
                    "gas_prices": {
                        "safe": float(result.get("SafeGasPrice", 0)),
                        "standard": float(result.get("ProposeGasPrice", 0)),
                        "fast": float(result.get("FastGasPrice", 0)),
                        "unit": "gwei"
                    },
                    "meta": {
                        "source": "etherscan",
                        "timestamp": datetime.utcnow().isoformat()
                    }
                }
            else:
                raise HTTPException(status_code=400, detail=f"Chain {chain} not supported")
        except Exception as e:
            logger.error(f"❌ Gas prices failed: {e}")
            raise HTTPException(status_code=503, detail=f"Failed to fetch gas prices: {str(e)}")


class HuggingFaceSpaceClient:
    """

    Real HuggingFace Space Client

    Connects to REAL HF Space - NO MOCK DATA

    """
    
    def __init__(self):
        # Ensure token is stripped to prevent "Illegal header value" errors
        self.api_token = (RealAPIConfiguration.HF_API_TOKEN or "").strip()
        self.base_url = RealAPIConfiguration.HF_SPACE_BASE_URL
        self.headers = {
            "Authorization": f"Bearer {self.api_token}",
            "Content-Type": "application/json"
        } if self.api_token else {
            "Content-Type": "application/json"
        }
    
    async def check_connection(self) -> Dict[str, Any]:
        """

        Check REAL connection to HF Space

        """
        try:
            async with httpx.AsyncClient(timeout=10.0) as client:
                response = await client.get(
                    f"{self.base_url}/api/health",
                    headers=self.headers
                )
                response.raise_for_status()
                
                logger.info(f"βœ… HuggingFace Space: Connected successfully")
                return {
                    "success": True,
                    "connected": True,
                    "space_url": self.base_url,
                    "timestamp": datetime.utcnow().isoformat()
                }
        except Exception as e:
            logger.error(f"❌ HuggingFace Space connection failed: {e}")
            return {
                "success": False,
                "connected": False,
                "error": str(e),
                "timestamp": datetime.utcnow().isoformat()
            }
    
    async def get_market_data(self) -> Dict[str, Any]:
        """

        Fetch REAL market data from HF Space

        """
        try:
            async with httpx.AsyncClient(timeout=15.0) as client:
                response = await client.get(
                    f"{self.base_url}/api/market",
                    headers=self.headers
                )
                response.raise_for_status()
                data = response.json()
                
                logger.info(f"βœ… HF Space: Fetched real market data")
                return data
        except Exception as e:
            logger.error(f"❌ HF Space market data failed: {e}")
            # Return error instead of mock data
            raise HTTPException(status_code=503, detail=f"HF Space unavailable: {str(e)}")
    
    async def get_trading_pairs(self) -> Dict[str, Any]:
        """

        Fetch REAL trading pairs from HF Space

        """
        try:
            async with httpx.AsyncClient(timeout=15.0) as client:
                response = await client.get(
                    f"{self.base_url}/api/market/pairs",
                    headers=self.headers
                )
                response.raise_for_status()
                data = response.json()
                
                logger.info(f"βœ… HF Space: Fetched real trading pairs")
                return data
        except Exception as e:
            logger.error(f"❌ HF Space trading pairs failed: {e}")
            raise HTTPException(status_code=503, detail=f"Failed to fetch trading pairs: {str(e)}")


# Global instances - Initialize once
cmc_client = CoinMarketCapClient()
news_client = NewsAPIClient()
blockchain_client = BlockchainExplorerClient()
hf_client = HuggingFaceSpaceClient()


# Export all clients
__all__ = [
    "RealAPIConfiguration",
    "CoinMarketCapClient",
    "NewsAPIClient",
    "BlockchainExplorerClient",
    "HuggingFaceSpaceClient",
    "cmc_client",
    "news_client",
    "blockchain_client",
    "hf_client"
]