import time import os import sys import logging import pandas as pd import numpy as np import yfinance as yf import ccxt import requests from dotenv import load_dotenv # Internal Imports from core import Portfolio, AssetAllocation from forces import LongForce, ShortForce, CashForce from brain_mpc import MPCBoltzmannBrain from execution_mpc import MPCExecutionAgent from perception_tuned import RegimeClassifierTuned # Setup Logging logging.basicConfig( level=logging.INFO, format='%(asctime)s | %(levelname)s | %(message)s', handlers=[ logging.FileHandler("live_runner.log"), logging.StreamHandler(sys.stdout) ] ) logger = logging.getLogger("LiveRunner") # Load Env load_dotenv() IS_LIVE = os.getenv("IS_LIVE_TRADING", "false").lower() == "true" EXCHANGE_ID = os.getenv("EXCHANGE_ID", "alpaca").lower() # Ticker Mapping Configuration SYMBOLS_MAP = { "alpaca": {"BTC": "BTC/USD", "ETH": "ETH/USD"}, "paper": {"BTC": "BTC-USD", "ETH": "ETH-USD"} } # Determine the set of symbols to monitor CURRENT_MAP = SYMBOLS_MAP.get(EXCHANGE_ID, SYMBOLS_MAP["alpaca"]) SYMBOL_BTC = CURRENT_MAP.get("BTC") SYMBOL_ETH = CURRENT_MAP.get("ETH") SYMBOL_YAHOO = "BTC-USD" TIMEFRAME = "1h" class RealTimeExecutor(MPCExecutionAgent): def __init__(self, portfolio, exchange=None, is_live=False): super().__init__(portfolio, transaction_cost_rate=0.001) self.exchange = exchange self.is_live = is_live def _perform_trade(self, forces, target_weights, prices): """ Executes Real trades if IS_LIVE=True, else Paper. """ equity = self.portfolio.total_value logger.info(f"Rebalancing Equity: ${equity:.2f}") # 1. Calculate Target Asset Allocations target_asset_alloc = {} for i, force in enumerate(forces): force_w = target_weights[i] for asset, asset_w in force.allocation.weights.items(): if asset not in target_asset_alloc: target_asset_alloc[asset] = 0.0 target_asset_alloc[asset] += (force_w * asset_w) # 2. Compare and Execute per Asset for asset, target_w in target_asset_alloc.items(): if asset in ["USDT", "USD", "CASH"]: continue p = prices.get(asset) if not p: continue current_qty = self.portfolio.positions.get(asset, 0.0) target_usd = target_w * equity current_usd = current_qty * p diff_usd = target_usd - current_usd if abs(diff_usd) < 20.0: logger.info(f"Target Delta for {asset}: ${diff_usd:.2f} below threshold. Holding.") continue amount = abs(diff_usd) / p side = "buy" if diff_usd > 0 else "sell" logger.info(f"PLAN: {side.upper()} {amount:.6f} {asset} (${diff_usd:.2f})") # Resolve Symbol symbol = CURRENT_MAP.get(asset) if not symbol: continue if self.is_live and self.exchange: logger.info(f"🚀 LIVE EXECUTING {asset} on {self.exchange.id}...") try: target_symbol = symbol if side == "buy": bal = self.exchange.fetch_balance() # Use 'free' dictionary for purchasing power currency = 'USD' if 'USD' in bal['free'] else 'USDT' free_cash = bal['free'].get(currency, 0.0) if (amount * p) > free_cash: logger.info(f"âš ī¸ Capping BUY to available cash: ${free_cash:.2f}") amount = (free_cash * 0.95) / p if amount > 0.0001: logger.info(f"🛒 Sending MARKET BUY for {amount:.6f} {asset}") order = self.exchange.create_market_buy_order(target_symbol, amount) logger.info(f"✅ {asset} BUY ORDER FILLED: {order['id']}") else: logger.warning(f"đŸšĢ {asset} Buy amount {amount} too small.") continue else: logger.info(f"🛒 Sending MARKET SELL for {amount:.6f} {asset}") order = self.exchange.create_market_sell_order(symbol, amount) logger.info(f"✅ {asset} SELL ORDER FILLED: {order['id']}") except Exception as e: logger.error(f"❌ {asset} ORDER FAILED: {e}") else: # Paper Trade fee = abs(diff_usd) * self.tc_rate self.portfolio.cash -= fee if side == "buy": self.portfolio.cash -= abs(diff_usd) self.portfolio.positions[asset] = current_qty + amount else: self.portfolio.cash += abs(diff_usd) self.portfolio.positions[asset] = current_qty - amount logger.info(f"✅ PAPER EXECUTED: {side.upper()} {asset} @ ${p:.2f}") def fetch_ohlcv_ccxt(exchange, symbol, timeframe="1h", limit=60): try: # ccxt.fetch_ohlcv returns [timestamp, open, high, low, close, volume] ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit) df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) # CCXT timestamp is in milliseconds df.set_index(pd.to_datetime(df['timestamp'], unit='ms'), inplace=True) return df except Exception as e: logger.error(f"CCXT OHLCV Error: {e}") return pd.DataFrame() def fetch_data_yahoo(symbol, interval="1h", limit=60): try: df = yf.download(tickers=symbol, period="5d", interval=interval, progress=False) if df.empty: return pd.DataFrame() if isinstance(df.columns, pd.MultiIndex): df.columns = df.columns.get_level_values(0) df.columns = [c.lower() for c in df.columns] return df.tail(limit) except: return pd.DataFrame() def get_live_price_ccxt(exchange, symbol): try: # ticker = exchange.fetch_ticker(symbol) # return ticker['last'] # Alpaca/Oanda fetch_ticker works well t = exchange.fetch_ticker(symbol) return t['last'] except Exception as e: logger.error(f"Price Error ({exchange.id}): {e}") return None def get_live_price_yahoo(symbol): try: data = yf.Ticker(symbol) return data.fast_info['last_price'] except: return None def sync_portfolio_ccxt(exchange, portfolio): try: bal = exchange.fetch_balance() # CCXT unifies this nicely usually to 'free' / 'used' / 'total' # Alpaca: 'USD' or 'USDT'? Usually 'USD' for stocks/crypto-on-alpaca # Oanda: 'USD' currency = 'USD' if 'USD' in bal else 'USDT' # Use 'total' (free + used) so we don't think we are broke if cash is locked in orders cash = bal.get(currency, {}).get('total', 0.0) portfolio.cash = cash # Positions: # fetch_balance often has 'total' for assets. # e.g. bal['BTC']['total'] btc_holding = bal.get('BTC', {}).get('total', 0.0) portfolio.positions["BTC"] = btc_holding return True except Exception as e: logger.error(f"Sync Error: {e}") return False def run_live(): logger.info("--- 🚀 STARTING LIVE AGENT ---") logger.info(f"Mode: {'LIVE TRADING' if IS_LIVE else 'PAPER TRADING'} | Exchange: {EXCHANGE_ID}") exchange = None if IS_LIVE: try: if EXCHANGE_ID == 'oanda': exchange = ccxt.oanda({ 'apiKey': os.getenv("OANDA_API_KEY"), 'account_id': os.getenv("OANDA_ACCOUNT_ID"), 'environment': 'practice' if 'practice' in os.getenv("OANDA_API_KEY", "") else 'live' }) elif EXCHANGE_ID == 'alpaca': # Simplified: Use CCXT's built-in sandbox mode exchange = ccxt.alpaca({ 'apiKey': os.getenv("ALPACA_API_KEY"), 'secret': os.getenv("ALPACA_SECRET"), 'options': {'defaultType': 'spot'} }) is_paper = os.getenv("ALPACA_API_KEY", "").startswith("PK") if is_paper: logger.info("â„šī¸ Detected Alpaca Paper Key (PK...), enabling Sandbox Mode.") exchange.set_sandbox_mode(True) else: # specific binance or others if needed exchange_class = getattr(ccxt, EXCHANGE_ID) exchange = exchange_class({ 'apiKey': os.getenv(f"{EXCHANGE_ID.upper()}_API_KEY"), 'secret': os.getenv(f"{EXCHANGE_ID.upper()}_SECRET") }) exchange.load_markets() logger.info(f"✅ Connected to {EXCHANGE_ID}") except Exception as e: logger.critical(f"Failed to connect to {EXCHANGE_ID}: {e}") return # 1. Initialize Strategies from forces import LongForce, ShortForce, CashForce, ETHForce brain = MPCBoltzmannBrain(temperature=0.5, cash_bear_energy=1.0) classifier = RegimeClassifierTuned(fast_window=10, slow_window=50) forces = [LongForce(), ShortForce(), CashForce(), ETHForce()] portfolio = Portfolio(cash=100000.0) if IS_LIVE: portfolio.cash = 0.0 # Will sync from exchange executor = RealTimeExecutor(portfolio, exchange=exchange, is_live=IS_LIVE) # Helpers for Heartbeat last_context = {"tags": set(), "metrics": {}} def get_pv_callback(): return portfolio.total_value def get_conn_callback(): if IS_LIVE: return "Connected" if exchange else "Disconnected" return "Paper (OK)" def get_tags_callback(): return last_context brain.start_heartbeat( get_portfolio_value=get_pv_callback, get_connectivity_status=get_conn_callback, get_current_tags=get_tags_callback ) def get_remote_allocation(query, forces, context, df_history): """ Calls the Smart Brain Microservice (FastAPI + Gemini + Sector Pulse). """ try: # 1. Prepare Returns History returns = df_history['close'].pct_change().fillna(0.0).tolist() force_payload = [] for f in forces: # Mapping local force logic to API schema hist = returns if "short" in f.tags: hist = [-r for r in returns] elif "safe" in f.tags or "stable" in f.tags: hist = [0.0] * len(returns) force_payload.append({ "id": f.name.lower(), "name": f.name, "tags": list(f.tags), "returns_history": hist }) # 2. Call Service url = "http://localhost:8001/allocate/boltzmann" payload = { "query": query, "forces": force_payload, "regime_tags": list(context.get('tags', [])) } logger.info(f"📡 Requesting Smart Allocation for query: '{query}'") resp = requests.post(url, json=payload, timeout=10) resp.raise_for_status() data = resp.json() return np.array(data["weights"]), data.get("applied_context", []) except Exception as e: logger.error(f"âš ī¸ Remote Brain failed: {e}. Falling back to local brain.") return None, None while True: try: # A. Fetch Data prices = {"USDT": 1.0, "USD": 1.0} if exchange: # Multi-Asset Pricing prices["BTC"] = get_live_price_ccxt(exchange, SYMBOL_BTC) prices["ETH"] = get_live_price_ccxt(exchange, SYMBOL_ETH) df_history = fetch_ohlcv_ccxt(exchange, SYMBOL_BTC, TIMEFRAME, limit=60) else: # Public Yahoo Path (Paper/Backup) prices["BTC"] = get_live_price_yahoo(SYMBOL_YAHOO) prices["ETH"] = get_live_price_yahoo("ETH-USD") df_history = fetch_data_yahoo(SYMBOL_YAHOO, TIMEFRAME, limit=60) current_price = prices["BTC"] # legacy reference for logging if df_history.empty: logger.warning("Data fetch failed. Retrying...") time.sleep(10) continue # B. Sync if IS_LIVE: sync_portfolio_ccxt(exchange, portfolio) portfolio.update(prices) else: portfolio.update(prices) # C. Perceive context = classifier.get_current_regime(df_history) last_context.update(context) ctx_tags = context['tags'] metrics = context['metrics'] ema_delta = metrics.get('ema_delta', 0.0) logger.info(f"🧠 PERCEPTION: {ctx_tags} | Price: ${current_price:,.2f} | EMA Delta: {ema_delta*100:.2f}%") # D. Brain (Hybrid: Remote with Local Fallback) query = os.getenv("AGENT_INTENT", "Optimize for steady growth and risk management") weights, remote_tags = get_remote_allocation(query, forces, context, df_history) if weights is not None: logger.info(f"✨ SMART BRAIN ACTIVE: {remote_tags}") # We need energies for the rebalance function, but weights are primary # We can derive energies from weights if needed, or just pass weights energies = -np.log(weights + 1e-9) # Inverse of Boltzmann for logging else: # Local Fallback energies = brain.calculate_energies(forces, context=context) weights = brain.allocate_weights(energies, context=context) for f, w, e in zip(forces, weights, energies): logger.info(f" > Force {f.name}: {w*100:.1f}% (E={e:.1f})") # E. Execute executor.execute_optimized_rebalance(forces, weights, energies, prices) sleep_time = 300 if IS_LIVE else 120 logger.info(f"Sleeping {sleep_time}s...") time.sleep(sleep_time) except KeyboardInterrupt: brain.stop_heartbeat() break except Exception as e: logger.error(f"LOOP ERROR: {e}") time.sleep(60) if __name__ == "__main__": run_live()