Spaces:
Paused
Paused
File size: 4,513 Bytes
be62102 | 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 | """
Multi-Exchange Gateway & Top Binance/Crypto Market Screener
Supports CCXT Verified Exchange Connections:
- Binance (Spot / Futures)
- Bybit
- OKX
- KuCoin
- Gate.io
- Bitget
"""
import ccxt
import asyncio
import httpx
import time
class MultiExchangeManager:
def __init__(self):
self.supported_exchanges = ['binance', 'bybit', 'okx', 'kucoin', 'gateio', 'bitget']
self.active_exchange_id = 'binance'
self.active_client = None
self.is_live_trading = False
self.api_credentials = {}
self.top_tickers = []
self.last_ticker_update = 0
def init_exchange(self, exchange_id='binance', api_key=None, api_secret=None, passphrase=None, is_testnet=False):
exchange_id = exchange_id.lower()
if exchange_id not in self.supported_exchanges:
exchange_id = 'binance'
self.active_exchange_id = exchange_id
config = {
'enableRateLimit': True,
'timeout': 15000,
}
if api_key and api_secret:
config['apiKey'] = api_key
config['secret'] = api_secret
if passphrase and exchange_id in ['okx', 'kucoin']:
config['password'] = passphrase
self.is_live_trading = True
else:
self.is_live_trading = False
exchange_class = getattr(ccxt, exchange_id)
self.active_client = exchange_class(config)
if is_testnet:
self.active_client.set_sandbox_mode(True)
return {"status": "connected", "exchange": exchange_id, "mode": "LIVE" if self.is_live_trading else "PAPER_FEED"}
async def fetch_top_100_binance_tokens(self):
"""Fetch real-time top 100+ Binance tokens with 24h stats, volume, high, low, change"""
try:
now = time.time()
if self.top_tickers and (now - self.last_ticker_update) < 4:
return self.top_tickers
async with httpx.AsyncClient(timeout=8.0) as client:
res = await client.get('https://api.binance.com/api/v3/ticker/24hr')
if res.status_code == 200:
data = res.json()
# Filter for USDT pairs only and sort by quoteVolume (most liquid)
usdt_pairs = [
{
"symbol": item["symbol"],
"price": float(item["lastPrice"]),
"change": float(item["priceChangePercent"]),
"high": float(item["highPrice"]),
"low": float(item["lowPrice"]),
"volume": float(item["volume"]),
"quoteVolume": float(item["quoteVolume"]),
"count": int(item["count"])
}
for item in data
if item["symbol"].endswith("USDT") and not item["symbol"].endswith("UPUSDT") and not item["symbol"].endswith("DOWNUSDT")
]
# Sort by volume desc
usdt_pairs.sort(key=lambda x: x["quoteVolume"], reverse=True)
self.top_tickers = usdt_pairs[:120] # Top 120 live Binance tokens
self.last_ticker_update = now
return self.top_tickers
except Exception as e:
print(f"[EXCHANGE] Error fetching top 100 tickers: {e}")
return self.top_tickers or []
async def fetch_live_orderbook(self, symbol="BTCUSDT", limit=15):
"""Fetch live depth L2 orderbook from Binance / Active exchange"""
try:
clean_symbol = symbol.replace('/', '').upper()
async with httpx.AsyncClient(timeout=5.0) as client:
res = await client.get(f'https://api.binance.com/api/v3/depth?symbol={clean_symbol}&limit={limit}')
if res.status_code == 200:
data = res.json()
bids = [[float(p), float(q)] for p, q in data.get('bids', [])]
asks = [[float(p), float(q)] for p, q in data.get('asks', [])]
return {
"symbol": clean_symbol,
"bids": bids,
"asks": asks,
"lastUpdateId": data.get("lastUpdateId", 0)
}
except Exception as e:
pass
return {"symbol": symbol, "bids": [], "asks": []}
exchange_mgr = MultiExchangeManager()
|