commit 98f2340a53349a56a08832110a6a372ad3d900b8 Author: anor Date: Sun Mar 8 20:53:55 2026 +1000 feat: RemizovTrader v0.1.0 — полный торговый продукт - CLI: init, run, status, history, web - Web dashboard: FastAPI + Jinja2 + HTMX + Pico CSS + Chart.js - Core: model wrapper, shape confirmation, risk management, circuit breaker - SQLite state management (trades, positions, equity, signals) - config.yaml для всех параметров - Paper mode с $100 начальным капиталом Co-Authored-By: Claude Opus 4.6 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0016f7c --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +__pycache__/ +*.py[cod] +*.egg-info/ +.venv/ +dist/ +build/ +data/models/ +data/trades.db +.DS_Store diff --git a/config.yaml b/config.yaml new file mode 100644 index 0000000..d4f2731 --- /dev/null +++ b/config.yaml @@ -0,0 +1,53 @@ +# RemizovTrader Configuration + +mode: paper # paper | live + +capital: + initial: 100.0 + currency: USDT + +risk: + per_trade: 0.05 # 5% risk per trade ($100 capital) + max_position_pct: 0.50 # max 50% of equity in one position + max_open_positions: 2 + +assets: + - ticker: BTC-USD + binance_symbol: BTC/USDT + K: 2 + corr_thresh: 0.5 + trailing_stop: true + +model: + window_size: 64 + n_steps: 20 + total_time: 0.5 + shift: 7 + epochs: 200 + finetune_epochs: 50 + lr: 0.003 + +circuit_breaker: + atr_ratio_on: 3.0 # ATR14/ATR50 > 3 → pause + atr_ratio_off: 2.0 # ATR14/ATR50 < 2 → resume + max_drawdown: 0.20 # 20% DD → pause + dd_reset: 0.10 # 10% DD → resume + +exchange: + name: binance + api_key: "" # set via REMIZOV_API_KEY env var + api_secret: "" # set via REMIZOV_API_SECRET env var + testnet: true + +web: + host: 0.0.0.0 + port: 8080 + +telegram: + enabled: false + bot_token: "" # set via REMIZOV_TG_TOKEN env var + chat_id: "" + +schedule: + timeframe: 1d # 1d | 4h + check_time: "22:00" # UTC diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..fb630a1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,36 @@ +[build-system] +requires = ["setuptools>=68.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "remizov-trader" +version = "0.1.0" +description = "Crypto trading system based on RemizovNet PDE/SDE solver" +requires-python = ">=3.11" +dependencies = [ + "remizov-net @ file:///Users/alchemist/Python_projects/remizov-net", + "numpy>=1.26", + "torch>=2.2", + "yfinance>=0.2.36", + "ccxt>=4.5", + "fastapi>=0.115", + "uvicorn>=0.32", + "jinja2>=3.1", + "pyyaml>=6.0", + "click>=8.1", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0", + "ruff>=0.8", +] + +[project.scripts] +remizov-trader = "remizov_trader.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.ruff] +line-length = 100 diff --git a/src/remizov_trader/__init__.py b/src/remizov_trader/__init__.py new file mode 100644 index 0000000..d712af8 --- /dev/null +++ b/src/remizov_trader/__init__.py @@ -0,0 +1,3 @@ +"""RemizovTrader — crypto trading system based on RemizovNet PDE/SDE solver.""" + +__version__ = "0.1.0" diff --git a/src/remizov_trader/cli.py b/src/remizov_trader/cli.py new file mode 100644 index 0000000..8ec8941 --- /dev/null +++ b/src/remizov_trader/cli.py @@ -0,0 +1,188 @@ +"""CLI interface — remizov-trader command.""" + +from __future__ import annotations + +import sys + +import click +import numpy as np +import torch + +from .config import load_config +from .state import get_db, init_db, get_all_assets, get_open_position, get_trade_history, upsert_asset + + +@click.group() +def main(): + """RemizovTrader — crypto trading with RemizovNet PDE/SDE solver.""" + pass + + +@main.command() +def init(): + """Initialize: download data, train models, create state.""" + cfg = load_config() + conn = get_db() + init_db(conn) + + from .core import model as model_mod, signals + + click.echo("=" * 60) + click.echo("REMIZOV TRADER — INIT") + click.echo("=" * 60) + click.echo(f" Mode: {cfg.mode}") + click.echo(f" Capital: ${cfg.initial_capital:.2f}") + click.echo(f" Assets: {[a.ticker for a in cfg.assets]}") + click.echo() + + for asset_cfg in cfg.assets: + ticker = asset_cfg.ticker + click.echo(f" {ticker}...", nl=False) + + interval = cfg.timeframe + period = "max" if interval == "1d" else "730d" + prices, dates = signals.fetch_prices(ticker, interval, period) + if prices is None: + click.echo(" ERROR: no data") + continue + + data = signals.prepare_windows(prices, cfg.model.window_size, cfg.model.shift) + click.echo(f" {len(prices)} bars, {len(data)} windows...", nl=False) + + torch.manual_seed(42) + np.random.seed(42) + mdl = model_mod.create_model(cfg.model) + windows = np.array([d["norm_input"] for d in data]) + targets = np.array([d["norm_target"] for d in data]) + model_mod.train(mdl, windows, targets, cfg.model.epochs, cfg.model.lr) + model_mod.save_model(mdl, ticker) + + upsert_asset(conn, ticker, cfg.initial_capital) + click.echo(" done") + + conn.close() + click.echo(f"\n Database: data/trades.db") + click.echo(f" Models: data/models/") + click.echo("=" * 60) + + +@main.command() +def run(): + """Run one trading cycle: check stops + generate signals.""" + cfg = load_config() + conn = get_db() + init_db(conn) + + from .core.executor import run_cycle + + click.echo(f"Running cycle ({cfg.timeframe})...") + logs = run_cycle(conn, cfg) + + for msg in logs: + click.echo(f" {msg}") + + conn.close() + click.echo("Done.") + + +@main.command() +def status(): + """Show current positions and equity.""" + cfg = load_config() + conn = get_db() + init_db(conn) + + assets = get_all_assets(conn) + if not assets: + click.echo("No assets initialized. Run: remizov-trader init") + return + + click.echo() + click.echo("=" * 70) + click.echo(f" REMIZOV TRADER — {cfg.mode.upper()} MODE") + click.echo("=" * 70) + + total_equity = 0 + total_initial = 0 + + header = f" {'Asset':<10s} {'Equity':>10s} {'PnL':>10s} {'Trades':>7s} {'WR':>5s} {'Position':>12s} {'CB':>3s}" + click.echo(header) + click.echo(f" {'─' * 62}") + + for a in assets: + eq = a["equity"] + pnl = a["total_pnl"] + trades = a["trades_count"] + wins = a["wins"] + wr = wins / trades * 100 if trades > 0 else 0 + + pos = get_open_position(conn, a["ticker"]) + pos_str = "—" + if pos: + d = "L" if pos["direction"] == 1 else "S" + pos_str = f"{d} ${pos['entry_price']:,.0f}" + + cb = "ON" if a["cb_active"] else "—" + total_equity += eq + total_initial += cfg.initial_capital + + click.echo(f" {a['ticker']:<10s} ${eq:>9,.2f} ${pnl:>+9,.2f} " + f"{trades:>7d} {wr:>4.0f}% {pos_str:>12s} {cb:>3s}") + + total_ret = (total_equity / total_initial - 1) * 100 if total_initial > 0 else 0 + click.echo(f" {'─' * 62}") + click.echo(f" {'TOTAL':<10s} ${total_equity:>9,.2f} " + f"${total_equity - total_initial:>+9,.2f} ({total_ret:+.1f}%)") + click.echo("=" * 70) + + conn.close() + + +@main.command() +@click.option("--limit", "-n", default=20, help="Number of trades to show") +def history(limit): + """Show trade history.""" + conn = get_db() + init_db(conn) + + trades = get_trade_history(conn, limit=limit) + if not trades: + click.echo("No trades yet.") + return + + click.echo() + click.echo(f" {'Date':<12s} {'Asset':<10s} {'Dir':>5s} {'Entry':>10s} " + f"{'Exit':>10s} {'PnL':>10s} {'Reason':>6s}") + click.echo(f" {'─' * 65}") + + for t in reversed(trades): + d = "LONG" if t["direction"] == 1 else "SHORT" + pnl = t["pnl_net"] or 0 + click.echo(f" {t['entry_date']:<12s} {t['ticker']:<10s} {d:>5s} " + f"${t['entry_price']:>9,.2f} ${(t['exit_price'] or 0):>9,.2f} " + f"${pnl:>+9,.2f} {(t['exit_reason'] or ''):>6s}") + + conn.close() + + +@main.command() +def web(): + """Start web dashboard.""" + cfg = load_config() + + click.echo(f"Starting web dashboard on http://{cfg.web.host}:{cfg.web.port}") + + import uvicorn + from .web.app import create_app + + app = create_app(cfg) + uvicorn.run(app, host=cfg.web.host, port=cfg.web.port) + + +@main.command() +@click.argument("key") +@click.argument("value") +def config(key, value): + """Show or update config value (e.g., risk.per_trade 0.05).""" + click.echo(f"Config: {key} = {value}") + click.echo("(Config update via CLI not yet implemented — edit config.yaml directly)") diff --git a/src/remizov_trader/config.py b/src/remizov_trader/config.py new file mode 100644 index 0000000..2fac508 --- /dev/null +++ b/src/remizov_trader/config.py @@ -0,0 +1,130 @@ +"""Configuration loader — single source of truth for all parameters.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass, field +from pathlib import Path + +import yaml + +CONFIG_PATH = Path(__file__).parent.parent.parent / "config.yaml" +DATA_DIR = Path(__file__).parent.parent.parent / "data" + + +@dataclass +class AssetConfig: + ticker: str + binance_symbol: str + K: int = 2 + corr_thresh: float = 0.5 + trailing_stop: bool = True + + +@dataclass +class ModelConfig: + window_size: int = 64 + n_steps: int = 20 + total_time: float = 0.5 + shift: int = 7 + epochs: int = 200 + finetune_epochs: int = 50 + lr: float = 0.003 + + +@dataclass +class RiskConfig: + per_trade: float = 0.05 + max_position_pct: float = 0.50 + max_open_positions: int = 2 + + +@dataclass +class CircuitBreakerConfig: + atr_ratio_on: float = 3.0 + atr_ratio_off: float = 2.0 + max_drawdown: float = 0.20 + dd_reset: float = 0.10 + + +@dataclass +class ExchangeConfig: + name: str = "binance" + api_key: str = "" + api_secret: str = "" + testnet: bool = True + + +@dataclass +class WebConfig: + host: str = "0.0.0.0" + port: int = 8080 + + +@dataclass +class TelegramConfig: + enabled: bool = False + bot_token: str = "" + chat_id: str = "" + + +@dataclass +class Config: + mode: str = "paper" + initial_capital: float = 100.0 + currency: str = "USDT" + timeframe: str = "1d" + check_time: str = "22:00" + assets: list[AssetConfig] = field(default_factory=list) + model: ModelConfig = field(default_factory=ModelConfig) + risk: RiskConfig = field(default_factory=RiskConfig) + circuit_breaker: CircuitBreakerConfig = field(default_factory=CircuitBreakerConfig) + exchange: ExchangeConfig = field(default_factory=ExchangeConfig) + web: WebConfig = field(default_factory=WebConfig) + telegram: TelegramConfig = field(default_factory=TelegramConfig) + + +def load_config(path: Path | None = None) -> Config: + """Load configuration from YAML file + environment variables.""" + path = path or CONFIG_PATH + if not path.exists(): + return Config() + + with open(path) as f: + raw = yaml.safe_load(f) or {} + + assets = [ + AssetConfig(**a) for a in raw.get("assets", []) + ] + + model_raw = raw.get("model", {}) + risk_raw = raw.get("risk", {}) + cb_raw = raw.get("circuit_breaker", {}) + exchange_raw = raw.get("exchange", {}) + web_raw = raw.get("web", {}) + tg_raw = raw.get("telegram", {}) + capital_raw = raw.get("capital", {}) + schedule_raw = raw.get("schedule", {}) + + exchange = ExchangeConfig(**exchange_raw) + # Override with env vars (secrets should not be in config file) + exchange.api_key = os.environ.get("REMIZOV_API_KEY", exchange.api_key) + exchange.api_secret = os.environ.get("REMIZOV_API_SECRET", exchange.api_secret) + + telegram = TelegramConfig(**tg_raw) + telegram.bot_token = os.environ.get("REMIZOV_TG_TOKEN", telegram.bot_token) + + return Config( + mode=raw.get("mode", "paper"), + initial_capital=capital_raw.get("initial", 100.0), + currency=capital_raw.get("currency", "USDT"), + timeframe=schedule_raw.get("timeframe", "1d"), + check_time=schedule_raw.get("check_time", "22:00"), + assets=assets or [AssetConfig(ticker="BTC-USD", binance_symbol="BTC/USDT")], + model=ModelConfig(**model_raw), + risk=RiskConfig(**risk_raw), + circuit_breaker=CircuitBreakerConfig(**cb_raw), + exchange=exchange, + web=WebConfig(**web_raw), + telegram=telegram, + ) diff --git a/src/remizov_trader/core/__init__.py b/src/remizov_trader/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/remizov_trader/core/executor.py b/src/remizov_trader/core/executor.py new file mode 100644 index 0000000..81c76d9 --- /dev/null +++ b/src/remizov_trader/core/executor.py @@ -0,0 +1,246 @@ +"""Trade executor — paper mode (SQLite) and live mode (ccxt, future).""" + +from __future__ import annotations + +import sqlite3 +from datetime import date + +from ..config import Config, AssetConfig +from ..state import ( + add_equity_snapshot, close_position, get_open_position, log_cb_event, + log_signal, open_position, update_asset, update_position, +) +from . import model as model_mod +from . import risk, signals + + +def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]: + """Run one trading cycle: check stops, generate signals. + + Returns list of log messages. + """ + logs = [] + today = str(date.today()) + + for asset_cfg in cfg.assets: + ticker = asset_cfg.ticker + asset = _get_or_skip(conn, ticker) + if asset is None: + logs.append(f"{ticker}: not initialized") + continue + + # Fetch prices + interval = cfg.timeframe + period = "max" if interval == "1d" else "730d" + prices, dates = signals.fetch_prices(ticker, interval, period) + if prices is None or len(prices) < cfg.model.window_size + cfg.model.shift: + logs.append(f"{ticker}: not enough data") + continue + + last_price = float(prices[-1]) + last_date = str(dates[-1]) + + # Circuit breaker + cb_active, cb_reason, cb_details = risk.check_circuit_breaker( + prices, asset["equity"], asset["peak_equity"], + bool(asset["cb_active"]), cfg.circuit_breaker, + ) + + if cb_active != bool(asset["cb_active"]): + action = "on" if cb_active else "off" + log_cb_event(conn, ticker, action, cb_reason or "", str(cb_details)) + update_asset(conn, ticker, cb_active=int(cb_active), cb_reason=cb_reason) + logs.append(f"{ticker}: CB {'ON — ' + cb_reason if cb_active else 'OFF'}") + + # 1. Check open position + pos = get_open_position(conn, ticker) + if pos is not None: + msg = _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg) + if msg: + logs.append(f"{ticker}: {msg}") + # Re-fetch asset after potential close + asset = _get_or_skip(conn, ticker) + pos = get_open_position(conn, ticker) + + # 2. New signal (if no position and CB off) + if pos is None and not cb_active: + # Check max open positions + open_count = _count_open_positions(conn) + if open_count >= cfg.risk.max_open_positions: + logs.append(f"{ticker}: max {cfg.risk.max_open_positions} positions reached") + else: + msg = _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg) + if msg: + logs.append(f"{ticker}: {msg}") + elif pos is None and cb_active: + logs.append(f"{ticker}: CB active ({cb_reason}) — skip signal") + + # Equity snapshot + asset = _get_or_skip(conn, ticker) + if asset: + add_equity_snapshot(conn, ticker, asset["equity"], last_price, last_date) + + # Retrain check + if asset and asset["signals_since_retrain"] >= 10: + _retrain(conn, ticker, prices, cfg) + logs.append(f"{ticker}: retrained") + + return logs + + +def _get_or_skip(conn, ticker): + from ..state import get_asset + return get_asset(conn, ticker) + + +def _count_open_positions(conn: sqlite3.Connection) -> int: + row = conn.execute( + "SELECT COUNT(*) as cnt FROM positions WHERE status='open'" + ).fetchone() + return row["cnt"] if row else 0 + + +def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg): + """Check if open position should be closed. Returns log message or None.""" + 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 = pos["entry_date"] + + last_price = float(prices[-1]) + last_date = str(dates[-1]) + + # Days held + from datetime import date as d + days_held = (d.fromisoformat(last_date) - d.fromisoformat(entry_date)).days + + # Update trailing stop + if asset_cfg.trailing_stop: + best_price, stop_price = risk.update_trailing_stop( + last_price, best_price, stop_price, stop_dist, direction, + ) + update_position(conn, pos["id"], + best_price=best_price, stop_price=stop_price) + + # Check stop + stopped = risk.is_stopped(last_price, stop_price, direction) + + # Check time exit + max_hold = cfg.model.shift - pos["k_used"] + 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_net, pnl_pct = risk.calculate_pnl( + entry_price, exit_price, direction, pos_size, pos_value, + ) + + close_position(conn, pos["id"], + exit_price=exit_price, exit_date=last_date, + exit_reason=exit_reason, pnl_net=pnl_net, pnl_pct=pnl_pct) + + new_equity = asset["equity"] + pnl_net + new_peak = max(asset["peak_equity"], new_equity) + win = pnl_net > 0 + + update_asset(conn, asset["ticker"], + equity=new_equity, peak_equity=new_peak, + trades_count=asset["trades_count"] + 1, + wins=asset["wins"] + (1 if win else 0), + losses=asset["losses"] + (0 if win else 1), + total_pnl=asset["total_pnl"] + pnl_net) + + dir_str = "LONG" if direction == 1 else "SHORT" + win_str = "WIN" if win else "LOSS" + return (f"CLOSED {dir_str} ${entry_price:,.2f}→${exit_price:,.2f} " + f"({exit_reason}) PnL ${pnl_net:+,.2f} [{win_str}]") + + return None + + +def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg): + """Check for new trading signal. Returns log message or None.""" + K = asset_cfg.K + corr_thresh = asset_cfg.corr_thresh + + # Load model + mdl = model_mod.load_model(ticker, cfg.model) + if mdl is None: + return "no model" + + # Get signal window + sw = signals.get_latest_signal_window(prices, cfg.model.window_size, K) + if sw is None: + return "not enough data" + + # Predict + pred = model_mod.predict(mdl, sw["norm_input"]) + pred_new = pred[-cfg.model.shift:] + + # Shape confirmation + corr, confirmed = signals.check_shape_confirmation( + pred_new, sw["confirm_prices"], sw["mu"], sw["std"], K, corr_thresh, + ) + + update_asset(conn, ticker, + signals_since_retrain=asset["signals_since_retrain"] + 1) + + if not confirmed: + log_signal(conn, ticker=ticker, date=str(dates[-1]), + correlation=corr, action="skip_corr") + return f"corr={corr:.3f} < {corr_thresh} — SKIP" + + # Direction + direction = signals.get_direction(pred_new, K) + if direction is None: + return "indeterminate direction" + + entry_price = sw["last_price"] + + # Stop + stop_dist, stop_price = risk.calculate_stop(prices, len(prices) - 1, entry_price, direction) + + # Position sizing + pos_size, pos_value = risk.calculate_position( + asset["equity"], entry_price, stop_dist, cfg.risk, + ) + + # Open position + pos_id = open_position(conn, + ticker=ticker, direction=direction, + entry_price=entry_price, entry_date=str(dates[-1]), + stop_price=stop_price, stop_dist=stop_dist, + best_price=entry_price, pos_size=pos_size, + pos_value=pos_value, correlation=corr, k_used=K) + + log_signal(conn, ticker=ticker, date=str(dates[-1]), + correlation=corr, direction=direction, action="open") + + dir_str = "LONG" if direction == 1 else "SHORT" + return (f"SIGNAL {dir_str} @ ${entry_price:,.2f} " + f"stop ${stop_price:,.2f} corr={corr:.3f} size=${pos_value:,.2f}") + + +def _retrain(conn, ticker, prices, cfg): + """Retrain model on all available data.""" + import numpy as np + import torch + + data = signals.prepare_windows(prices, cfg.model.window_size, cfg.model.shift) + if len(data) < 20: + return + + torch.manual_seed(42) + np.random.seed(42) + mdl = model_mod.create_model(cfg.model) + windows = np.array([d["norm_input"] for d in data]) + targets = np.array([d["norm_target"] for d in data]) + model_mod.train(mdl, windows, targets, cfg.model.finetune_epochs, cfg.model.lr) + model_mod.save_model(mdl, ticker) + update_asset(conn, ticker, signals_since_retrain=0, last_train_date=str(date.today())) diff --git a/src/remizov_trader/core/model.py b/src/remizov_trader/core/model.py new file mode 100644 index 0000000..9eb2c7f --- /dev/null +++ b/src/remizov_trader/core/model.py @@ -0,0 +1,78 @@ +"""RemizovNet model wrapper — train, predict, save/load.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch +import torch.nn as nn + +from .net import EnhancedRemizovNet + +from ..config import ModelConfig + +MODELS_DIR = Path(__file__).parent.parent.parent.parent / "data" / "models" + + +def create_model(cfg: ModelConfig) -> EnhancedRemizovNet: + return EnhancedRemizovNet( + grid_size=cfg.window_size, + n_steps=cfg.n_steps, + total_time=cfg.total_time, + dx=1.0 / cfg.window_size, + use_sde=True, + ) + + +def train(model: EnhancedRemizovNet, windows: np.ndarray, targets: np.ndarray, + epochs: int, lr: float = 0.003) -> float: + """Train model, return final loss.""" + 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)) + last_loss = 0.0 + + 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() + last_loss = loss.item() + + return last_loss + + +def predict(model: EnhancedRemizovNet, norm_input: np.ndarray) -> np.ndarray: + """Single prediction, returns full output array.""" + model.eval() + with torch.no_grad(): + inp = torch.tensor(norm_input, dtype=torch.float32).unsqueeze(0) + return model(inp, stochastic=False).squeeze(0).numpy() + + +def save_model(model: EnhancedRemizovNet, ticker: str, path: Path | None = None) -> Path: + """Save model state_dict.""" + d = path or MODELS_DIR + d.mkdir(parents=True, exist_ok=True) + fpath = d / f"{ticker.replace('-', '_')}.pt" + torch.save(model.state_dict(), fpath) + return fpath + + +def load_model(ticker: str, cfg: ModelConfig, path: Path | None = None) -> EnhancedRemizovNet | None: + """Load model from state_dict.""" + d = path or MODELS_DIR + fpath = d / f"{ticker.replace('-', '_')}.pt" + if not fpath.exists(): + return None + model = create_model(cfg) + model.load_state_dict(torch.load(fpath, weights_only=True)) + return model diff --git a/src/remizov_trader/core/net.py b/src/remizov_trader/core/net.py new file mode 100644 index 0000000..8ad31df --- /dev/null +++ b/src/remizov_trader/core/net.py @@ -0,0 +1,310 @@ +""" +Enhanced RemizovNet variants for crypto direction prediction. + +4 enhancements from arxiv research: + 1. Neural SDE — learnable σ(x) noise in Chernoff steps + 2. Learnable FNO — spectral correction on top of physics kernel + 3. Diagonal SSM — state space regime encoder + 4. GBM augmentation — heteroskedastic data augmentation (in experiment.py) + +All enhancements are toggleable via flags for clean ablation. +""" + +from __future__ import annotations + +import math + +import torch +import torch.nn as nn +import torch.nn.functional as f_nn +from torch import Tensor + + +# --------------------------------------------------------------------------- +# 1. Diagonal SSM — regime encoder +# --------------------------------------------------------------------------- + +class DiagonalSSM(nn.Module): + """Diagonal State Space Model for regime detection. + + Captures long-range dependencies via learned decay rates. + Computed efficiently via FFT convolution (not sequential). + + Architecture: S4D-style diagonal SSM with skip connection. + y[n] = sum_d C[d] * A[d]^n * B[d] (conv with input) + D * x[n] + """ + + def __init__(self, d_state: int = 8): + super().__init__() + self.d_state = d_state + + # Decay rates in log-space (negative → stable, in (0,1) after exp) + # HiPPO-inspired initialization: different timescales + self.log_A = nn.Parameter(torch.linspace(-0.1, -2.0, d_state)) + + # Input-to-state and state-to-output projections + self.B = nn.Parameter(torch.randn(d_state) * 0.1) + self.C = nn.Parameter(torch.randn(d_state) * 0.1) + + # Skip connection (initialized to 1 = identity at start) + self.D = nn.Parameter(torch.ones(1)) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x: (batch, seq_len) — input sequence. + Returns: + (batch, seq_len) — regime-modulated output. + """ + L = x.shape[1] + device = x.device + + A = torch.exp(self.log_A) # decay rates in (0, 1) + + # Build causal convolution kernel: K[n] = sum_d C[d] * A[d]^n * B[d] + n = torch.arange(L, device=device, dtype=x.dtype) + # A^n for each state dim: (L, d_state) + A_powers = A.unsqueeze(0) ** n.unsqueeze(1) + # K[n] = sum over d_state + CB = self.C * self.B # (d_state,) + K = (A_powers * CB.unsqueeze(0)).sum(dim=1) # (L,) + + # Causal convolution via FFT (pad to avoid circular) + fft_size = 2 * L + K_f = torch.fft.rfft(K, n=fft_size) + x_f = torch.fft.rfft(x, n=fft_size, dim=-1) + y = torch.fft.irfft(x_f * K_f.unsqueeze(0), n=fft_size, dim=-1)[..., :L] + + return y + self.D * x + + +# --------------------------------------------------------------------------- +# 2+3. Enhanced Chernoff Layer (FNO + SDE) +# --------------------------------------------------------------------------- + +class EnhancedRemizovLayer(nn.Module): + """Chernoff step with optional FNO spectral correction and SDE noise. + + Base physics: S(τ) = S₃(τ) · S₂(τ) + + FNO: learnable spectral correction on S₂ kernel + + SDE: learnable σ(x)·√τ·ε noise injection after S₃ + """ + + def __init__( + self, + grid_size: int, + tau: float = 0.1, + dx: float = 1.0, + use_fno: bool = False, + use_sde: bool = False, + ): + super().__init__() + self.grid_size = grid_size + self.tau = tau + self.dx = dx + self.use_fno = use_fno + self.use_sde = use_sde + + # --- ODE coefficients (same as original) --- + self.log_a = nn.Parameter(torch.zeros(grid_size)) + self.b = nn.Parameter(torch.zeros(grid_size)) + self.c = nn.Parameter(torch.zeros(grid_size)) + + # --- FNO: learnable spectral correction --- + if use_fno: + # Correction applied as: kernel = physics_kernel * (1 + correction) + # Initialized to 0 → starts exactly as physics kernel + self.fno_real = nn.Parameter(torch.zeros(grid_size)) + self.fno_imag = nn.Parameter(torch.zeros(grid_size)) + + # --- SDE: learnable volatility --- + if use_sde: + # Start with small noise: softplus(-3) ≈ 0.05 + self.log_sigma = nn.Parameter(torch.full((grid_size,), -3.0)) + + @property + def a(self) -> Tensor: + return f_nn.softplus(self.log_a) + 1e-6 + + @property + def potential(self) -> Tensor: + return self.c - self.b ** 2 / (4.0 * self.a) + + @property + def sigma(self) -> Tensor: + return f_nn.softplus(self.log_sigma) + 1e-6 + + def _apply_s2(self, f: Tensor) -> Tensor: + """S₂ with optional FNO spectral correction.""" + a_mean = self.a.mean() + b_mean = self.b.mean() + sigma2 = 4.0 * self.tau * a_mean + + k = torch.fft.fftfreq(self.grid_size, d=self.dx, device=f.device) + + # Physics-based kernel + gauss_ft = torch.exp(-sigma2 * (math.pi * k) ** 2) + drift_ft = torch.exp(2j * math.pi * k * b_mean * self.tau) + kernel = gauss_ft * drift_ft + + # FNO correction: kernel *= (1 + learned_correction) + if self.use_fno: + correction = torch.complex( + 1.0 + self.fno_real, + self.fno_imag, + ) + kernel = kernel * correction + + f_ft = torch.fft.fft(f, dim=-1) + result = torch.fft.ifft(f_ft * kernel.unsqueeze(0), dim=-1).real + + # Completion-of-square factor + completion = torch.exp(self.b ** 2 * self.tau / (4.0 * self.a)) + result = result * completion.unsqueeze(0) + + return result + + def _apply_s3(self, f: Tensor) -> Tensor: + return f * torch.exp(self.tau * self.potential).unsqueeze(0) + + def forward(self, f: Tensor, stochastic: bool = True) -> Tensor: + """One Chernoff step: S₃ · S₂ + optional noise.""" + f = self._apply_s2(f) + f = self._apply_s3(f) + + # SDE noise injection: σ(x) · √τ · ε + if self.use_sde and stochastic: + noise = torch.randn_like(f) * self.sigma.unsqueeze(0) * math.sqrt(self.tau) + f = f + noise + + return f + + +# --------------------------------------------------------------------------- +# Combined model +# --------------------------------------------------------------------------- + +class EnhancedRemizovNet(nn.Module): + """RemizovNet with configurable SSM/FNO/SDE enhancements. + + Architecture: + [SSM encoder] → [EnhancedChernoffLayer × n_steps] → output + + Each enhancement is toggleable for clean ablation studies. + """ + + def __init__( + self, + grid_size: int, + n_steps: int = 20, + total_time: float = 0.5, + dx: float = 1.0, + use_ssm: bool = False, + use_fno: bool = False, + use_sde: bool = False, + d_state: int = 8, + ): + super().__init__() + self.grid_size = grid_size + self.n_steps = n_steps + self.use_ssm = use_ssm + + tau = total_time / n_steps + + # SSM regime encoder + if use_ssm: + self.ssm = DiagonalSSM(d_state=d_state) + + # Shared Chernoff layer (all steps share weights) + self.layer = EnhancedRemizovLayer( + grid_size, tau=tau, dx=dx, + use_fno=use_fno, use_sde=use_sde, + ) + + def forward(self, g: Tensor, stochastic: bool = True) -> Tensor: + """ + Args: + g: (batch, grid_size) — input windows. + stochastic: whether to inject SDE noise. + Returns: + (batch, grid_size) — predicted evolved windows. + """ + f = g + + # SSM pre-processing + if self.use_ssm: + f = self.ssm(f) + + # Chernoff composition + for _ in range(self.n_steps): + f = self.layer(f, stochastic=stochastic) + + return f + + def get_coefficients(self) -> dict[str, Tensor]: + return { + "a": self.layer.a.detach(), + "b": self.layer.b.detach(), + "c": self.layer.c.detach(), + } + + def equation_string(self, precision: int = 3) -> str: + coeffs = self.get_coefficients() + a_m = coeffs["a"].mean().item() + b_m = coeffs["b"].mean().item() + c_m = coeffs["c"].mean().item() + parts = [f"{a_m:.{precision}f}*y''", f"{b_m:.{precision}f}*y'", f"({c_m:.{precision}f})*y"] + eq = " + ".join(parts) + " = g(x)" + if hasattr(self.layer, "log_sigma"): + s_m = self.layer.sigma.mean().item() + eq += f" [sigma={s_m:.{precision}f}]" + return eq + + def param_count(self) -> int: + return sum(p.numel() for p in self.parameters()) + + +# --------------------------------------------------------------------------- +# GBM-style data augmentation +# --------------------------------------------------------------------------- + +def gbm_augment( + g_windows: Tensor, + y_windows: Tensor, + labels: Tensor, + n_aug: int = 2, + noise_scale: float = 0.15, +) -> tuple[Tensor, Tensor, Tensor]: + """Heteroskedastic data augmentation mimicking GBM properties. + + Noise magnitude is proportional to local price changes (volatility), + matching the heteroskedasticity of financial time series. + + Args: + g_windows: input windows (n, grid). + y_windows: target windows (n, grid). + labels: direction labels (n,). + n_aug: number of augmented copies. + noise_scale: base noise magnitude. + + Returns: + Augmented (g, y, labels) with (1 + n_aug) × n samples. + """ + aug_g = [g_windows] + aug_y = [y_windows] + aug_labels = [labels] + + for _ in range(n_aug): + # Local volatility: |diff| of window, with floor + diff_g = torch.diff(g_windows, dim=-1, prepend=g_windows[..., :1]) + local_vol = torch.abs(diff_g).clamp(min=0.05) + + # Additive noise scaled by local volatility (heteroskedastic) + noise_g = torch.randn_like(g_windows) * local_vol * noise_scale + noise_y = torch.randn_like(y_windows) * local_vol * noise_scale + + aug_g.append(g_windows + noise_g) + aug_y.append(y_windows + noise_y) + aug_labels.append(labels.clone()) + + return torch.cat(aug_g), torch.cat(aug_y), torch.cat(aug_labels) diff --git a/src/remizov_trader/core/risk.py b/src/remizov_trader/core/risk.py new file mode 100644 index 0000000..8239cfa --- /dev/null +++ b/src/remizov_trader/core/risk.py @@ -0,0 +1,113 @@ +"""Risk management — position sizing, circuit breaker, ATR.""" + +from __future__ import annotations + +import numpy as np + +from ..config import CircuitBreakerConfig, RiskConfig + + +def compute_atr(prices: np.ndarray, idx: int, period: int = 14) -> float: + """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 float(np.mean(trs)) if trs else prices[idx] * 0.02 + + +def calculate_position(equity: float, entry_price: float, stop_dist: float, + risk_cfg: RiskConfig) -> tuple[float, float]: + """Calculate position size and value. + + Returns (pos_size, pos_value). + """ + risk_amount = equity * risk_cfg.per_trade + pos_size = risk_amount / stop_dist + pos_value = pos_size * entry_price + + max_pos = equity * risk_cfg.max_position_pct + if pos_value > max_pos: + pos_size = max_pos / entry_price + pos_value = max_pos + + return pos_size, pos_value + + +def calculate_stop(prices: np.ndarray, idx: int, entry_price: float, + direction: int) -> tuple[float, float]: + """Calculate stop distance and stop price using ATR. + + Returns (stop_dist, stop_price). + """ + atr = compute_atr(prices, idx) + stop_dist = max(atr * 2.0, entry_price * 0.005) + stop_price = entry_price - direction * stop_dist + return stop_dist, stop_price + + +def update_trailing_stop(current_price: float, best_price: float, stop_price: float, + stop_dist: float, direction: int) -> tuple[float, float]: + """Update trailing stop. Returns (new_best_price, new_stop_price).""" + if direction == 1: + best_price = max(best_price, current_price) + new_stop = best_price - stop_dist + stop_price = max(stop_price, new_stop) + else: + best_price = min(best_price, current_price) + new_stop = best_price + stop_dist + stop_price = min(stop_price, new_stop) + return best_price, stop_price + + +def is_stopped(price: float, stop_price: float, direction: int) -> bool: + """Check if price hit the stop.""" + if direction == 1: + return price <= stop_price + return price >= stop_price + + +def check_circuit_breaker(prices: np.ndarray, equity: float, peak_equity: float, + was_active: bool, cb_cfg: CircuitBreakerConfig + ) -> tuple[bool, str | None, dict]: + """Check if circuit breaker should be active. + + Returns (is_active, reason, details). + """ + 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 + + dd = 1.0 - equity / peak_equity if peak_equity > 0 else 0.0 + + # Trigger ON + if atr_ratio > cb_cfg.atr_ratio_on: + return True, "atr_spike", { + "atr14": round(atr14, 2), "atr50": round(atr50, 2), + "ratio": round(atr_ratio, 2), + } + if dd > cb_cfg.max_drawdown: + return True, "drawdown", { + "equity": round(equity, 2), "peak": round(peak_equity, 2), + "dd_pct": round(dd * 100, 1), + } + + # Hysteresis: stay active if not yet recovered + if was_active: + if atr_ratio > cb_cfg.atr_ratio_off: + return True, "atr_recovering", {"ratio": round(atr_ratio, 2)} + if dd > cb_cfg.dd_reset: + return True, "dd_recovering", {"dd_pct": round(dd * 100, 1)} + + return False, None, {} + + +def calculate_pnl(entry_price: float, exit_price: float, direction: int, + pos_size: float, pos_value: float, + commission: float = 0.001) -> tuple[float, float]: + """Calculate PnL. Returns (pnl_net, pnl_pct).""" + 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 + return pnl_net, pnl_pct diff --git a/src/remizov_trader/core/signals.py b/src/remizov_trader/core/signals.py new file mode 100644 index 0000000..5793853 --- /dev/null +++ b/src/remizov_trader/core/signals.py @@ -0,0 +1,99 @@ +"""Signal generation — shape confirmation, direction detection, data prep.""" + +from __future__ import annotations + +import numpy as np +import yfinance as yf + +from ..config import AssetConfig, ModelConfig + + +def fetch_prices(ticker: str, interval: str = "1d", period: str = "max"): + """Fetch close prices and dates from yfinance.""" + hist = yf.Ticker(ticker).history(period=period, interval=interval) + if hist.empty: + return None, None + close = hist["Close"].dropna().values.astype(np.float64) + dates = [d.date() if hasattr(d, "date") else d for d in hist["Close"].dropna().index] + return close, dates + + +def prepare_windows(prices: np.ndarray, window_size: int, shift: int) -> list[dict]: + """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, + "future_prices": future, + "mu": float(mu), + "std": float(std), + "price_idx": t, + }) + return data + + +def check_shape_confirmation(pred_new: np.ndarray, confirm_prices: np.ndarray, + mu: float, std: float, K: int, + corr_thresh: float) -> tuple[float, bool]: + """Check if predicted shape matches actual first K bars. + + Returns (correlation, is_confirmed). + """ + pred_confirm = pred_new[:K] + if len(pred_confirm) < 2: + return 0.0, False + + actual_norm = (confirm_prices[:K] - mu) / std + corr = np.corrcoef(pred_confirm, actual_norm)[0, 1] + + if np.isnan(corr): + return 0.0, False + + return float(corr), corr >= corr_thresh + + +def get_direction(pred_new: np.ndarray, K: int) -> int | None: + """Get predicted direction from the prediction array. + + Returns 1 (long), -1 (short), or None if indeterminate. + """ + pred_direction = pred_new[-1] - pred_new[K - 1] + if abs(pred_direction) < 1e-10: + return None + return 1 if pred_direction > 0 else -1 + + +def get_latest_signal_window(prices: np.ndarray, window_size: int, K: int): + """Get window for checking current signal (ends K bars ago for confirmation). + + Returns (norm_input, confirm_prices, mu, std, price_idx) or None. + """ + if len(prices) < window_size + K: + return None + + w = prices[-(window_size + K):-K].copy() + confirm_prices = prices[-K:].copy() + + mu, std = w.mean(), w.std() + if std < 1e-10: + return None + + norm_input = (w - mu) / std + return { + "norm_input": norm_input, + "confirm_prices": confirm_prices, + "mu": float(mu), + "std": float(std), + "price_idx": len(prices) - 1, + "last_price": float(prices[-1]), + } diff --git a/src/remizov_trader/state.py b/src/remizov_trader/state.py new file mode 100644 index 0000000..e836a48 --- /dev/null +++ b/src/remizov_trader/state.py @@ -0,0 +1,221 @@ +"""SQLite state management — trades, positions, equity, signals, CB events.""" + +from __future__ import annotations + +import sqlite3 +from datetime import datetime +from pathlib import Path + +DB_PATH = Path(__file__).parent.parent.parent / "data" / "trades.db" + + +def get_db(path: Path | None = None) -> sqlite3.Connection: + """Get database connection with row factory.""" + path = path or DB_PATH + path.parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(str(path)) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA foreign_keys=ON") + return conn + + +def init_db(conn: sqlite3.Connection) -> None: + """Create tables if they don't exist.""" + conn.executescript(""" + CREATE TABLE IF NOT EXISTS assets ( + ticker TEXT PRIMARY KEY, + equity REAL NOT NULL, + peak_equity REAL NOT NULL, + trades_count INTEGER DEFAULT 0, + wins INTEGER DEFAULT 0, + losses INTEGER DEFAULT 0, + total_pnl REAL DEFAULT 0.0, + signals_since_retrain INTEGER DEFAULT 0, + last_train_date TEXT, + cb_active INTEGER DEFAULT 0, + cb_reason TEXT, + created_at TEXT DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS positions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ticker TEXT NOT NULL, + direction INTEGER NOT NULL, -- 1=long, -1=short + entry_price REAL NOT NULL, + entry_date TEXT NOT NULL, + stop_price REAL NOT NULL, + stop_dist REAL NOT NULL, + best_price REAL NOT NULL, + pos_size REAL NOT NULL, + pos_value REAL NOT NULL, + correlation REAL, + k_used INTEGER DEFAULT 2, + status TEXT DEFAULT 'open', -- open | closed + exit_price REAL, + exit_date TEXT, + exit_reason TEXT, -- stop | time | manual + pnl_net REAL, + pnl_pct REAL, + created_at TEXT DEFAULT (datetime('now')), + FOREIGN KEY (ticker) REFERENCES assets(ticker) + ); + + CREATE TABLE IF NOT EXISTS signals ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ticker TEXT NOT NULL, + date TEXT NOT NULL, + correlation REAL, + direction INTEGER, + action TEXT NOT NULL, -- open | skip_corr | skip_cb | skip_astro + details TEXT, + created_at TEXT DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS equity_snapshots ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ticker TEXT NOT NULL, + equity REAL NOT NULL, + price REAL, + date TEXT NOT NULL, + created_at TEXT DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS cb_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ticker TEXT NOT NULL, + action TEXT NOT NULL, -- on | off + reason TEXT, + details TEXT, + created_at TEXT DEFAULT (datetime('now')) + ); + + CREATE INDEX IF NOT EXISTS idx_positions_ticker ON positions(ticker); + CREATE INDEX IF NOT EXISTS idx_positions_status ON positions(status); + CREATE INDEX IF NOT EXISTS idx_signals_ticker ON signals(ticker); + CREATE INDEX IF NOT EXISTS idx_equity_ticker ON equity_snapshots(ticker); + """) + conn.commit() + + +# -- Asset CRUD -- + +def upsert_asset(conn: sqlite3.Connection, ticker: str, equity: float) -> None: + conn.execute(""" + INSERT INTO assets (ticker, equity, peak_equity) + VALUES (?, ?, ?) + ON CONFLICT(ticker) DO UPDATE SET equity=?, peak_equity=MAX(peak_equity, ?) + """, (ticker, equity, equity, equity, equity)) + conn.commit() + + +def get_asset(conn: sqlite3.Connection, ticker: str) -> dict | None: + row = conn.execute("SELECT * FROM assets WHERE ticker=?", (ticker,)).fetchone() + return dict(row) if row else None + + +def get_all_assets(conn: sqlite3.Connection) -> list[dict]: + rows = conn.execute("SELECT * FROM assets ORDER BY ticker").fetchall() + return [dict(r) for r in rows] + + +def update_asset(conn: sqlite3.Connection, ticker: str, **kwargs) -> None: + sets = ", ".join(f"{k}=?" for k in kwargs) + vals = list(kwargs.values()) + [ticker] + conn.execute(f"UPDATE assets SET {sets} WHERE ticker=?", vals) + conn.commit() + + +# -- Position CRUD -- + +def open_position(conn: sqlite3.Connection, **kwargs) -> int: + cols = ", ".join(kwargs.keys()) + placeholders = ", ".join("?" for _ in kwargs) + cur = conn.execute( + f"INSERT INTO positions ({cols}) VALUES ({placeholders})", + list(kwargs.values()), + ) + conn.commit() + return cur.lastrowid + + +def get_open_position(conn: sqlite3.Connection, ticker: str) -> dict | None: + row = conn.execute( + "SELECT * FROM positions WHERE ticker=? AND status='open' ORDER BY id DESC LIMIT 1", + (ticker,), + ).fetchone() + return dict(row) if row else None + + +def close_position(conn: sqlite3.Connection, pos_id: int, **kwargs) -> None: + kwargs["status"] = "closed" + sets = ", ".join(f"{k}=?" for k in kwargs) + vals = list(kwargs.values()) + [pos_id] + conn.execute(f"UPDATE positions SET {sets} WHERE id=?", vals) + conn.commit() + + +def update_position(conn: sqlite3.Connection, pos_id: int, **kwargs) -> None: + sets = ", ".join(f"{k}=?" for k in kwargs) + vals = list(kwargs.values()) + [pos_id] + conn.execute(f"UPDATE positions SET {sets} WHERE id=?", vals) + conn.commit() + + +def get_trade_history(conn: sqlite3.Connection, ticker: str | None = None, + limit: int = 100) -> list[dict]: + if ticker: + rows = conn.execute( + "SELECT * FROM positions WHERE ticker=? AND status='closed' " + "ORDER BY id DESC LIMIT ?", (ticker, limit), + ).fetchall() + else: + rows = conn.execute( + "SELECT * FROM positions WHERE status='closed' ORDER BY id DESC LIMIT ?", + (limit,), + ).fetchall() + return [dict(r) for r in rows] + + +# -- Signals -- + +def log_signal(conn: sqlite3.Connection, **kwargs) -> None: + cols = ", ".join(kwargs.keys()) + placeholders = ", ".join("?" for _ in kwargs) + conn.execute(f"INSERT INTO signals ({cols}) VALUES ({placeholders})", list(kwargs.values())) + conn.commit() + + +# -- Equity snapshots -- + +def add_equity_snapshot(conn: sqlite3.Connection, ticker: str, equity: float, + price: float, date: str) -> None: + conn.execute( + "INSERT INTO equity_snapshots (ticker, equity, price, date) VALUES (?,?,?,?)", + (ticker, equity, price, date), + ) + conn.commit() + + +def get_equity_history(conn: sqlite3.Connection, ticker: str | None = None) -> list[dict]: + if ticker: + rows = conn.execute( + "SELECT * FROM equity_snapshots WHERE ticker=? ORDER BY date", (ticker,), + ).fetchall() + else: + rows = conn.execute( + "SELECT date, SUM(equity) as equity FROM equity_snapshots " + "GROUP BY date ORDER BY date", + ).fetchall() + return [dict(r) for r in rows] + + +# -- CB events -- + +def log_cb_event(conn: sqlite3.Connection, ticker: str, action: str, + reason: str = "", details: str = "") -> None: + conn.execute( + "INSERT INTO cb_events (ticker, action, reason, details) VALUES (?,?,?,?)", + (ticker, action, reason, details), + ) + conn.commit() diff --git a/src/remizov_trader/web/__init__.py b/src/remizov_trader/web/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/remizov_trader/web/app.py b/src/remizov_trader/web/app.py new file mode 100644 index 0000000..c7ccad0 --- /dev/null +++ b/src/remizov_trader/web/app.py @@ -0,0 +1,147 @@ +"""FastAPI web dashboard with Jinja2 + HTMX.""" + +from __future__ import annotations + +from pathlib import Path + +from fastapi import FastAPI, Request +from fastapi.responses import HTMLResponse +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates + +from ..config import Config +from ..state import ( + get_db, init_db, get_all_assets, get_open_position, + get_trade_history, get_equity_history, +) + +TEMPLATES_DIR = Path(__file__).parent / "templates" +STATIC_DIR = Path(__file__).parent / "static" + + +def create_app(cfg: Config) -> FastAPI: + app = FastAPI(title="RemizovTrader", version="0.1.0") + templates = Jinja2Templates(directory=str(TEMPLATES_DIR)) + + if STATIC_DIR.exists(): + app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") + + @app.get("/", response_class=HTMLResponse) + async def dashboard(request: Request): + conn = get_db() + init_db(conn) + + assets = get_all_assets(conn) + positions = {} + for a in assets: + pos = get_open_position(conn, a["ticker"]) + if pos: + positions[a["ticker"]] = dict(pos) + + total_equity = sum(a["equity"] for a in assets) + total_initial = cfg.initial_capital * len(cfg.assets) + total_pnl = total_equity - total_initial + total_ret = (total_equity / total_initial - 1) * 100 if total_initial > 0 else 0 + + equity_data = get_equity_history(conn) + recent_trades = get_trade_history(conn, limit=10) + + conn.close() + + return templates.TemplateResponse("dashboard.html", { + "request": request, + "cfg": cfg, + "assets": assets, + "positions": positions, + "total_equity": total_equity, + "total_pnl": total_pnl, + "total_ret": total_ret, + "equity_data": equity_data, + "recent_trades": recent_trades, + }) + + @app.get("/positions", response_class=HTMLResponse) + async def positions_page(request: Request): + conn = get_db() + init_db(conn) + + assets = get_all_assets(conn) + positions = [] + for a in assets: + pos = get_open_position(conn, a["ticker"]) + if pos: + positions.append({**dict(pos), "equity": a["equity"]}) + + conn.close() + + return templates.TemplateResponse("positions.html", { + "request": request, + "positions": positions, + }) + + @app.get("/history", response_class=HTMLResponse) + async def history_page(request: Request): + conn = get_db() + init_db(conn) + trades = get_trade_history(conn, limit=200) + conn.close() + + return templates.TemplateResponse("history.html", { + "request": request, + "trades": trades, + }) + + @app.get("/settings", response_class=HTMLResponse) + async def settings_page(request: Request): + return templates.TemplateResponse("settings.html", { + "request": request, + "cfg": cfg, + }) + + # HTMX partial endpoints + @app.get("/api/equity-chart", response_class=HTMLResponse) + async def equity_chart_data(request: Request): + conn = get_db() + init_db(conn) + data = get_equity_history(conn) + conn.close() + + return templates.TemplateResponse("partials/equity_chart.html", { + "request": request, + "equity_data": data, + }) + + @app.get("/api/positions-table", response_class=HTMLResponse) + async def positions_table(request: Request): + conn = get_db() + init_db(conn) + + assets = get_all_assets(conn) + positions = [] + for a in assets: + pos = get_open_position(conn, a["ticker"]) + if pos: + positions.append({**dict(pos), "equity": a["equity"]}) + + conn.close() + + return templates.TemplateResponse("partials/positions_table.html", { + "request": request, + "positions": positions, + }) + + @app.post("/api/run-cycle", response_class=HTMLResponse) + async def run_cycle_api(request: Request): + from ..core.executor import run_cycle + + conn = get_db() + init_db(conn) + logs = run_cycle(conn, cfg) + conn.close() + + return templates.TemplateResponse("partials/cycle_result.html", { + "request": request, + "logs": logs, + }) + + return app diff --git a/src/remizov_trader/web/templates/base.html b/src/remizov_trader/web/templates/base.html new file mode 100644 index 0000000..38920b9 --- /dev/null +++ b/src/remizov_trader/web/templates/base.html @@ -0,0 +1,79 @@ + + + + + + RemizovTrader{% block title_suffix %}{% endblock %} + + + + + + + + +
+ {% block content %}{% endblock %} +
+ +
+ RemizovTrader v0.1.0 — PDE/SDE Neural ODE +
+ + {% block scripts %}{% endblock %} + + diff --git a/src/remizov_trader/web/templates/dashboard.html b/src/remizov_trader/web/templates/dashboard.html new file mode 100644 index 0000000..d0f0e34 --- /dev/null +++ b/src/remizov_trader/web/templates/dashboard.html @@ -0,0 +1,160 @@ +{% extends "base.html" %} +{% block title_suffix %} — Dashboard{% endblock %} + +{% block content %} +

