""" Paper trading system for RemizovNet. Uses best strategy: ATR stop + Trailing stop. Maintains persistent state (model, positions, equity) between runs. Modes: python paper_trader.py # daily update (signals + stops via yfinance) python paper_trader.py --init # initialize: train models, create state python paper_trader.py --status # show current positions and equity python paper_trader.py --history # show trade history python paper_trader.py --monitor # realtime stop monitor via Binance (ccxt) python paper_trader.py --monitor --interval 240 # check every 4h (default) State file: paper_state.json Trade log: logs/paper_trades.jsonl (append-only) """ from __future__ import annotations import argparse import json import os import pickle import sys import time import warnings from datetime import date, datetime, timedelta from pathlib import Path import ccxt import numpy as np import torch import torch.nn as nn from data_v2 import fetch_asset from final_backtest import ( COMMISSION, FINETUNE_EPOCHS, LR, RISK_PER_TRADE, SHIFT, WINDOW_SIZE, discretize_astro, passes_astro_filter, ) from models import EnhancedRemizovNet from retest_all import curated_astro_features warnings.filterwarnings("ignore") # -- Config ------------------------------------------------------------------ N_STEPS = 20 TOTAL_TIME = 0.5 EPOCHS = 200 STATE_FILE = Path(__file__).parent / "paper_state.json" MODEL_DIR = Path(__file__).parent / "paper_models" LOG_DIR = Path(__file__).parent / "logs" TRADE_LOG = LOG_DIR / "paper_trades.jsonl" # Yahoo Finance ticker -> Binance symbol mapping BINANCE_SYMBOLS = { "BTC-USD": "BTC/USDT", "ETH-USD": "ETH/USDT", "SOL-USD": "SOL/USDT", "BNB-USD": "BNB/USDT", } # Best strategy per asset from A/B testing ASSET_CONFIGS = { "BTC-USD": { "K": 2, "corr_thresh": 0.7, "astro_filter": "btc", "adaptive_stop": True, "trailing_stop": True, }, "ETH-USD": { "K": 2, "corr_thresh": 0.5, "astro_filter": "eth", "adaptive_stop": True, "trailing_stop": True, }, "SOL-USD": { "K": 3, "corr_thresh": 0.5, "astro_filter": None, "adaptive_stop": True, "trailing_stop": True, }, "BNB-USD": { "K": 3, "corr_thresh": 0.5, "astro_filter": "bnb", "adaptive_stop": True, "trailing_stop": True, }, } INITIAL_EQUITY_PER_ASSET = 10000.0 # Circuit breaker thresholds CB_ATR_RATIO = 3.0 # ATR14 / ATR50 > 3 → pause trading CB_ATR_RESET = 2.0 # ATR14 / ATR50 < 2 → resume trading (hysteresis) CB_MAX_DD = 0.20 # 20% drawdown from peak → pause CB_DD_RESET = 0.10 # drawdown recovers to 10% → resume CB_MAX_POS_PCT = 0.30 # max 30% of equity in single position # -- Model ------------------------------------------------------------------- def create_model(): return EnhancedRemizovNet( grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME, dx=1.0 / WINDOW_SIZE, use_sde=True, ) def train_model(model, windows, targets, epochs): g = torch.tensor(windows, dtype=torch.float32) y = torch.tensor(targets, dtype=torch.float32) opt = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4) crit = nn.MSELoss() bs = min(64, len(windows)) for _ in range(epochs): model.train() perm = torch.randperm(len(g)) for i in range(0, len(g), bs): idx = perm[i:i + bs] opt.zero_grad() loss = crit(model(g[idx], stochastic=True), y[idx]) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() def predict(model, norm_input): model.eval() with torch.no_grad(): inp = torch.tensor(norm_input, dtype=torch.float32).unsqueeze(0) return model(inp, stochastic=False).squeeze(0).numpy() # -- Data helpers ------------------------------------------------------------ def prepare_windows(prices): """Create normalized windows from price array.""" data = [] n = len(prices) for t in range(WINDOW_SIZE, n - SHIFT, SHIFT): w = prices[t - WINDOW_SIZE:t].copy() future = prices[t:t + SHIFT].copy() if len(future) < SHIFT: continue mu, std = w.mean(), w.std() if std < 1e-10: continue s = prices[t - WINDOW_SIZE + SHIFT:t + SHIFT].copy() data.append({ "norm_input": (w - mu) / std, "norm_target": (s - mu) / std, "mu": float(mu), "std": float(std), "future_prices": future.tolist(), "price_idx": t, }) return data def compute_atr(prices, idx, period=14): """ATR from close-only data.""" if idx < period + 1: return prices[idx] * 0.02 trs = [abs(prices[i] - prices[i - 1]) for i in range(idx - period, idx)] return np.mean(trs) if trs else prices[idx] * 0.02 def check_circuit_breaker(prices, asset_state): """Check if circuit breaker should be active. Returns (is_active, reason, details) tuple. Two triggers: 1. ATR spike: ATR14 / ATR50 > CB_ATR_RATIO → volatility crisis 2. Drawdown: equity / peak_equity < (1 - CB_MAX_DD) → capital protection Hysteresis: once active, requires lower threshold to deactivate. """ cb = asset_state.get("circuit_breaker", {}) was_active = cb.get("active", False) # 1. ATR ratio check n = len(prices) atr14 = compute_atr(prices, n - 1, period=14) atr50 = compute_atr(prices, n - 1, period=50) atr_ratio = atr14 / atr50 if atr50 > 0 else 1.0 atr_trigger = atr_ratio > CB_ATR_RATIO atr_still_high = was_active and atr_ratio > CB_ATR_RESET # 2. Drawdown check equity = asset_state["equity"] peak = asset_state["peak_equity"] dd = 1.0 - equity / peak if peak > 0 else 0.0 dd_trigger = dd > CB_MAX_DD dd_still_bad = was_active and dd > CB_DD_RESET # Determine state if atr_trigger: return True, "atr_spike", { "atr14": round(atr14, 2), "atr50": round(atr50, 2), "ratio": round(atr_ratio, 2), } if dd_trigger: return True, "drawdown", { "equity": round(equity, 2), "peak": round(peak, 2), "dd_pct": round(dd * 100, 1), } if atr_still_high: return True, "atr_recovering", {"ratio": round(atr_ratio, 2)} if dd_still_bad: return True, "dd_recovering", {"dd_pct": round(dd * 100, 1)} return False, None, {} def get_latest_window(prices): """Get the most recent window for prediction (no future prices needed).""" if len(prices) < WINDOW_SIZE: return None w = prices[-WINDOW_SIZE:].copy() mu, std = w.mean(), w.std() if std < 1e-10: return None return { "norm_input": (w - mu) / std, "mu": float(mu), "std": float(std), "price_idx": len(prices) - 1, "last_price": float(prices[-1]), } # -- State management ------------------------------------------------------- def load_state(): """Load persistent state from JSON.""" if not STATE_FILE.exists(): return None with open(STATE_FILE) as f: return json.load(f) def save_state(state): """Save state to JSON.""" with open(STATE_FILE, "w") as f: json.dump(state, f, indent=2, default=str) def save_model(model, asset): """Save model state_dict.""" MODEL_DIR.mkdir(exist_ok=True) path = MODEL_DIR / f"{asset.replace('-', '_')}.pt" torch.save(model.state_dict(), path) def load_model(asset): """Load model from state_dict.""" path = MODEL_DIR / f"{asset.replace('-', '_')}.pt" if not path.exists(): return None model = create_model() model.load_state_dict(torch.load(path, weights_only=True)) return model def log_event(event: dict): """Append event to trade log (JSONL).""" LOG_DIR.mkdir(exist_ok=True) event["timestamp"] = datetime.now().isoformat() with open(TRADE_LOG, "a") as f: f.write(json.dumps(event, default=str) + "\n") # -- Core logic -------------------------------------------------------------- def init_system(): """Initialize: download data, train models, create state.""" print("=" * 70) print("PAPER TRADER INITIALIZATION") print("=" * 70) state = { "created": datetime.now().isoformat(), "last_update": None, "assets": {}, } for asset, cfg in ASSET_CONFIGS.items(): print(f"\n {asset}...") try: prices, dates = fetch_asset(asset) except Exception as e: print(f" ERROR fetching {asset}: {e}") continue # Prepare training data data = prepare_windows(prices) train_size = min(len(data) - 5, len(data)) # use all available data print(f" {len(data)} windows, training on {train_size}...", end=" ", flush=True) # Train model torch.manual_seed(42) np.random.seed(42) model = create_model() windows = np.array([d["norm_input"] for d in data[:train_size]]) targets = np.array([d["norm_target"] for d in data[:train_size]]) train_model(model, windows, targets, EPOCHS) save_model(model, asset) print("done") # Store asset state state["assets"][asset] = { "equity": INITIAL_EQUITY_PER_ASSET, "peak_equity": INITIAL_EQUITY_PER_ASSET, "open_position": None, "trades_count": 0, "wins": 0, "losses": 0, "total_pnl": 0.0, "last_train_date": str(dates[-1]), "signals_since_retrain": 0, "config": { "K": cfg["K"], "corr_thresh": cfg["corr_thresh"], "astro_filter": cfg["astro_filter"], "adaptive_stop": cfg.get("adaptive_stop", False), "trailing_stop": cfg.get("trailing_stop", False), }, } log_event({ "type": "init", "asset": asset, "windows": len(data), "train_size": train_size, "last_price": float(prices[-1]), "last_date": str(dates[-1]), }) state["last_update"] = datetime.now().isoformat() save_state(state) print(f"\n State saved to {STATE_FILE}") print(f" Models saved to {MODEL_DIR}/") print(f" Trade log: {TRADE_LOG}") print(f"\n Add to crontab for daily runs:") print(f" 0 22 * * * cd {Path(__file__).parent} && " f".venv/bin/python paper_trader.py >> logs/paper_cron.log 2>&1") print("=" * 70) def daily_update(): """Daily update: check positions, generate signals, manage trades.""" state = load_state() if state is None: print("ERROR: No state found. Run with --init first.") sys.exit(1) today = date.today() print(f"\n{'=' * 70}") print(f"PAPER TRADER — {today}") print(f"{'=' * 70}") for asset, cfg_full in ASSET_CONFIGS.items(): asset_state = state["assets"].get(asset) if asset_state is None: print(f"\n {asset}: not initialized, skipping") continue cfg = asset_state["config"] K = cfg["K"] corr_thresh = cfg["corr_thresh"] equity = asset_state["equity"] print(f"\n {asset} (equity: ${equity:,.2f})") # Fetch latest prices try: prices, dates = fetch_asset(asset) except Exception as e: print(f" ERROR fetching: {e}") continue last_date = dates[-1] last_price = float(prices[-1]) print(f" Last price: ${last_price:,.2f} ({last_date})") # 0. Circuit breaker check cb_active, cb_reason, cb_details = check_circuit_breaker( prices, asset_state, ) prev_cb = asset_state.get("circuit_breaker", {}).get("active", False) asset_state["circuit_breaker"] = { "active": cb_active, "reason": cb_reason, "details": cb_details, } if cb_active and not prev_cb: print(f" *** CIRCUIT BREAKER ON: {cb_reason} {cb_details}") log_event({ "type": "circuit_breaker_on", "asset": asset, "reason": cb_reason, **cb_details, }) elif not cb_active and prev_cb: print(f" *** CIRCUIT BREAKER OFF — trading resumed") log_event({ "type": "circuit_breaker_off", "asset": asset, }) elif cb_active: print(f" *** CB ACTIVE: {cb_reason} {cb_details} — no new signals") # 1. Check open position pos = asset_state["open_position"] if pos is not None: pos = _update_position(pos, prices, dates, asset_state, asset, cfg) asset_state["open_position"] = pos # 2. If no open position AND circuit breaker is OFF, check for new signal if asset_state["open_position"] is None and not cb_active: _check_signal( asset, prices, dates, cfg, asset_state, today, ) # 3. Check if retrain needed if asset_state["signals_since_retrain"] >= 10: print(f" Retraining model (10 signals since last)...", end=" ", flush=True) _retrain_model(asset, prices) asset_state["signals_since_retrain"] = 0 asset_state["last_train_date"] = str(last_date) print("done") state["last_update"] = datetime.now().isoformat() save_state(state) _print_portfolio_summary(state) def _update_position(pos, prices, dates, asset_state, asset, cfg): """Check if open position should be closed.""" direction = pos["direction"] # 1 or -1 entry_price = pos["entry_price"] stop_price = pos["stop_price"] best_price = pos["best_price"] stop_dist = pos["stop_dist"] pos_size = pos["pos_size"] pos_value = pos["pos_value"] entry_date = date.fromisoformat(pos["entry_date"]) last_price = float(prices[-1]) last_date = dates[-1] # Days in trade days_held = (last_date - entry_date).days # Update trailing stop if cfg.get("trailing_stop", False): if direction == 1: if last_price > best_price: best_price = last_price pos["best_price"] = best_price trailing_stop = best_price - stop_dist stop_price = max(stop_price, trailing_stop) pos["stop_price"] = stop_price else: if last_price < best_price: best_price = last_price pos["best_price"] = best_price trailing_stop = best_price + stop_dist stop_price = min(stop_price, trailing_stop) pos["stop_price"] = stop_price # Check stop hit stopped = False if direction == 1 and last_price <= stop_price: stopped = True elif direction == -1 and last_price >= stop_price: stopped = True # Check max hold time (SHIFT days = 7 days from entry after K confirmation) max_hold = SHIFT - pos.get("K_used", 2) time_exit = days_held >= max_hold if stopped or time_exit: exit_price = stop_price if stopped else last_price exit_reason = "stop" if stopped else "time" pnl_gross = pos_size * (exit_price - entry_price) * direction commission_cost = pos_value * COMMISSION * 2 pnl_net = pnl_gross - commission_cost pnl_pct = pnl_net / pos_value * 100 if pos_value > 0 else 0 asset_state["equity"] += pnl_net asset_state["peak_equity"] = max( asset_state["peak_equity"], asset_state["equity"] ) asset_state["trades_count"] += 1 asset_state["total_pnl"] += pnl_net win = pnl_net > 0 if win: asset_state["wins"] += 1 else: asset_state["losses"] += 1 dir_str = "LONG" if direction == 1 else "SHORT" win_str = "WIN" if win else "LOSS" print(f" CLOSED {dir_str}: ${entry_price:,.2f} → ${exit_price:,.2f} " f"({exit_reason}) PnL: ${pnl_net:+,.2f} ({pnl_pct:+.2f}%) [{win_str}]") log_event({ "type": "close", "asset": asset, "direction": dir_str, "entry_price": entry_price, "exit_price": exit_price, "entry_date": pos["entry_date"], "exit_date": str(last_date), "days_held": days_held, "exit_reason": exit_reason, "pnl_net": round(pnl_net, 2), "pnl_pct": round(pnl_pct, 4), "equity_after": round(asset_state["equity"], 2), "win": win, }) return None # position closed # Position still open unrealized = pos_size * (last_price - entry_price) * direction dir_str = "LONG" if direction == 1 else "SHORT" print(f" OPEN {dir_str}: entry ${entry_price:,.2f}, " f"stop ${stop_price:,.2f}, current ${last_price:,.2f}, " f"unrealized ${unrealized:+,.2f} (day {days_held})") return pos def _check_signal(asset, prices, dates, cfg, asset_state, today): """Check for new trading signal.""" K = cfg["K"] corr_thresh = cfg["corr_thresh"] astro_filter = cfg.get("astro_filter") # Load model model = load_model(asset) if model is None: print(f" No model found for {asset}") return # We need at least WINDOW_SIZE + K prices to check confirmation if len(prices) < WINDOW_SIZE + K: print(f" Not enough data") return # Get window ending K days ago (to check confirmation) # Window: prices[-(WINDOW_SIZE+K) : -K] # Confirmation: prices[-K:] if len(prices) < WINDOW_SIZE + K: return w = prices[-(WINDOW_SIZE + K):-K].copy() confirm_prices = prices[-K:].copy() mu, std = w.mean(), w.std() if std < 1e-10: return norm_input = (w - mu) / std # Predict pred = predict(model, norm_input) pred_new = pred[-SHIFT:] pred_confirm = pred_new[:K] if len(pred_confirm) < 2: return # Shape confirmation actual_norm = (confirm_prices - mu) / std corr = np.corrcoef(pred_confirm, actual_norm)[0, 1] asset_state["signals_since_retrain"] += 1 if np.isnan(corr) or corr < corr_thresh: print(f" Signal: corr={corr:.3f} < {corr_thresh} — SKIP") return # Astro filter trade_date = dates[-1] if not passes_astro_filter(trade_date, astro_filter): print(f" Signal: corr={corr:.3f} OK, astro filter — SKIP") log_event({ "type": "signal_filtered", "asset": asset, "date": str(trade_date), "correlation": round(float(corr), 4), "filter": "astro", }) return # Direction from prediction pred_direction = pred_new[-1] - pred_new[K - 1] if abs(pred_direction) < 1e-10: return direction = 1 if pred_direction > 0 else -1 entry_price = float(prices[-1]) # enter at current price # Stop distance equity = asset_state["equity"] if cfg.get("adaptive_stop", False): atr = compute_atr(prices, len(prices) - 1) stop_dist = max(atr * 2.0, entry_price * 0.005) else: pred_range = np.max(np.abs(pred_new[K:] - pred_new[K - 1])) stop_dist = max(pred_range * std * 1.5, entry_price * 0.005) # Position sizing (fixed 2% risk, capped at CB_MAX_POS_PCT of equity) risk_amount = equity * RISK_PER_TRADE pos_size = risk_amount / stop_dist pos_value = pos_size * entry_price max_pos_value = equity * CB_MAX_POS_PCT if pos_value > max_pos_value: pos_size = max_pos_value / entry_price pos_value = max_pos_value stop_price = entry_price - direction * stop_dist dir_str = "LONG" if direction == 1 else "SHORT" print(f" SIGNAL: {dir_str} at ${entry_price:,.2f}, " f"stop ${stop_price:,.2f} (dist ${stop_dist:,.2f}), " f"corr={corr:.3f}, size=${pos_value:,.2f}") # Open position asset_state["open_position"] = { "direction": direction, "entry_price": entry_price, "entry_date": str(trade_date), "stop_price": stop_price, "stop_dist": stop_dist, "best_price": entry_price, "pos_size": pos_size, "pos_value": pos_value, "correlation": float(corr), "K_used": K, } log_event({ "type": "open", "asset": asset, "direction": dir_str, "entry_price": entry_price, "stop_price": round(stop_price, 2), "stop_dist": round(stop_dist, 2), "pos_size": round(pos_size, 6), "pos_value": round(pos_value, 2), "correlation": round(float(corr), 4), "date": str(trade_date), }) def _retrain_model(asset, prices): """Retrain model on all available data.""" data = prepare_windows(prices) train_size = len(data) torch.manual_seed(42) np.random.seed(42) model = create_model() windows = np.array([d["norm_input"] for d in data[:train_size]]) targets = np.array([d["norm_target"] for d in data[:train_size]]) train_model(model, windows, targets, FINETUNE_EPOCHS) save_model(model, asset) def _print_portfolio_summary(state): """Print portfolio overview.""" print(f"\n{'=' * 70}") print("PORTFOLIO SUMMARY") print(f"{'=' * 70}") total_equity = 0 total_invested = 0 print(f" {'Asset':<10s} {'Equity':>10s} {'PnL':>10s} {'Trades':>7s} " f"{'W/L':>7s} {'WR%':>5s} {'Position':>10s} {'CB':>4s}") print(f" {'─' * 68}") for asset in ASSET_CONFIGS: a = state["assets"].get(asset) if a is None: continue eq = a["equity"] pnl = a["total_pnl"] trades = a["trades_count"] wins = a["wins"] losses = a["losses"] wr = wins / trades * 100 if trades > 0 else 0 pos_str = "—" pos = a.get("open_position") if pos: d = "L" if pos["direction"] == 1 else "S" pos_str = f"{d} ${pos['entry_price']:,.0f}" cb = a.get("circuit_breaker", {}) cb_str = "ON" if cb.get("active") else "—" total_equity += eq total_invested += INITIAL_EQUITY_PER_ASSET print(f" {asset:<10s} ${eq:>9,.2f} ${pnl:>+9,.2f} {trades:>7d} " f"{wins:>3d}/{losses:<3d} {wr:>4.0f}% {pos_str:>10s} {cb_str:>4s}") total_ret = (total_equity / total_invested - 1) * 100 if total_invested > 0 else 0 print(f" {'─' * 62}") print(f" {'TOTAL':<10s} ${total_equity:>9,.2f} " f"${total_equity - total_invested:>+9,.2f} " f"({total_ret:+.1f}%)") print(f"{'=' * 70}") def show_status(): """Show current status.""" state = load_state() if state is None: print("No state found. Run with --init first.") return print(f"Last update: {state.get('last_update', 'never')}") _print_portfolio_summary(state) def show_history(): """Show trade history from log.""" if not TRADE_LOG.exists(): print("No trade log found.") return print(f"\n{'=' * 70}") print("TRADE HISTORY") print(f"{'=' * 70}") with open(TRADE_LOG) as f: for line in f: event = json.loads(line.strip()) etype = event.get("type") ts = event.get("timestamp", "")[:19] if etype == "open": print(f" {ts} OPEN {event['asset']} {event['direction']} " f"@ ${event['entry_price']:,.2f} " f"(stop ${event['stop_price']:,.2f}, " f"corr={event['correlation']:.3f})") elif etype == "close": win = "WIN" if event.get("win") else "LOSS" print(f" {ts} CLOSE {event['asset']} {event['direction']} " f"@ ${event['exit_price']:,.2f} " f"PnL ${event['pnl_net']:+,.2f} ({event['pnl_pct']:+.2f}%) " f"[{win}] ({event['exit_reason']})") elif etype == "signal_filtered": print(f" {ts} SKIP {event['asset']} " f"corr={event['correlation']:.3f} " f"(filtered: {event['filter']})") elif etype == "init": print(f" {ts} INIT {event['asset']} " f"last=${event['last_price']:,.2f} " f"({event['windows']} windows)") # -- Realtime stop monitor via Binance (ccxt) -------------------------------- def _fetch_realtime_price(exchange, asset): """Get current price from Binance.""" symbol = BINANCE_SYMBOLS.get(asset) if not symbol: return None try: ticker = exchange.fetch_ticker(symbol) return ticker["last"] except Exception as e: print(f" {asset}: fetch error ({e})") return None def _monitor_check_stops(state, exchange): """Check all open positions against realtime prices. Close if stopped.""" closed_any = False now = datetime.now() for asset in ASSET_CONFIGS: asset_state = state["assets"].get(asset) if asset_state is None: continue pos = asset_state.get("open_position") if pos is None: continue price = _fetch_realtime_price(exchange, asset) if price is None: continue direction = pos["direction"] entry_price = pos["entry_price"] stop_price = pos["stop_price"] stop_dist = pos["stop_dist"] best_price = pos["best_price"] pos_size = pos["pos_size"] pos_value = pos["pos_value"] entry_date = date.fromisoformat(pos["entry_date"]) days_held = (date.today() - entry_date).days # Update trailing stop cfg = asset_state["config"] if cfg.get("trailing_stop", False): if direction == 1 and price > best_price: pos["best_price"] = price best_price = price elif direction == -1 and price < best_price: pos["best_price"] = price best_price = price if direction == 1: new_stop = best_price - stop_dist if new_stop > stop_price: pos["stop_price"] = new_stop stop_price = new_stop else: new_stop = best_price + stop_dist if new_stop < stop_price: pos["stop_price"] = new_stop stop_price = new_stop # Check stop stopped = False if direction == 1 and price <= stop_price: stopped = True elif direction == -1 and price >= stop_price: stopped = True # Check time exit max_hold = SHIFT - pos.get("K_used", 2) time_exit = days_held >= max_hold dir_str = "LONG" if direction == 1 else "SHORT" unrealized = pos_size * (price - entry_price) * direction if stopped or time_exit: exit_price = stop_price if stopped else price exit_reason = "stop" if stopped else "time" pnl_gross = pos_size * (exit_price - entry_price) * direction commission_cost = pos_value * COMMISSION * 2 pnl_net = pnl_gross - commission_cost pnl_pct = pnl_net / pos_value * 100 if pos_value > 0 else 0 asset_state["equity"] += pnl_net asset_state["peak_equity"] = max( asset_state["peak_equity"], asset_state["equity"] ) asset_state["trades_count"] += 1 asset_state["total_pnl"] += pnl_net win = pnl_net > 0 if win: asset_state["wins"] += 1 else: asset_state["losses"] += 1 asset_state["open_position"] = None closed_any = True win_str = "WIN" if win else "LOSS" print(f" {now.strftime('%H:%M:%S')} {asset} CLOSED {dir_str}: " f"${entry_price:,.2f} → ${exit_price:,.2f} ({exit_reason}) " f"PnL ${pnl_net:+,.2f} ({pnl_pct:+.2f}%) [{win_str}]") log_event({ "type": "close", "asset": asset, "direction": dir_str, "entry_price": entry_price, "exit_price": exit_price, "entry_date": pos["entry_date"], "exit_date": str(date.today()), "days_held": days_held, "exit_reason": exit_reason, "pnl_net": round(pnl_net, 2), "pnl_pct": round(pnl_pct, 4), "equity_after": round(asset_state["equity"], 2), "win": win, "source": "monitor", }) else: print(f" {now.strftime('%H:%M:%S')} {asset} {dir_str}: " f"${price:,.2f} (stop ${stop_price:,.2f}, " f"unreal ${unrealized:+,.2f}, day {days_held})") return closed_any def run_monitor(interval_minutes=240): """Run continuous position monitor. Shows realtime prices from Binance. NOTE: Hourly backtest proved that intraday stop monitoring HURTS results (Sharpe drops by 0.5-1.0 across all assets due to noise stops on wicks). Stops are only checked on DAILY close via daily_update(). This monitor shows unrealized P&L only — no stop execution. """ state = load_state() if state is None: print("ERROR: No state found. Run with --init first.") sys.exit(1) exchange = ccxt.binance({"enableRateLimit": True}) print(f"{'=' * 70}") print(f"POSITION MONITOR (Binance, every {interval_minutes}min)") print(f"{'=' * 70}") print(f" NOTE: stops checked on DAILY close only (hourly hurts results)") # Check which assets have open positions open_assets = [] for asset in ASSET_CONFIGS: a = state["assets"].get(asset) if a and a.get("open_position"): pos = a["open_position"] d = "LONG" if pos["direction"] == 1 else "SHORT" print(f" {asset}: {d} @ ${pos['entry_price']:,.2f}, " f"stop ${pos['stop_price']:,.2f}") open_assets.append(asset) if not open_assets: print("\n No open positions to monitor.") print(" Run daily update first to generate signals.") return print(f"\n Monitoring {len(open_assets)} positions...") print(f" Press Ctrl+C to stop.\n") try: while True: state = load_state() if state is None: break has_open = any( state["assets"].get(a, {}).get("open_position") for a in ASSET_CONFIGS ) if not has_open: print(f"\n All positions closed. Stopping monitor.") break # Show current prices and unrealized P&L (NO stop execution) now = datetime.now() for asset in ASSET_CONFIGS: asset_state = state["assets"].get(asset) if not asset_state: continue pos = asset_state.get("open_position") if not pos: continue price = _fetch_realtime_price(exchange, asset) if price is None: continue direction = pos["direction"] entry_price = pos["entry_price"] stop_price = pos["stop_price"] pos_size = pos["pos_size"] entry_date = date.fromisoformat(pos["entry_date"]) days_held = (date.today() - entry_date).days unrealized = pos_size * (price - entry_price) * direction dir_str = "LONG" if direction == 1 else "SHORT" dist_to_stop = abs(price - stop_price) print(f" {now.strftime('%H:%M:%S')} {asset} {dir_str}: " f"${price:,.2f} (stop ${stop_price:,.2f}, " f"dist ${dist_to_stop:,.2f}, " f"unreal ${unrealized:+,.2f}, day {days_held})") time.sleep(interval_minutes * 60) except KeyboardInterrupt: print(f"\n\n Monitor stopped.") _print_portfolio_summary(state) # -- Entry point ------------------------------------------------------------- def main(): parser = argparse.ArgumentParser(description="RemizovNet Paper Trader") parser.add_argument("--init", action="store_true", help="Initialize: train models and create state") parser.add_argument("--status", action="store_true", help="Show current positions and equity") parser.add_argument("--history", action="store_true", help="Show trade history") parser.add_argument("--monitor", action="store_true", help="Realtime stop monitor via Binance") parser.add_argument("--interval", type=int, default=240, help="Monitor check interval in minutes (default: 240)") args = parser.parse_args() if args.init: init_system() elif args.status: show_status() elif args.history: show_history() elif args.monitor: run_monitor(args.interval) else: daily_update() if __name__ == "__main__": main()