Spaces:
Sleeping
Sleeping
File size: 14,910 Bytes
d96a847 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | 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()
|