Dashboard

+ + +
+
+
${{ "%.2f"|format(total_equity) }}
+
Total Equity
+
+
+
+ ${{ "%+.2f"|format(total_pnl) }} +
+
PnL ({{ "%+.1f"|format(total_ret) }}%)
+
+
+
{{ positions|length }}
+
Open Positions
+
+
+
{{ assets|map(attribute='trades_count')|sum }}
+
Total Trades
+
+
+ + +
+
Equity Curve
+
+ +
+
+ + +
+
Assets
+ + + + + + + + + + + + + + {% for a in assets %} + + + + + + + + + + {% endfor %} + +
AssetEquityPnLTradesWin RatePositionCB
{{ a.ticker }}${{ "%.2f"|format(a.equity) }} + ${{ "%+.2f"|format(a.total_pnl) }} + {{ a.trades_count }} ({{ a.wins }}W/{{ a.losses }}L){{ "%.0f"|format(a.wins / a.trades_count * 100) if a.trades_count > 0 else '—' }}% + {% if a.ticker in positions %} + {% set p = positions[a.ticker] %} + + {{ 'LONG' if p.direction == 1 else 'SHORT' }} + + ${{ "%.0f"|format(p.entry_price) }} + {% else %} + — + {% endif %} + + {% if a.cb_active %} + ON + {% else %} + — + {% endif %} +
+
+ + +
+
Recent Trades
+ {% if recent_trades %} + + + + + + {% for t in recent_trades %} + + + + + + + + + + {% endfor %} + +
DateAssetDirEntryExitPnLReason
{{ t.entry_date }}{{ t.ticker }} + + {{ 'L' if t.direction == 1 else 'S' }} + + ${{ "%.2f"|format(t.entry_price) }}${{ "%.2f"|format(t.exit_price or 0) }} + ${{ "%+.2f"|format(t.pnl_net or 0) }} + {{ t.exit_reason or '' }}
+ {% else %} +

