""" Paper trading system for RemizovNet. Runs daily via cron. Uses best strategy: ATR stop + Trailing stop. Maintains persistent state (model, positions, equity) between runs. Usage: python paper_trader.py # daily update (for cron) 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 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 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" # 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 # -- 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 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})") # 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, check for new signal if asset_state["open_position"] is None: _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) risk_amount = equity * RISK_PER_TRADE pos_size = risk_amount / stop_dist pos_value = pos_size * entry_price if pos_value > equity: pos_size = equity / entry_price pos_value = equity 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}") print(f" {'─' * 62}") 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}" 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}") 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)") # -- 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") args = parser.parse_args() if args.init: init_system() elif args.status: show_status() elif args.history: show_history() else: daily_update() if __name__ == "__main__": main()