Spaces:
Paused
Paused
Download python_engine/engine.py from mossoo/nexus-quant-bot: direct link, hf CLI and curl.
- Browser
- Download file 23 kB
-
https://huggingface.co/spaces/mossoo/nexus-quant-bot/resolve/main/python_engine/engine.py
- Command line
-
hf download hf://spaces/mossoo/nexus-quant-bot/python_engine/engine.py
-
curl -L -o engine.py https://huggingface.co/spaces/mossoo/nexus-quant-bot/resolve/main/python_engine/engine.py
23 kB
| """ | |
| High-Speed Python Trading Engine with Multi-Exchange Support & Universal Takashi Kotegawa Dip Hunter | |
| """ | |
| import asyncio | |
| import json | |
| import time | |
| import httpx | |
| import websockets | |
| from datetime import datetime | |
| from python_engine.strategies.bnf_strategy import TakashiKotegawaQuant | |
| from python_engine.strategies.other_strategies import SMCQuantStrategy, GridQuantStrategy | |
| from python_engine.exchange_manager import exchange_mgr | |
| from python_engine.multi_agent_council import agent_council | |
| class PythonTradingEngine: | |
| def __init__(self): | |
| self.symbol = "BTCUSDT" | |
| self.interval = "1m" | |
| self.active_strategy_name = "BNF_TAKASHI" | |
| self.is_running = True | |
| self.active_exchange = "binance" | |
| self.trading_mode = "PAPER" | |
| self.auto_hunt_all_tokens = True | |
| # Strategies | |
| self.bnf_strat = TakashiKotegawaQuant(ma_period=25, min_deviation_pct=2.8, volume_mult=1.6) | |
| self.smc_strat = SMCQuantStrategy() | |
| self.grid_strat = GridQuantStrategy() | |
| # Balances & Durable State | |
| import os | |
| self.state_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "trading_state.json") | |
| self.balance = 10000.0 | |
| self.equity = 10000.0 | |
| self.trade_history = [] | |
| self.positions = [] | |
| self.load_persisted_state() | |
| self.leverage = 10 | |
| self.risk_pct = 3.0 | |
| self.sl_pct = 1.5 | |
| self.tp_pct = 3.5 | |
| # Buffers | |
| self.candles = [] | |
| self.current_price = 0.0 | |
| self.live_price_map = {} | |
| self.orderbook = {"bids": [], "asks": []} | |
| self.market_tickers = [] | |
| self.bnf_opportunities = [] | |
| self.logs = [] | |
| self.subscribers = set() | |
| self.council_data = {} | |
| self.current_ws_conn = None | |
| self.rest_url = "https://api.binance.com/api/v3" | |
| self.ws_base = "wss://stream.binance.com:9443/ws" | |
| def load_persisted_state(self): | |
| try: | |
| import os | |
| if os.path.exists(self.state_file): | |
| with open(self.state_file, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| self.balance = float(data.get("balance", 10000.0)) | |
| self.equity = float(data.get("equity", 10000.0)) | |
| self.trade_history = data.get("trade_history", []) | |
| self.positions = data.get("positions", []) | |
| print(f"β [PERSISTENCE] Loaded {len(self.positions)} active positions and {len(self.trade_history)} closed trades from disk!") | |
| except Exception as e: | |
| print(f"β οΈ [PERSISTENCE] Load error: {e}") | |
| def save_persisted_state(self): | |
| try: | |
| with open(self.state_file, "w") as f: | |
| json.dump({ | |
| "balance": self.balance, | |
| "equity": self.equity, | |
| "trade_history": self.trade_history, | |
| "positions": self.positions | |
| }, f, indent=2) | |
| except Exception: | |
| pass | |
| def log(self, message, level="INFO"): | |
| entry = { | |
| "time": datetime.now().strftime("%H:%M:%S"), | |
| "level": level, | |
| "message": message | |
| } | |
| self.logs.insert(0, entry) | |
| if len(self.logs) > 80: | |
| self.logs.pop() | |
| print(f"[{entry['time']}][{level}] {message}") | |
| async def fetch_initial_candles(self, symbol=None, interval=None, limit=500): | |
| sym = symbol or self.symbol | |
| tf = interval or self.interval | |
| try: | |
| async with httpx.AsyncClient(timeout=8.0) as client: | |
| res = await client.get( | |
| f"{self.rest_url}/klines", | |
| params={"symbol": sym.upper(), "interval": tf, "limit": limit} | |
| ) | |
| if res.status_code == 200: | |
| raw = res.json() | |
| self.candles = [{ | |
| "time": int(c[0] / 1000), | |
| "open": float(c[1]), | |
| "high": float(c[2]), | |
| "low": float(c[3]), | |
| "close": float(c[4]), | |
| "volume": float(c[5]) | |
| } for c in raw] | |
| if self.candles: | |
| self.current_price = self.candles[-1]["close"] | |
| self.live_price_map[sym.upper()] = self.current_price | |
| self.log(f"Loaded {len(self.candles)} historical candles for {sym} ({tf})", "INFO") | |
| return self.candles | |
| except Exception as e: | |
| self.log(f"Candles fetch error for {sym}: {e}", "WARN") | |
| return [] | |
| async def fetch_top_tickers_and_bnf_scan(self): | |
| try: | |
| async with httpx.AsyncClient(timeout=6.0) as client: | |
| res = await client.get(f"{self.rest_url}/ticker/24hr") | |
| if res.status_code == 200: | |
| raw = res.json() | |
| usdt_pairs = [ | |
| t for t in raw | |
| if t["symbol"].endswith("USDT") and not t["symbol"].endswith("UPUSDT") and not t["symbol"].endswith("DOWNUSDT") | |
| ] | |
| usdt_pairs.sort(key=lambda x: float(x.get("quoteVolume", 0)), reverse=True) | |
| top_100 = usdt_pairs[:120] | |
| processed = [] | |
| for t in top_100: | |
| sym = t["symbol"] | |
| price = float(t.get("lastPrice", 0)) | |
| chg = float(t.get("priceChangePercent", 0)) | |
| vol = float(t.get("quoteVolume", 0)) | |
| high = float(t.get("highPrice", 0)) | |
| low = float(t.get("lowPrice", 0)) | |
| vwap = float(t.get("weightedAvgPrice", price)) | |
| disparity = round(((price - vwap) / vwap) * 100.0, 2) if vwap > 0 else 0.0 | |
| self.live_price_map[sym] = price | |
| status = "NORMAL" | |
| if disparity <= -3.0: | |
| status = "π BNF OVERSOLD DIP (BUY)" | |
| elif disparity >= 4.0: | |
| status = "OVERBOUGHT (SHORT)" | |
| processed.append({ | |
| "symbol": sym, | |
| "price": price, | |
| "change_24h": chg, | |
| "volume_24h": vol, | |
| "high_24h": high, | |
| "low_24h": low, | |
| "disparity_24h": disparity, | |
| "status": status | |
| }) | |
| self.market_tickers = processed | |
| bnf_dips = sorted([p for p in processed if p["disparity_24h"] <= -2.0], key=lambda x: x["disparity_24h"]) | |
| self.bnf_opportunities = bnf_dips[:15] | |
| # High-Frequency Multi-Token Auto-Hunter (Long on Dips & Short on Overextensions) | |
| if self.is_running and len(self.positions) < 5: | |
| for opp in self.bnf_opportunities[:5]: | |
| if len(self.positions) >= 5: | |
| break | |
| disp = opp.get("disparity_24h", 0.0) | |
| sym = opp["symbol"] | |
| px = opp["price"] | |
| existing = [p for p in self.positions if p["symbol"] == sym] | |
| if existing or px <= 0: | |
| continue | |
| # Takashi BNF Oversold Dip Trigger | |
| if disp <= -2.0: | |
| self.open_position( | |
| action="BUY", | |
| reason=f"π [Takashi BNF Hunter] {sym} Oversold Dip ({disp:+.2f}%)", | |
| confidence=int(min(98, 70 + abs(disp) * 7)), | |
| symbol_override=sym, | |
| price_override=px | |
| ) | |
| break | |
| except Exception: | |
| pass | |
| async def fetch_orderbook(self, symbol=None, limit=15): | |
| sym = symbol or self.symbol | |
| try: | |
| async with httpx.AsyncClient(timeout=3.5) as client: | |
| res = await client.get(f"{self.rest_url}/depth", params={"symbol": sym.upper(), "limit": limit}) | |
| if res.status_code == 200: | |
| data = res.json() | |
| self.orderbook = { | |
| "bids": [[float(b[0]), float(b[1])] for b in data.get("bids", [])], | |
| "asks": [[float(a[0]), float(a[1])] for a in data.get("asks", [])] | |
| } | |
| except Exception: | |
| pass | |
| async def run_market_stream(self): | |
| while True: | |
| active_sym = self.symbol.lower() | |
| active_int = self.interval | |
| try: | |
| ws_url = f"wss://stream.binance.com:9443/ws/{active_sym}@kline_{active_int}" | |
| self.log(f"Connecting to Binance Ultra-Fast Feed: {active_sym.upper()}@{active_int}", "INFO") | |
| async with websockets.connect(ws_url, ping_interval=20, ping_timeout=20) as ws: | |
| self.current_ws_conn = ws | |
| self.log(f"Connected to Binance Real-Time WebSocket for {active_sym.upper()}!", "SUCCESS") | |
| ticker_scan_counter = 0 | |
| while True: | |
| if self.symbol.lower() != active_sym or self.interval != active_int: | |
| break | |
| msg = await ws.recv() | |
| data = json.loads(msg) | |
| if "k" in data: | |
| kline = data["k"] | |
| candle = { | |
| "time": int(kline["t"] / 1000), | |
| "open": float(kline["o"]), | |
| "high": float(kline["h"]), | |
| "low": float(kline["l"]), | |
| "close": float(kline["c"]), | |
| "volume": float(kline["v"]) | |
| } | |
| self.current_price = candle["close"] | |
| self.live_price_map[self.symbol] = self.current_price | |
| if self.candles and self.candles[-1]["time"] == candle["time"]: | |
| self.candles[-1] = candle | |
| else: | |
| self.candles.append(candle) | |
| if len(self.candles) > 500: | |
| self.candles.pop(0) | |
| await self.process_tick() | |
| ticker_scan_counter += 1 | |
| if ticker_scan_counter % 3 == 0: | |
| asyncio.create_task(self.fetch_orderbook()) | |
| if ticker_scan_counter >= 10: | |
| ticker_scan_counter = 0 | |
| asyncio.create_task(self.fetch_top_tickers_and_bnf_scan()) | |
| await self.broadcast_state() | |
| except Exception as e: | |
| await asyncio.sleep(1.0) | |
| async def process_tick(self): | |
| if self.current_price <= 0: | |
| return | |
| # 1. Update Positions PnL in Real-Time & Check SL/TP | |
| unrealized_sum = 0.0 | |
| for pos in list(self.positions): | |
| sym = pos["symbol"] | |
| cur_p = self.live_price_map.get(sym, self.current_price if sym == self.symbol else pos["entry_price"]) | |
| entry = pos["entry_price"] | |
| size = pos["amount"] | |
| side = pos["side"] | |
| if side == "BUY": | |
| pnl = (cur_p - entry) * size | |
| pnl_pct = ((cur_p - entry) / entry) * 100.0 * pos["leverage"] | |
| else: | |
| pnl = (entry - cur_p) * size | |
| pnl_pct = ((entry - cur_p) / entry) * 100.0 * pos["leverage"] | |
| pos["mark_price"] = round(cur_p, 4 if cur_p < 1 else 2) | |
| pos["unrealized_pnl"] = round(pnl, 2) | |
| pos["pnl_pct"] = round(pnl_pct, 2) | |
| # Auto Stop Loss Trigger | |
| if (side == "BUY" and cur_p <= pos["stop_loss"]) or \ | |
| (side == "SELL" and cur_p >= pos["stop_loss"]): | |
| self.close_position(pos, "STOP_LOSS_PROTECTION_TRIGGERED", exit_p=cur_p) | |
| continue | |
| # Auto Take Profit / Mean Reversion Exit | |
| if (side == "BUY" and cur_p >= pos["take_profit"]) or \ | |
| (side == "SELL" and cur_p <= pos["take_profit"]): | |
| self.close_position(pos, "TAKE_PROFIT_TARGET_REACHED", exit_p=cur_p) | |
| continue | |
| unrealized_sum += pos["unrealized_pnl"] | |
| self.equity = round(self.balance + unrealized_sum, 2) | |
| # 2. Multi-Agent Council Live Debate & Auto-Execution on active chart token | |
| strat_res = self.evaluate_strategy() | |
| self.council_data = agent_council.analyze( | |
| symbol=self.symbol, | |
| current_price=self.current_price, | |
| candles=self.candles, | |
| disparity_pct=strat_res.get("disparity_pct", 0), | |
| rsi=strat_res.get("rsi", 50), | |
| volume_surge=strat_res.get("volume_surge", 1.0) | |
| ) | |
| if self.is_running and len(self.positions) < 3: | |
| consensus_action = self.council_data.get("consensus", "HOLD") | |
| confidence = self.council_data.get("confidence", 0) | |
| if consensus_action in ["BUY", "SELL"] and confidence >= 70: | |
| existing = [p for p in self.positions if p["symbol"] == self.symbol and p["side"] == consensus_action] | |
| if not existing: | |
| self.open_position( | |
| action=consensus_action, | |
| reason=f"π§ [Council Consensus] {consensus_action} on {self.symbol} ({confidence}% Conf)", | |
| confidence=confidence | |
| ) | |
| def evaluate_strategy(self): | |
| if len(self.candles) < 30: | |
| return { | |
| "action": "HOLD", "confidence": 0, "reason": "Gathering live 25-MA price stream...", | |
| "disparity_pct": 0, "sma25": 0, "rsi": 50, "volume_surge": 1.0 | |
| } | |
| if self.active_strategy_name == "BNF_TAKASHI": | |
| return self.bnf_strat.analyze(self.candles) | |
| elif self.active_strategy_name == "SMC_ICT": | |
| return self.smc_strat.analyze(self.candles) | |
| elif self.active_strategy_name == "GRID": | |
| return self.grid_strat.analyze(self.candles) | |
| else: | |
| return self.bnf_strat.analyze(self.candles) | |
| def open_position(self, action, reason, confidence, symbol_override=None, price_override=None): | |
| sym = (symbol_override or self.symbol).upper() | |
| price = price_override or self.current_price | |
| if price <= 0: | |
| return | |
| # 1. Guard against duplicate positions on the same token | |
| if any(p["symbol"] == sym for p in self.positions): | |
| return | |
| # 2. Guard against max concurrent positions (Max 5 open positions) | |
| if len(self.positions) >= 5: | |
| return | |
| side = action.upper() | |
| # Risk exactly 2% of current account equity per trade | |
| margin = max(10.0, round(self.equity * (self.risk_pct / 100.0), 2)) | |
| position_value = margin * self.leverage | |
| amount = position_value / price | |
| if side == "BUY": | |
| sl = price * (1 - (self.sl_pct / 100.0)) | |
| tp = price * (1 + (self.tp_pct / 100.0)) | |
| else: | |
| sl = price * (1 + (self.sl_pct / 100.0)) | |
| tp = price * (1 - (self.tp_pct / 100.0)) | |
| pos = { | |
| "id": f"pos_{int(time.time()*1000)}", | |
| "symbol": sym, | |
| "side": side, | |
| "entry_price": round(price, 4 if price < 1 else 2), | |
| "mark_price": round(price, 4 if price < 1 else 2), | |
| "amount": amount, | |
| "margin": margin, | |
| "leverage": self.leverage, | |
| "stop_loss": round(sl, 4 if price < 1 else 2), | |
| "take_profit": round(tp, 4 if price < 1 else 2), | |
| "unrealized_pnl": 0.0, | |
| "pnl_pct": 0.0, | |
| "opened_at": datetime.now().strftime("%H:%M:%S"), | |
| "confidence": confidence, | |
| "reason": reason | |
| } | |
| self.positions.append(pos) | |
| self.save_persisted_state() | |
| self.log(f"β‘ [QUANT EXEC] {side} {sym} @ ${price:,.2f} | Margin: ${margin:,.2f} ({self.leverage}x) | SL: ${sl:,.2f} | TP: ${tp:,.2f}", "SUCCESS") | |
| if self.trading_mode == "LIVE": | |
| asyncio.create_task( | |
| exchange_mgr.create_order( | |
| exchange_id=self.active_exchange, | |
| symbol=sym, | |
| order_type="market", | |
| side=side.lower(), | |
| amount=amount | |
| ) | |
| ) | |
| def close_position(self, pos, reason_text, exit_p=None): | |
| if pos in self.positions: | |
| self.positions.remove(pos) | |
| actual_exit = exit_p or self.live_price_map.get(pos["symbol"], pos["entry_price"]) | |
| # Compute final realized PnL | |
| if pos["side"] == "BUY": | |
| realized_pnl = round((actual_exit - pos["entry_price"]) * pos["amount"], 2) | |
| else: | |
| realized_pnl = round((pos["entry_price"] - actual_exit) * pos["amount"], 2) | |
| self.balance = round(self.balance + realized_pnl, 2) | |
| remaining_unrealized = sum(p.get("unrealized_pnl", 0.0) for p in self.positions) | |
| self.equity = round(self.balance + remaining_unrealized, 2) | |
| trade = dict(pos) | |
| trade["closed_at"] = datetime.now().strftime("%H:%M:%S") | |
| trade["exit_price"] = round(actual_exit, 4 if actual_exit < 1 else 2) | |
| trade["realized_pnl"] = realized_pnl | |
| trade["close_reason"] = reason_text | |
| self.trade_history.insert(0, trade) | |
| self.save_persisted_state() | |
| pnl_tag = f"+${realized_pnl}" if realized_pnl >= 0 else f"-${abs(realized_pnl)}" | |
| self.log(f"π― [AUTO-CLOSED] {pos['side']} on {pos['symbol']} | PnL: {pnl_tag} ({pos['pnl_pct']}%) | Reason: {reason_text}", "SUCCESS" if realized_pnl >= 0 else "WARN") | |
| async def broadcast_state(self, force=False): | |
| if not self.subscribers: | |
| return | |
| # Smart Throttling: Max 2 broadcasts per second to prevent network choking | |
| now = time.time() | |
| if not force and hasattr(self, '_last_broadcast_time') and (now - self._last_broadcast_time < 0.5): | |
| return | |
| self._last_broadcast_time = now | |
| state = self.get_full_state() | |
| msg = json.dumps({"event": "STATE_UPDATE", "data": state}) | |
| dead = set() | |
| for ws in list(self.subscribers): | |
| try: | |
| await ws.send_text(msg) | |
| except Exception: | |
| dead.add(ws) | |
| self.subscribers.difference_update(dead) | |
| def get_full_state(self): | |
| wins = [t for t in self.trade_history if t.get("realized_pnl", 0) > 0] | |
| win_rate = (len(wins) / len(self.trade_history) * 100.0) if self.trade_history else 0.0 | |
| total_pnl = self.equity - 10000.0 | |
| roi = (total_pnl / 10000.0) * 100.0 | |
| current_signal = self.evaluate_strategy() | |
| # Futures Margin Accounting | |
| used_margin = sum(p.get("margin", 0.0) for p in self.positions) | |
| free_balance = max(0.0, self.balance - used_margin) | |
| return { | |
| "symbol": self.symbol, | |
| "interval": self.interval, | |
| "price": self.current_price, | |
| "is_running": self.is_running, | |
| "strategy": self.active_strategy_name, | |
| "trading_mode": self.trading_mode, | |
| "active_exchange": self.active_exchange, | |
| "balance": round(self.balance, 2), | |
| "free_balance": round(free_balance, 2), | |
| "used_margin": round(used_margin, 2), | |
| "equity": round(self.equity, 2), | |
| "total_pnl": round(total_pnl, 2), | |
| "roi": round(roi, 2), | |
| "win_rate": round(win_rate, 1), | |
| "total_trades": len(self.trade_history), | |
| "leverage": self.leverage, | |
| "risk_pct": self.risk_pct, | |
| "sl_pct": self.sl_pct, | |
| "tp_pct": self.tp_pct, | |
| "signal": current_signal, | |
| "council": self.council_data, | |
| "positions": self.positions, | |
| "history": self.trade_history[:20], | |
| "candles": self.candles[-100:] if self.candles else [], | |
| "orderbook": self.orderbook, | |
| "market_tickers": self.market_tickers[:80], | |
| "bnf_opportunities": self.bnf_opportunities, | |
| "logs": self.logs[:30] | |
| } | |
| async def change_symbol(self, new_symbol, new_interval=None): | |
| target_sym = new_symbol.upper() | |
| target_tf = new_interval or self.interval | |
| self.symbol = target_sym | |
| self.interval = target_tf | |
| if target_sym in self.live_price_map and self.live_price_map[target_sym] > 0: | |
| self.current_price = self.live_price_map[target_sym] | |
| self.log(f"β‘ Instant switch to {target_sym} ({target_tf})", "INFO") | |
| # Immediate state push (0ms delay) | |
| await self.broadcast_state(force=True) | |
| # Concurrently fetch candles and orderbook in background without blocking | |
| async def _load_market_data(): | |
| try: | |
| await asyncio.gather( | |
| self.fetch_initial_candles(target_sym, target_tf), | |
| self.fetch_orderbook(target_sym), | |
| return_exceptions=True | |
| ) | |
| if self.symbol == target_sym: | |
| await self.broadcast_state(force=True) | |
| except Exception as e: | |
| self.log(f"Market fetch error for {target_sym}: {e}", "WARN") | |
| asyncio.create_task(_load_market_data()) | |
| async def run(self): | |
| self.log(f"π [INIT] Booting Takashi Kotegawa Universal Engine for {self.symbol}...", "INFO") | |
| await self.fetch_initial_candles() | |
| await self.fetch_top_tickers_and_bnf_scan() | |
| await self.fetch_orderbook() | |
| await self.run_market_stream() | |
| bot_engine = PythonTradingEngine() | |
| engine = bot_engine |