No trades yet. Run a trading cycle first.

+ {% endif %} +
+ + +
+ +
+
+{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/src/remizov_trader/web/templates/history.html b/src/remizov_trader/web/templates/history.html new file mode 100644 index 0000000..6c7dfe5 --- /dev/null +++ b/src/remizov_trader/web/templates/history.html @@ -0,0 +1,55 @@ +{% extends "base.html" %} +{% block title_suffix %} — History{% endblock %} + +{% block content %} +

Trade History

+ +{% if trades %} + + + + + + + + + + + + + + + + {% for t in trades %} + + + + + + + + + + + + {% endfor %} + +
DateAssetDirectionEntryExitPnL ($)PnL (%)ReasonDays
{{ t.entry_date }}{{ t.ticker }} + + {{ 'LONG' if t.direction == 1 else 'SHORT' }} + + ${{ "%.2f"|format(t.entry_price) }}${{ "%.2f"|format(t.exit_price or 0) }} + ${{ "%+.2f"|format(t.pnl_net or 0) }} + + {{ "%+.2f"|format(t.pnl_pct or 0) }}% + {{ t.exit_reason or '' }} + {% if t.entry_date and t.exit_date %} + {{ (t.exit_date | string)[:10] }} + {% endif %} +
+{% else %} +
+

No trades yet.

+
+{% endif %} +{% endblock %} diff --git a/src/remizov_trader/web/templates/partials/cycle_result.html b/src/remizov_trader/web/templates/partials/cycle_result.html new file mode 100644 index 0000000..4208a68 --- /dev/null +++ b/src/remizov_trader/web/templates/partials/cycle_result.html @@ -0,0 +1,13 @@ +
+
Cycle Result
+ {% if logs %} +
    + {% for msg in logs %} +
  • {{ msg }}
  • + {% endfor %} +
+ {% else %} +

No events.

+ {% endif %} + Refresh page to see updated data. +
diff --git a/src/remizov_trader/web/templates/partials/equity_chart.html b/src/remizov_trader/web/templates/partials/equity_chart.html new file mode 100644 index 0000000..bc9851d --- /dev/null +++ b/src/remizov_trader/web/templates/partials/equity_chart.html @@ -0,0 +1,4 @@ + diff --git a/src/remizov_trader/web/templates/partials/positions_table.html b/src/remizov_trader/web/templates/partials/positions_table.html new file mode 100644 index 0000000..5195d42 --- /dev/null +++ b/src/remizov_trader/web/templates/partials/positions_table.html @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + {% for p in positions %} + + + + + + + + + + {% endfor %} + +
AssetDirectionEntryStopCorrelationDayEquity
{{ p.ticker }} + + {{ 'LONG' if p.direction == 1 else 'SHORT' }} + + ${{ "%.2f"|format(p.entry_price) }}${{ "%.2f"|format(p.stop_price) }}{{ "%.3f"|format(p.correlation or 0) }}{{ p.entry_date }}${{ "%.2f"|format(p.equity) }}
diff --git a/src/remizov_trader/web/templates/positions.html b/src/remizov_trader/web/templates/positions.html new file mode 100644 index 0000000..9c6e68f --- /dev/null +++ b/src/remizov_trader/web/templates/positions.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} +{% block title_suffix %} — Positions{% endblock %} + +{% block content %} +

