gate_dash / api.py
luguog's picture
Create api.py
a965e54 verified
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import ccxt
import os
import pandas as pd
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
# CORS (optional)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
exchange = ccxt.gateio({
'apiKey': os.getenv("GATE_API_KEY"),
'secret': os.getenv("GATE_API_SECRET"),
'enableRateLimit': True,
'options': {'defaultType': 'swap'}
})
@app.get("/api/data")
def get_data():
try:
markets = exchange.load_markets()
usdt_pairs = [s for s in markets if "/USDT" in s and markets[s].get("type") == "swap"]
results = []
for symbol in usdt_pairs:
try:
ticker = exchange.fetch_ticker(symbol)
price = ticker['last']
volume = ticker['quoteVolume']
orderbook = exchange.fetch_order_book(symbol)
if orderbook['asks'] and orderbook['bids']:
spread = orderbook['asks'][0][0] - orderbook['bids'][0][0]
spread_pct = (spread / price) * 100
bid_depth = sum(b[1] for b in orderbook['bids'][:5])
ask_depth = sum(a[1] for a in orderbook['asks'][:5])
depth = bid_depth + ask_depth
ohlcv = exchange.fetch_ohlcv(symbol, '1h', limit=24)
closes = [x[4] for x in ohlcv]
volatility = (pd.Series(closes).std() / pd.Series(closes).mean()) * 100
score = (
max(0, 100 - (spread_pct * 20)) +
min(100, volume / 200000 * 100) +
min(100, depth / 100) +
max(0, 100 - (volatility * 10))
) / 4
results.append({
"symbol": symbol,
"price": price,
"spread_pct": spread_pct,
"volume_24h": volume,
"depth": depth,
"volatility": volatility,
"mm_score": round(score, 2)
})
except:
continue
top_symbols = sorted(results, key=lambda x: x['mm_score'], reverse=True)[:10]
return {"top_symbols": top_symbols}
except Exception as e:
return {"error": str(e)}