Download api/app.py from Qempireautomation/qrypto-engine: direct link, hf CLI and curl.
- Browser
- Download file 19.3 kB
-
https://huggingface.co/Qempireautomation/qrypto-engine/resolve/main/api/app.py
- Command line
-
hf download hf://Qempireautomation/qrypto-engine/api/app.py
-
curl -L -o app.py https://huggingface.co/Qempireautomation/qrypto-engine/resolve/main/api/app.py
19.3 kB
| """Qrypto API — Starlette app. Run: uvicorn api.app:app --host 0.0.0.0 --port 7860""" | |
| from __future__ import annotations | |
| import asyncio | |
| import contextlib | |
| import logging | |
| import os | |
| import time | |
| from functools import wraps | |
| from typing import Any, Callable | |
| from starlette.applications import Starlette | |
| from starlette.middleware import Middleware | |
| from starlette.middleware.cors import CORSMiddleware | |
| from starlette.requests import Request | |
| from starlette.responses import JSONResponse | |
| from starlette.routing import Route | |
| from qrypto import __version__ | |
| from qrypto.alpaca import AlpacaBroker, AlpacaMarket | |
| from qrypto.backtest import run_backtest | |
| from qrypto.broker import make_live_broker | |
| from qrypto.catalog import CATALOG, TIMEFRAMES, info, is_crypto, symbols_for, venue_for | |
| from qrypto.data import MarketData, synthetic, timeframe_seconds | |
| from qrypto.strategies import STRATEGY_REGISTRY, make_strategy | |
| from . import db, security | |
| from .manager import OFFLINE, BotManager | |
| from .tiers import ORDER, TIERS, at_least, tier | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s") | |
| log = logging.getLogger("qrypto.api") | |
| ADMIN_EMAILS = {e.strip().lower() for e in os.environ.get("QRYPTO_ADMIN_EMAILS", "").split(",") if e.strip()} | |
| SUPPORTED_TIMEFRAMES = TIMEFRAMES | |
| RISK_TEXT = ( | |
| "Trading cryptocurrency, stocks and precious metals involves substantial risk of loss. Qrypto Coin executes " | |
| "rules you choose; it does not predict prices and cannot guarantee profit. Past performance, including " | |
| "backtests, is not indicative of future results. Never trade money you cannot afford to lose. Qrypto Coin is " | |
| "software, not investment advice." | |
| ) | |
| manager = BotManager() | |
| # --- helpers ------------------------------------------------------------------- | |
| def err(msg: str, status: int = 400) -> JSONResponse: | |
| return JSONResponse({"error": msg}, status_code=status) | |
| async def body(request: Request) -> dict[str, Any]: | |
| try: | |
| return await request.json() | |
| except Exception: | |
| return {} | |
| def current_user(request: Request) -> dict | None: | |
| auth = request.headers.get("authorization", "") | |
| if not auth.lower().startswith("bearer "): | |
| return None | |
| token = auth[7:].strip() | |
| if token.startswith("tb_"): | |
| u = db.user_for_api_token(token) | |
| return u if u and tier(u["tier"])["api_access"] else None | |
| uid = security.read_token(token) | |
| return db.get_user(uid) if uid else None | |
| def authed(fn: Callable): | |
| async def wrapper(request: Request): | |
| user = current_user(request) | |
| if not user: | |
| return err("unauthorized", 401) | |
| request.state.user = user | |
| return await fn(request) | |
| return wrapper | |
| def public_user(u: dict) -> dict: | |
| t = tier(u["tier"]) | |
| return {"id": u["id"], "email": u["email"], "tier": u["tier"], "plan": t, "is_admin": bool(u["is_admin"]), | |
| "accepted_risk": bool(u["accepted_risk_at"]), "created_at": u["created_at"]} | |
| # --- public -------------------------------------------------------------------- | |
| async def health(request: Request): | |
| return JSONResponse({"ok": True, "version": __version__, "offline": OFFLINE, "running_bots": len(manager.runners), "time": time.time()}) | |
| async def plans(request: Request): | |
| return JSONResponse({"plans": [{"id": k, **TIERS[k]} for k in ORDER], "risk_disclosure": RISK_TEXT}) | |
| async def strategies(request: Request): | |
| """Public catalogue. If a valid token is sent, the instrument list is filtered to the caller's plan.""" | |
| out = [] | |
| for name, cls in STRATEGY_REGISTRY.items(): | |
| s = cls() | |
| out.append({**s.describe(), "warmup_candles": s.warmup()}) | |
| user = current_user(request) | |
| classes = tier(user["tier"])["asset_classes"] if user else ["crypto"] | |
| return JSONResponse({ | |
| "strategies": out, | |
| "asset_classes": classes, | |
| "instruments": symbols_for(classes), | |
| "all_instruments": symbols_for(["crypto", "stocks", "bonds", "metals"]), | |
| "timeframes": SUPPORTED_TIMEFRAMES, | |
| }) | |
| async def register(request: Request): | |
| b = await body(request) | |
| email, pw = str(b.get("email", "")).strip().lower(), str(b.get("password", "")) | |
| if "@" not in email or len(pw) < 8: | |
| return err("valid email and a password of 8+ characters required") | |
| if not b.get("accept_risk"): | |
| return err("you must accept the risk disclosure to create an account") | |
| if db.get_user_by_email(email): | |
| return err("email already registered", 409) | |
| is_admin = email in ADMIN_EMAILS or db.count_users() == 0 | |
| u = db.create_user(email, security.hash_password(pw), True, is_admin=is_admin) | |
| return JSONResponse({"token": security.issue_token(u["id"]), "user": public_user(u)}, status_code=201) | |
| async def login(request: Request): | |
| b = await body(request) | |
| u = db.get_user_by_email(str(b.get("email", ""))) | |
| if not u or not security.verify_password(str(b.get("password", "")), u["pw_hash"]): | |
| return err("invalid email or password", 401) | |
| return JSONResponse({"token": security.issue_token(u["id"]), "user": public_user(u)}) | |
| # --- account ------------------------------------------------------------------- | |
| async def me(request: Request): | |
| return JSONResponse({"user": public_user(request.state.user), "exchanges": db.list_exchange_keys(request.state.user["id"])}) | |
| async def upgrade(request: Request): | |
| """Called by the app after a store purchase. Verify the receipt with RevenueCat / Play / App Store | |
| before trusting it. Until a verifier is configured, only admins can set tiers.""" | |
| b = await body(request) | |
| user = request.state.user | |
| target = str(b.get("tier", "")).lower() | |
| if target not in ORDER: | |
| return err("unknown tier") | |
| verifier = os.environ.get("QRYPTO_RECEIPT_VERIFIER_URL") | |
| if user["is_admin"]: | |
| db.set_tier(user["id"], target) | |
| elif verifier: | |
| import requests | |
| r = requests.post(verifier, json={"user_id": user["id"], "tier": target, "receipt": b.get("receipt")}, timeout=15) | |
| if r.status_code != 200 or not r.json().get("valid"): | |
| return err("purchase could not be verified", 402) | |
| db.set_tier(user["id"], target) | |
| else: | |
| return err("purchases are not configured yet on this server", 501) | |
| return JSONResponse({"user": public_user(db.get_user(user["id"]))}) | |
| async def admin_set_tier(request: Request): | |
| if not request.state.user["is_admin"]: | |
| return err("admin only", 403) | |
| b = await body(request) | |
| target = db.get_user_by_email(str(b.get("email", ""))) | |
| if not target or b.get("tier") not in ORDER: | |
| return err("unknown user or tier") | |
| db.set_tier(target["id"], b["tier"]) | |
| return JSONResponse({"user": public_user(db.get_user(target["id"]))}) | |
| async def create_api_token(request: Request): | |
| user = request.state.user | |
| if not tier(user["tier"])["api_access"]: | |
| return err("API access requires the Enterprise plan", 403) | |
| b = await body(request) | |
| return JSONResponse({"token": db.create_api_token(user["id"], str(b.get("label", "default")))}, status_code=201) | |
| # --- exchange keys -------------------------------------------------------------- | |
| async def connect_exchange(request: Request): | |
| user = request.state.user | |
| t = tier(user["tier"]) | |
| if not t["live_trading"]: | |
| return err("live trading requires the Pro plan or higher", 403) | |
| b = await body(request) | |
| exchange = str(b.get("exchange", "")).lower() | |
| key, secret = str(b.get("api_key", "")).strip(), str(b.get("api_secret", "")).strip() | |
| if exchange not in t["venues"] or not key or not secret: | |
| return err(f"exchange must be one of {t['venues']}, with api_key and api_secret") | |
| existing = db.list_exchange_keys(user["id"]) | |
| if exchange not in [e["exchange"] for e in existing] and len(existing) >= t["max_exchange_accounts"]: | |
| return err(f"your plan allows {t['max_exchange_accounts']} connected account(s)", 403) | |
| if not OFFLINE: | |
| try: | |
| if exchange == "alpaca": | |
| broker = AlpacaBroker(key, secret, paper=bool(b.get("paper", True))) | |
| else: | |
| broker = make_live_broker(exchange, key, secret) | |
| await asyncio.get_event_loop().run_in_executor(None, broker.verify_permissions) | |
| except PermissionError as e: | |
| return err(str(e), 400) | |
| except Exception as e: | |
| return err(f"could not verify keys with {exchange}: {str(e)[:160]}", 400) | |
| # Alpaca has separate paper and live endpoints; remember which one these keys belong to. | |
| label = "paper" if (exchange == "alpaca" and b.get("paper", True)) else str(b.get("label", "live")) | |
| db.put_exchange_key(user["id"], exchange, security.encrypt(key), security.encrypt(secret), label) | |
| return JSONResponse({"exchanges": db.list_exchange_keys(user["id"])}, status_code=201) | |
| async def disconnect_exchange(request: Request): | |
| exchange = request.path_params["exchange"].lower() | |
| for bot in db.list_bots(request.state.user["id"]): | |
| if bot["mode"] == "live" and bot["exchange"] == exchange and bot["status"] == "running": | |
| return err("stop live bots on this exchange first", 409) | |
| db.delete_exchange_key(request.state.user["id"], exchange) | |
| return JSONResponse({"exchanges": db.list_exchange_keys(request.state.user["id"])}) | |
| # --- bots ------------------------------------------------------------------------ | |
| CLASS_LABEL = {"crypto": "Crypto", "stocks": "Stocks", "bonds": "Bond ETFs", "metals": "Precious metals"} | |
| CLASS_TIER = {"crypto": "Floor Pass", "stocks": "Pro Desk", "bonds": "Pro Desk", "metals": "Vault"} | |
| def _market_for(symbol: str, user_id: str): | |
| """Candle source for an instrument. Crypto is public; Alpaca data needs the user's own keys.""" | |
| venue = venue_for(symbol) | |
| if venue in ("binance", "kraken"): | |
| return MarketData(venue) | |
| key = db.get_exchange_key(user_id, "alpaca") | |
| if not key: | |
| return None | |
| return AlpacaMarket(security.decrypt(key["enc_key"]), security.decrypt(key["enc_secret"])) | |
| def _validate_bot(b: dict, user: dict) -> str | None: | |
| t = tier(user["tier"]) | |
| if b.get("strategy") not in STRATEGY_REGISTRY: | |
| return f"strategy must be one of {list(STRATEGY_REGISTRY)}" | |
| if b["strategy"] not in t["strategies"]: | |
| return f"the {b['strategy'].title()} trader requires the Pro Desk plan or higher" | |
| inst = info(str(b.get("symbol", ""))) | |
| if not inst: | |
| return "unknown instrument" | |
| if inst["cls"] not in t["asset_classes"]: | |
| return f"{CLASS_LABEL[inst['cls']]} requires the {CLASS_TIER[inst['cls']]} plan" | |
| if b.get("timeframe") not in SUPPORTED_TIMEFRAMES: | |
| return f"timeframe must be one of {SUPPORTED_TIMEFRAMES}" | |
| mode = b.get("mode", "paper") | |
| if mode not in ("paper", "live"): | |
| return "mode must be paper or live" | |
| if mode == "live": | |
| if not t["live_trading"]: | |
| return "live trading requires the Pro Desk plan or higher" | |
| venue = b.get("exchange") | |
| if venue not in inst["venues"]: | |
| return f"{b['symbol']} trades on {' or '.join(inst['venues'])}" | |
| if not db.get_exchange_key(user["id"], venue): | |
| return f"connect your {venue.title()} keys first" | |
| return None | |
| async def list_bots(request: Request): | |
| bots = [manager.snapshot(b) for b in db.list_bots(request.state.user["id"])] | |
| return JSONResponse({"bots": bots}) | |
| async def create_bot(request: Request): | |
| user = request.state.user | |
| b = await body(request) | |
| b.setdefault("mode", "paper") | |
| if e := _validate_bot(b, user): | |
| return err(e) | |
| if len(db.list_bots(user["id"])) >= tier(user["tier"])["max_bots"]: | |
| return err(f"your plan allows {tier(user['tier'])['max_bots']} bot(s). Delete one or upgrade.", 403) | |
| params = b.get("params") or {} | |
| if not isinstance(params, dict): | |
| return err("params must be an object") | |
| name = str(b.get("name") or f"{b['strategy'].title()} {b['symbol']}")[:40] | |
| bot = db.create_bot(user["id"], name, b["strategy"], params, b["symbol"], b["timeframe"], b["mode"], b.get("exchange")) | |
| return JSONResponse({"bot": manager.snapshot(bot)}, status_code=201) | |
| def _own_bot(request: Request) -> dict | None: | |
| bot = db.get_bot(request.path_params["bot_id"]) | |
| return bot if bot and bot["user_id"] == request.state.user["id"] else None | |
| async def get_bot(request: Request): | |
| bot = _own_bot(request) | |
| if not bot: | |
| return err("not found", 404) | |
| return JSONResponse({"bot": manager.snapshot(bot), "events": db.list_events(bot["id"], 50)}) | |
| async def start_bot(request: Request): | |
| bot = _own_bot(request) | |
| if not bot: | |
| return err("not found", 404) | |
| if e := _validate_bot(bot, request.state.user): | |
| return err(e, 403) | |
| running = [x for x in db.list_bots(request.state.user["id"]) if x["status"] == "running" and x["id"] != bot["id"]] | |
| if len(running) >= tier(request.state.user["tier"])["max_bots"]: | |
| return err("bot limit for your plan reached", 403) | |
| try: | |
| await asyncio.get_event_loop().run_in_executor(None, manager.start_bot, bot) | |
| except Exception as e: | |
| db.update_bot(bot["id"], status="error") | |
| return err(f"could not start: {str(e)[:200]}", 400) | |
| return JSONResponse({"bot": manager.snapshot(db.get_bot(bot["id"]))}) | |
| async def stop_bot(request: Request): | |
| bot = _own_bot(request) | |
| if not bot: | |
| return err("not found", 404) | |
| manager.stop_bot(bot["id"]) | |
| return JSONResponse({"bot": manager.snapshot(db.get_bot(bot["id"]))}) | |
| async def reset_bot(request: Request): | |
| """Clear a max-drawdown halt (manual acknowledgement) and, for paper bots, optionally reset the ledger.""" | |
| bot = _own_bot(request) | |
| if not bot: | |
| return err("not found", 404) | |
| b = await body(request) | |
| manager.reset_halt(bot["id"]) | |
| if b.get("reset_paper") and bot["mode"] == "paper" and bot["status"] != "running": | |
| db.update_bot(bot["id"], state={}) | |
| db.add_event(bot["id"], {"type": "reset", "paper": bool(b.get("reset_paper"))}) | |
| return JSONResponse({"bot": manager.snapshot(db.get_bot(bot["id"]))}) | |
| async def delete_bot(request: Request): | |
| bot = _own_bot(request) | |
| if not bot: | |
| return err("not found", 404) | |
| manager.stop_bot(bot["id"]) | |
| db.delete_bot(bot["id"]) | |
| return JSONResponse({"deleted": bot["id"]}) | |
| async def bot_events(request: Request): | |
| bot = _own_bot(request) | |
| if not bot: | |
| return err("not found", 404) | |
| return JSONResponse({"events": db.list_events(bot["id"], int(request.query_params.get("limit", 100)))}) | |
| async def portfolio(request: Request): | |
| bots = [manager.snapshot(b) for b in db.list_bots(request.state.user["id"])] | |
| paper_eq = sum((b.get("live") or {}).get("equity") or (b.get("quote_balance") or 0) for b in bots if b["mode"] == "paper") | |
| live_eq = sum((b.get("live") or {}).get("equity") or 0 for b in bots if b["mode"] == "live") | |
| realized = sum(t.get("pnl", 0) for b in bots for t in b.get("trades", []) if t["side"] == "sell") | |
| return JSONResponse({"paper_equity": round(paper_eq, 2), "live_equity": round(live_eq, 2), | |
| "realized_pnl": round(realized, 2), "running": sum(1 for b in bots if b["status"] == "running"), | |
| "bots": len(bots)}) | |
| # --- backtest ---------------------------------------------------------------------- | |
| async def backtest(request: Request): | |
| user = request.state.user | |
| b = await body(request) | |
| strategy = b.get("strategy") | |
| if strategy not in STRATEGY_REGISTRY: | |
| return err(f"strategy must be one of {list(STRATEGY_REGISTRY)}") | |
| if strategy not in tier(user["tier"])["strategies"]: | |
| return err(f"backtesting the {strategy.title()} bot requires the Pro plan", 403) | |
| symbol = str(b.get("symbol", "BTC/USDT")).upper() | |
| timeframe = b.get("timeframe", "1h") | |
| inst = info(symbol) | |
| if not inst or timeframe not in SUPPORTED_TIMEFRAMES: | |
| return err("unsupported instrument or timeframe") | |
| if inst["cls"] not in tier(user["tier"])["asset_classes"]: | |
| return err(f"{CLASS_LABEL[inst['cls']]} requires the {CLASS_TIER[inst['cls']]} plan", 403) | |
| initial = max(1.0, float(b.get("initial", 100))) | |
| limit = 1000 if tier(user["tier"])["live_trading"] else 500 | |
| try: | |
| params = {k: v for k, v in (b.get("params") or {}).items() if k in make_strategy(strategy).default_params} | |
| strat = make_strategy(strategy, **params) | |
| if OFFLINE: | |
| candles = synthetic(limit, seed=11, tf=timeframe) | |
| else: | |
| source = _market_for(symbol, user["id"]) | |
| if source is None: | |
| return err("connect your Alpaca keys to backtest stocks, bonds or metal ETFs", 403) | |
| candles = await asyncio.get_event_loop().run_in_executor(None, source.candles, symbol, timeframe, limit) | |
| if candles is None or len(candles) < 50: | |
| return err("not enough market history for that instrument and timeframe", 400) | |
| result = await asyncio.get_event_loop().run_in_executor(None, run_backtest, strat, candles, symbol, timeframe, initial) | |
| except Exception as e: | |
| return err(f"backtest failed: {str(e)[:200]}", 500) | |
| out = result.summary() | |
| step = max(1, len(result.equity_curve) // 200) | |
| out["equity_curve"] = result.equity_curve[::step] | |
| out["recent_trades"] = result.trade_log[-20:] | |
| out["disclaimer"] = "Backtests use historical data with modelled fees and slippage. They are not a forecast." | |
| return JSONResponse(out) | |
| # --- app -------------------------------------------------------------------------- | |
| async def lifespan(app): | |
| await manager.start() | |
| log.info("Qrypto API %s started (offline=%s)", __version__, OFFLINE) | |
| yield | |
| await manager.stop() | |
| routes = [ | |
| Route("/health", health), | |
| Route("/plans", plans), | |
| Route("/strategies", strategies), | |
| Route("/auth/register", register, methods=["POST"]), | |
| Route("/auth/login", login, methods=["POST"]), | |
| Route("/me", me), | |
| Route("/me/upgrade", upgrade, methods=["POST"]), | |
| Route("/me/api-token", create_api_token, methods=["POST"]), | |
| Route("/admin/set-tier", admin_set_tier, methods=["POST"]), | |
| Route("/exchange/keys", connect_exchange, methods=["POST"]), | |
| Route("/exchange/keys/{exchange}", disconnect_exchange, methods=["DELETE"]), | |
| Route("/bots", list_bots), | |
| Route("/bots", create_bot, methods=["POST"]), | |
| Route("/bots/{bot_id}", get_bot), | |
| Route("/bots/{bot_id}", delete_bot, methods=["DELETE"]), | |
| Route("/bots/{bot_id}/start", start_bot, methods=["POST"]), | |
| Route("/bots/{bot_id}/stop", stop_bot, methods=["POST"]), | |
| Route("/bots/{bot_id}/reset", reset_bot, methods=["POST"]), | |
| Route("/bots/{bot_id}/events", bot_events), | |
| Route("/portfolio", portfolio), | |
| Route("/backtest", backtest, methods=["POST"]), | |
| ] | |
| app = Starlette(routes=routes, lifespan=lifespan, | |
| middleware=[Middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])]) | |