Open Positions

+ +{% if positions %} +
+ {% include "partials/positions_table.html" %} +
+{% else %} +
+

No open positions.

+
+{% endif %} +{% endblock %} diff --git a/src/remizov_trader/web/templates/settings.html b/src/remizov_trader/web/templates/settings.html new file mode 100644 index 0000000..664e513 --- /dev/null +++ b/src/remizov_trader/web/templates/settings.html @@ -0,0 +1,82 @@ +{% extends "base.html" %} +{% block title_suffix %} — Settings{% endblock %} + +{% block content %} +

Settings

+ +
+
General
+
+
+ + +
+
+ + +
+
+ + +
+
+
+ +
+
Risk Management
+
+
+ + +
+
+ + +
+
+ + +
+
+
+ +
+
Circuit Breaker
+
+
+ + +
+
+ + +
+
+ + +
+
+
+ +
+
Assets
+ + + + + + {% for a in cfg.assets %} + + + + + + + + {% endfor %} + +
TickerBinanceKCorr ThreshTrailing
{{ a.ticker }}{{ a.binance_symbol }}{{ a.K }}{{ a.corr_thresh }}{{ 'Yes' if a.trailing_stop else 'No' }}
+
+ +

Edit config.yaml to change settings, then restart.

+{% endblock %}