Spaces:
Paused
Paused
Download python_engine/server.py from mossoo/nexus-quant-bot: direct link, hf CLI and curl.
- Browser
- Download file 5.93 kB
-
https://huggingface.co/spaces/mossoo/nexus-quant-bot/resolve/main/python_engine/server.py
- Command line
-
hf download hf://spaces/mossoo/nexus-quant-bot/python_engine/server.py
-
curl -L -o server.py https://huggingface.co/spaces/mossoo/nexus-quant-bot/resolve/main/python_engine/server.py
5.93 kB
| import asyncio | |
| import os | |
| import json | |
| from contextlib import asynccontextmanager | |
| from fastapi import FastAPI, WebSocket, WebSocketDisconnect | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import FileResponse, JSONResponse, Response | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from python_engine.engine import bot_engine | |
| from python_engine.exchange_manager import exchange_mgr | |
| async def lifespan(app: FastAPI): | |
| task = asyncio.create_task(bot_engine.run()) | |
| yield | |
| bot_engine.is_running = False | |
| task.cancel() | |
| app = FastAPI(title="NEXUS QUANT PRO | Multi-Exchange Takashi Kotegawa Terminal", lifespan=lifespan) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| async def favicon(): | |
| return Response(status_code=204) | |
| async def get_state(): | |
| return { | |
| "status": "online", | |
| "state": bot_engine.get_full_state(), | |
| "supported_exchanges": exchange_mgr.get_supported_exchanges(), | |
| "configured_exchanges": exchange_mgr.get_configured_exchanges(), | |
| "strategies": ["BNF_TAKASHI", "SMC_ICT", "GRID"] | |
| } | |
| async def bot_control(payload: dict): | |
| action = payload.get("action") | |
| if action == "start": | |
| bot_engine.is_running = True | |
| return {"success": True, "message": "Python Quant Engine Started"} | |
| elif action == "stop": | |
| bot_engine.is_running = False | |
| return {"success": True, "message": "Python Quant Engine Paused"} | |
| elif action == "close_single": | |
| pos_id = payload.get("pos_id") | |
| target_pos = next((p for p in bot_engine.positions if p.get("id") == pos_id), None) | |
| if target_pos: | |
| bot_engine.close_position(target_pos, "MANUAL_SINGLE_CLOSE") | |
| return {"success": True, "message": f"Position {pos_id} closed successfully"} | |
| return {"error": "Position not found"} | |
| elif action == "emergency_close_all": | |
| for pos in list(bot_engine.positions): | |
| bot_engine.close_position(pos, "EMERGENCY_MANUAL_PANIC_CLOSE") | |
| return {"success": True, "message": "All positions liquidated instantly"} | |
| elif action == "reset": | |
| bot_engine.positions.clear() | |
| bot_engine.trade_history.clear() | |
| bot_engine.balance = 10000.0 | |
| bot_engine.equity = 10000.0 | |
| bot_engine.token_prices.clear() | |
| bot_engine.is_running = True | |
| bot_engine.log("System Reset: All trades cleared. Starting fresh with $10,000.00!", "SUCCESS") | |
| await bot_engine.broadcast_state() | |
| return {"success": True, "message": "Account reset to pristine $10,000"} | |
| return {"error": "Invalid action"} | |
| async def update_config(payload: dict): | |
| if "symbol" in payload and payload["symbol"].upper() != bot_engine.symbol: | |
| await bot_engine.change_symbol(payload["symbol"].upper(), payload.get("interval")) | |
| if "strategy" in payload: | |
| bot_engine.active_strategy_name = payload["strategy"] | |
| if "leverage" in payload: | |
| bot_engine.leverage = int(payload["leverage"]) | |
| if "risk_pct" in payload: | |
| bot_engine.risk_pct = float(payload["risk_pct"]) | |
| if "sl_pct" in payload: | |
| bot_engine.sl_pct = float(payload["sl_pct"]) | |
| if "tp_pct" in payload: | |
| bot_engine.tp_pct = float(payload["tp_pct"]) | |
| if "trading_mode" in payload: | |
| bot_engine.trading_mode = payload["trading_mode"].upper() | |
| if "exchange" in payload: | |
| bot_engine.active_exchange = payload["exchange"].lower() | |
| await bot_engine.broadcast_state() | |
| return {"success": True, "state": bot_engine.get_full_state()} | |
| async def connect_exchange_api(payload: dict): | |
| """Verify and connect Real Exchange API Keys (Binance, Bybit, OKX, etc.)""" | |
| exchange_id = payload.get("exchange", "binance").lower() | |
| api_key = payload.get("api_key", "") | |
| secret = payload.get("secret", "") | |
| passphrase = payload.get("passphrase", "") | |
| sandbox = bool(payload.get("sandbox", False)) | |
| res = await exchange_mgr.configure_exchange(exchange_id, api_key, secret, passphrase, sandbox) | |
| if res.get("status") == "CONNECTED": | |
| bot_engine.active_exchange = exchange_id | |
| bot_engine.log(f"Verified & Connected API for {exchange_id.upper()}! Balance: {res.get('balance')}", "SUCCESS") | |
| return {"success": True, "data": res} | |
| else: | |
| return JSONResponse(status_code=400, content={"success": False, "error": res.get("message")}) | |
| async def manual_trade(payload: dict): | |
| side = payload.get("side", "BUY").upper() | |
| if bot_engine.current_price <= 0: | |
| return {"error": "Waiting for live market price tick"} | |
| bot_engine.open_position( | |
| action=side, | |
| reason="Commander Manual Execution (Pro Terminal)", | |
| confidence=99 | |
| ) | |
| return {"success": True, "positions": bot_engine.positions} | |
| async def websocket_endpoint(websocket: WebSocket): | |
| await websocket.accept() | |
| bot_engine.subscribers.add(websocket) | |
| # Send initial state immediately | |
| await websocket.send_text(json.dumps({ | |
| "event": "STATE_UPDATE", | |
| "data": bot_engine.get_full_state() | |
| })) | |
| try: | |
| while True: | |
| data = await websocket.receive_text() | |
| # Handle incoming client commands if any | |
| try: | |
| msg = json.loads(data) | |
| if msg.get("action") == "CHANGE_SYMBOL": | |
| await bot_engine.change_symbol(msg.get("symbol"), msg.get("interval")) | |
| except Exception: | |
| pass | |
| except WebSocketDisconnect: | |
| bot_engine.subscribers.discard(websocket) | |
| app.mount("/", StaticFiles(directory="public", html=True), name="public") | |