#!/usr/bin/env python3 import argparse, fcntl, json, math, time from dataclasses import dataclass from datetime import datetime from pathlib import Path from urllib.request import Request, urlopen from zoneinfo import ZoneInfo ROOT = Path(__file__).resolve().parent DATA = ROOT / "data" STATE_PATH = DATA / "state.json" TRADES_PATH = DATA / "trades.jsonl" CONFIG_PATH = ROOT / "config.json" LOCK_PATH = DATA / "scan.lock" LOCAL_TZ = ZoneInfo("America/New_York") @dataclass class Candle: ts: int low: float high: float open: float close: float volume: float def now_iso(): return datetime.now(LOCAL_TZ).isoformat() def load_config(): return json.loads(CONFIG_PATH.read_text()) def default_state(cfg): return { "created_at": now_iso(), "updated_at": now_iso(), "mode": "paper", "cash_usd": float(cfg["starting_cash_usd"]), "starting_cash_usd": float(cfg["starting_cash_usd"]), "realized_pnl_usd": 0.0, "equity_high_watermark_usd": float(cfg["starting_cash_usd"]), "positions": {}, "last_trade_at": {}, "shadow_positions": {}, "shadow_last_trade_at": {}, "shadow_realized_pnl_usd": 0.0, "daily": {"date": datetime.now(LOCAL_TZ).date().isoformat(), "realized_pnl_usd": 0.0, "starting_equity_usd": float(cfg["starting_cash_usd"]), "blocked": False}, "last_scan": None, "last_signals": [] } def load_state(cfg): DATA.mkdir(exist_ok=True) if not STATE_PATH.exists(): st = default_state(cfg); save_state(st); return st return json.loads(STATE_PATH.read_text()) def save_state(st): st["updated_at"] = now_iso() tmp = STATE_PATH.with_suffix(".json.tmp") tmp.write_text(json.dumps(st, indent=2, sort_keys=True)) tmp.replace(STATE_PATH) def log_event(event): DATA.mkdir(exist_ok=True) with TRADES_PATH.open("a") as f: f.write(json.dumps({"ts": now_iso(), **event}, sort_keys=True) + "\n") def http_json(url, timeout=20): req = Request(url, headers={"User-Agent": "local-paper-trading-agent/0.1"}) with urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode()) def fetch_coinbase_candles(symbol, hours, granularity): end = int(time.time()) start = end - int(hours * 3600) start_s = datetime.fromtimestamp(start, LOCAL_TZ).isoformat() end_s = datetime.fromtimestamp(end, LOCAL_TZ).isoformat() url = f"https://api.exchange.coinbase.com/products/{symbol}/candles?granularity={granularity}&start={start_s}&end={end_s}" raw = http_json(url) candles = [Candle(int(x[0]), float(x[1]), float(x[2]), float(x[3]), float(x[4]), float(x[5])) for x in raw] candles = [c for c in candles if c.ts + granularity <= end] candles.sort(key=lambda c: c.ts) if candles and end - (candles[-1].ts + granularity) > granularity * 2: raise RuntimeError(f"stale candles for {symbol}") if any(not all(math.isfinite(v) and v > 0 for v in (c.open, c.high, c.low, c.close)) or c.low > min(c.open, c.close) or c.high < max(c.open, c.close) for c in candles): raise RuntimeError(f"invalid candles for {symbol}") if len(candles) < 10: raise RuntimeError(f"not enough candles for {symbol}: {len(candles)}") return candles def ema(values, span): alpha = 2 / (span + 1) out = values[0] for v in values[1:]: out = alpha * v + (1 - alpha) * out return out def vwap(candles): total_vol = sum(c.volume for c in candles) if total_vol <= 0: return candles[-1].close return sum(((c.high + c.low + c.close) / 3) * c.volume for c in candles) / total_vol def volatility_pct(candles): closes = [c.close for c in candles] rets = [math.log(closes[i] / closes[i-1]) for i in range(1, len(closes)) if closes[i-1] > 0] if len(rets) < 2: return 1.0 mean = sum(rets) / len(rets) var = sum((r - mean) ** 2 for r in rets) / (len(rets) - 1) return max(0.01, math.sqrt(var) * 100) def fair_value(candles): closes = [c.close for c in candles] return 0.45 * ema(closes, min(12, len(closes))) + 0.35 * ema(closes, min(48, len(closes))) + 0.20 * vwap(candles) def dollar_volume(candles): return sum(((c.high + c.low + c.close) / 3) * c.volume for c in candles) def rebound_metrics(candles): price = candles[-1].close recent = candles[-4:] if len(candles) >= 4 else candles recent_low = min(c.low for c in recent) rebound_pct = (price / recent_low - 1) * 100 if recent_low > 0 else 0.0 hour = candles[-12:] if len(candles) >= 12 else candles hour_open = hour[0].open hour_change_pct = (price / hour_open - 1) * 100 if hour_open > 0 else 0.0 return rebound_pct, hour_change_pct def day_change_pct(candles): first = candles[0].open last = candles[-1].close return (last / first - 1) * 100 if first > 0 else 0.0 def pullback_gap_pct(candles): """Major-coin dip signal: percent below recent highs. Fair-value EMA gap is often zero for large coins during broad market moves, so majors can sit blocked forever. Use a conservative fraction of the 6h/24h pullback as the actionable dip, while existing rebound/dump filters still block falling knives. """ price = candles[-1].close if price <= 0: return 0.0 high_6h = max(c.high for c in candles[-72:]) if len(candles) >= 72 else max(c.high for c in candles) high_24h = max(c.high for c in candles) pull_6h = max(0.0, (high_6h / price - 1) * 100) pull_24h = max(0.0, (high_24h / price - 1) * 100) return max(0.65 * pull_6h, 0.35 * pull_24h) def equity(st, prices): eq = float(st["cash_usd"]) for sym, pos in st.get("positions", {}).items(): px = prices.get(sym, pos.get("last_price", pos["avg_entry"])) eq += float(pos["qty"]) * px return eq def roll_daily(st, eq): today = datetime.now(LOCAL_TZ).date().isoformat() if st.get("daily", {}).get("date") != today: st["daily"] = {"date": today, "realized_pnl_usd": 0.0, "starting_equity_usd": eq, "blocked": False} # Existing accounts migrate without discarding today's realized losses. st["daily"].setdefault("starting_equity_usd", float((st.get("last_scan") or {}).get("equity_usd", st["starting_cash_usd"]))) st["daily"].setdefault("blocked", False) def daily_loss_blocked(st, cfg, eq): roll_daily(st, eq) high = max(float(st.get("equity_high_watermark_usd", eq)), eq) st["equity_high_watermark_usd"] = high baseline = float(st["daily"]["starting_equity_usd"]) daily_loss = max(baseline - eq, -float(st["daily"]["realized_pnl_usd"])) if daily_loss >= baseline * abs(cfg["max_daily_loss_pct"]) / 100: st["daily"]["blocked"] = True if st["daily"]["blocked"]: return True, "daily_loss_limit" dd = (high - eq) / high * 100 if high > 0 else 0 if dd >= cfg["max_drawdown_pct"]: return True, "max_drawdown" return False, None def in_cooldown(st, cfg, sym): last = st.get("last_trade_at", {}).get(sym) if not last: return False try: t = datetime.fromisoformat(last).timestamp() except Exception: return False return time.time() - t < cfg["cooldown_minutes_after_trade"] * 60 def recent_symbol_loss_blocked(cfg, sym, event_type="paper_sell"): if not TRADES_PATH.exists(): return False, None sells = [] for line in TRADES_PATH.read_text().splitlines(): if not line.strip(): continue try: ev = json.loads(line) except Exception: continue if ev.get("type") == event_type and ev.get("symbol") == sym: sells.append(ev) window = int(cfg.get("recent_symbol_window_trades", 4)) max_losses = int(cfg.get("max_recent_symbol_losses", 2)) recent = sells[-window:] losses = sum(1 for ev in recent if float(ev.get("realized_pnl_usd", 0)) < 0) if len(recent) >= max_losses and losses >= max_losses: return True, {"recent_closed": len(recent), "recent_losses": losses, "window": window} return False, None def closed_trade_stats(sym, event_types=("paper_sell",)): stats = {"closed": 0, "wins": 0, "losses": 0, "pnl": 0.0} if not TRADES_PATH.exists(): return stats for line in TRADES_PATH.read_text().splitlines(): if not line.strip(): continue try: ev = json.loads(line) except Exception: continue if ev.get("type") not in event_types or ev.get("symbol") != sym: continue pnl = float(ev.get("realized_pnl_usd", 0.0)) stats["closed"] += 1 stats["pnl"] += pnl if pnl >= 0: stats["wins"] += 1 else: stats["losses"] += 1 return stats def symbol_performance_multiplier(cfg, sym): """Scale proven winners up and unproven/weak names down. Uses closed paper trades plus shadow trades. Shadow history matters for newly promoted symbols, but live paper history dominates once it exists. """ paper = closed_trade_stats(sym, ("paper_sell",)) combined = closed_trade_stats(sym, ("paper_sell", "shadow_sell")) stats = paper if paper["closed"] >= 4 else combined closed = stats["closed"] win_rate = stats["wins"] / closed if closed else 0.0 pnl = stats["pnl"] mult = 1.0 if closed == 0: mult = 0.70 elif closed < 3: mult = 0.85 elif pnl <= 0 or win_rate < 0.55: mult = 0.60 elif closed >= 10 and pnl > 1.0 and win_rate >= 0.70: mult = 1.60 elif closed >= 3 and pnl > 0.25 and win_rate >= 0.66: mult = 1.35 return max(float(cfg.get("min_symbol_performance_multiplier", 0.5)), min(float(cfg.get("max_symbol_performance_multiplier", 1.6)), mult)) def close_position_if_needed(st, cfg, sym, price): pos = st.get("positions", {}).get(sym) if not pos: return None entry = float(pos["avg_entry"]) pnl_pct = (price - entry) / entry * 100 peak_price = max(float(pos.get("peak_price", entry)), price) pos["peak_price"] = peak_price peak_pnl_pct = (peak_price - entry) / entry * 100 if entry else 0.0 pos["highest_pnl_pct"] = max(float(pos.get("highest_pnl_pct", peak_pnl_pct)), peak_pnl_pct) trailing_trigger = float(cfg.get("trailing_stop_trigger_pct", 0.0) or 0.0) trailing_giveback = float(cfg.get("trailing_stop_giveback_pct", 0.0) or 0.0) breakeven_trigger = float(cfg.get("breakeven_stop_trigger_pct", 0.0) or 0.0) breakeven_stop = float(cfg.get("breakeven_stop_pct", 0.0) or 0.0) reason = "take_profit" if pnl_pct >= cfg["take_profit_pct"] else "stop_loss" if pnl_pct <= -abs(cfg["stop_loss_pct"]) else None if not reason and trailing_trigger > 0 and trailing_giveback > 0 and peak_pnl_pct >= trailing_trigger and pnl_pct <= peak_pnl_pct - trailing_giveback: reason = "trailing_stop" if not reason and breakeven_trigger > 0 and peak_pnl_pct >= breakeven_trigger and pnl_pct <= breakeven_stop: reason = "breakeven_stop" if not reason: pos["last_price"] = price; return None price *= 1 - float(cfg.get("slippage_bps", 0)) / 10000 qty = float(pos["qty"]); gross = qty * price; fee = gross * cfg["fee_bps"] / 10000 buy_fee = float(pos.get("buy_fee_usd", 0.0)) proceeds = gross - fee; realized = proceeds - qty * entry - buy_fee st["cash_usd"] += proceeds; st["realized_pnl_usd"] += realized; st["daily"]["realized_pnl_usd"] += realized del st["positions"][sym]; st.setdefault("last_trade_at", {})[sym] = now_iso() ev = {"type": "paper_sell", "symbol": sym, "reason": reason, "qty": qty, "price": price, "fee_usd": fee, "buy_fee_usd": buy_fee, "realized_pnl_usd": realized, "pnl_pct": pnl_pct} log_event(ev); return ev def close_shadow_position_if_needed(st, cfg, sym, price): pos = st.setdefault("shadow_positions", {}).get(sym) if not pos: return None entry = float(pos["avg_entry"]) pnl_pct = (price - entry) / entry * 100 peak_price = max(float(pos.get("peak_price", entry)), price) pos["peak_price"] = peak_price peak_pnl_pct = (peak_price - entry) / entry * 100 if entry else 0.0 pos["highest_pnl_pct"] = max(float(pos.get("highest_pnl_pct", peak_pnl_pct)), peak_pnl_pct) trailing_trigger = float(cfg.get("trailing_stop_trigger_pct", 0.0) or 0.0) trailing_giveback = float(cfg.get("trailing_stop_giveback_pct", 0.0) or 0.0) breakeven_trigger = float(cfg.get("breakeven_stop_trigger_pct", 0.0) or 0.0) breakeven_stop = float(cfg.get("breakeven_stop_pct", 0.0) or 0.0) reason = "take_profit" if pnl_pct >= cfg["take_profit_pct"] else "stop_loss" if pnl_pct <= -abs(cfg["stop_loss_pct"]) else None if not reason and trailing_trigger > 0 and trailing_giveback > 0 and peak_pnl_pct >= trailing_trigger and pnl_pct <= peak_pnl_pct - trailing_giveback: reason = "trailing_stop" if not reason and breakeven_trigger > 0 and peak_pnl_pct >= breakeven_trigger and pnl_pct <= breakeven_stop: reason = "breakeven_stop" if not reason: pos["last_price"] = price; return None price *= 1 - float(cfg.get("slippage_bps", 0)) / 10000 qty = float(pos["qty"]); gross = qty * price; fee = gross * cfg["fee_bps"] / 10000 buy_fee = float(pos.get("buy_fee_usd", 0.0)) proceeds = gross - fee; realized = proceeds - qty * entry - buy_fee st["shadow_realized_pnl_usd"] = float(st.get("shadow_realized_pnl_usd", 0.0)) + realized del st["shadow_positions"][sym] st.setdefault("shadow_last_trade_at", {})[sym] = now_iso() ev = {"type": "shadow_sell", "symbol": sym, "reason": reason, "qty": qty, "price": price, "fee_usd": fee, "buy_fee_usd": buy_fee, "realized_pnl_usd": realized, "pnl_pct": pnl_pct} log_event(ev); return ev def signal_has_fee_aware_edge(cfg, signal): round_trip_cost_pct = (2 * cfg["fee_bps"] + 2 * cfg["slippage_bps"]) / 100.0 required_gap = cfg["min_gap_pct"] + round_trip_cost_pct + cfg.get("min_edge_after_cost_pct", 0.0) if signal["gap_pct"] < required_gap: return False if signal.get("candles", 0) < cfg.get("min_candles_24h", 0): return False if signal.get("dollar_volume_24h", 0) < cfg.get("min_dollar_volume_24h", 0): return False if signal.get("day_change_pct", 0) > cfg.get("max_24h_pump_pct", 999): return False if signal.get("day_change_pct", 0) < -abs(cfg.get("max_24h_dump_pct", 999)): return False if cfg.get("require_rebound_confirmation", False): if signal.get("rebound_from_recent_low_pct", 0) < cfg.get("min_rebound_from_recent_low_pct", 0): return False if signal.get("hour_change_pct", 0) < -abs(cfg.get("max_drop_last_hour_pct", 100)): return False return True def maybe_open_position(st, cfg, signal, eq): sym = signal["symbol"] if sym in st.get("positions", {}) or in_cooldown(st, cfg, sym) or signal["gap_pct"] < cfg["min_gap_pct"]: return None blocked, loss_info = recent_symbol_loss_blocked(cfg, sym) if blocked: log_event({"type": "symbol_lockout", "symbol": sym, **(loss_info or {})}) return None if not signal_has_fee_aware_edge(cfg, signal): return None reliability = min(1.0, max(0.0, (signal["gap_pct"] - cfg["min_gap_pct"]) / max(0.01, cfg["strong_gap_pct"] - cfg["min_gap_pct"]))) reliability *= min(1.0, signal["gap_pct"] / max(signal["volatility_pct"], 0.01)) open_exposure = sum(float(p["qty"]) * float(p.get("last_price", p["avg_entry"])) for p in st.get("positions", {}).values()) max_total_exposure = eq * cfg.get("max_total_position_pct_of_equity", 1.0) remaining_exposure = max(0.0, max_total_exposure - open_exposure) performance_multiplier = symbol_performance_multiplier(cfg, sym) per_symbol_cap = eq * cfg.get("max_boosted_position_pct_of_equity", cfg["max_position_pct_of_equity"]) # Planned stop loss includes estimated entry/exit costs, not just price distance. loss_fraction = abs(cfg["stop_loss_pct"]) / 100 + (2 * cfg["fee_bps"] + 2 * cfg["slippage_bps"]) / 10000 risk_cap = eq * float(cfg.get("max_risk_per_trade_pct", 0.5)) / 100 / max(loss_fraction, 0.000001) notional = min( risk_cap, eq * cfg["max_position_pct_of_equity"] * performance_multiplier * max(0.25, reliability), per_symbol_cap, remaining_exposure, st["cash_usd"] * 0.95, ) if notional < cfg["min_trade_usd"]: return None exec_price = signal["price"] * (1 + cfg["slippage_bps"] / 10000); fee = notional * cfg["fee_bps"] / 10000 spend = notional + fee if spend > st["cash_usd"]: notional = st["cash_usd"] / (1 + cfg["fee_bps"] / 10000); fee = notional * cfg["fee_bps"] / 10000; spend = notional + fee qty = notional / exec_price st["cash_usd"] -= spend st.setdefault("positions", {})[sym] = {"qty": qty, "avg_entry": exec_price, "opened_at": now_iso(), "last_price": signal["price"], "notional_usd": notional, "buy_fee_usd": fee, "entry_gap_pct": signal["gap_pct"], "reliability": reliability, "performance_multiplier": performance_multiplier} st.setdefault("last_trade_at", {})[sym] = now_iso() ev = {"type": "paper_buy", "symbol": sym, "qty": qty, "price": exec_price, "fee_usd": fee, "notional_usd": notional, "gap_pct": signal["gap_pct"], "reliability": reliability, "performance_multiplier": performance_multiplier} log_event(ev); return ev def maybe_open_shadow_position(st, cfg, signal): sym = signal["symbol"] shadow_last = st.setdefault("shadow_last_trade_at", {}).get(sym) if shadow_last: st.setdefault("last_trade_at", {})[f"shadow:{sym}"] = shadow_last if sym in st.setdefault("shadow_positions", {}) or in_cooldown({"last_trade_at": {sym: shadow_last}}, cfg, sym) or signal["gap_pct"] < cfg["min_gap_pct"]: return None blocked, loss_info = recent_symbol_loss_blocked({**cfg, "max_recent_symbol_losses": 2, "recent_symbol_window_trades": 3}, sym, event_type="shadow_sell") if blocked: log_event({"type": "shadow_symbol_lockout", "symbol": sym, **(loss_info or {})}) return None if not signal_has_fee_aware_edge(cfg, signal): return None notional = float(cfg.get("shadow_trade_usd", 10.0)) exec_price = signal["price"] * (1 + cfg["slippage_bps"] / 10000) fee = notional * cfg["fee_bps"] / 10000 qty = notional / exec_price st["shadow_positions"][sym] = {"qty": qty, "avg_entry": exec_price, "opened_at": now_iso(), "last_price": signal["price"], "notional_usd": notional, "buy_fee_usd": fee, "entry_gap_pct": signal["gap_pct"]} st.setdefault("shadow_last_trade_at", {})[sym] = now_iso() ev = {"type": "shadow_buy", "symbol": sym, "qty": qty, "price": exec_price, "fee_usd": fee, "notional_usd": notional, "gap_pct": signal["gap_pct"]} log_event(ev); return ev def scan_once(cfg, st): roll_daily(st, equity(st, {})) signals=[]; prices={}; events=[] watch_all = list(dict.fromkeys(cfg.get("watch_only_symbols", []))) watch_limit = int(cfg.get("watch_scan_limit_per_cycle", 0) or 0) if watch_limit > 0 and len(watch_all) > watch_limit: cursor = int(st.get("watch_scan_cursor", 0) or 0) % len(watch_all) watch_slice = [watch_all[(cursor + i) % len(watch_all)] for i in range(watch_limit)] st["watch_scan_cursor"] = (cursor + watch_limit) % len(watch_all) else: watch_slice = watch_all scan_symbols = list(dict.fromkeys( list(cfg["symbols"]) + watch_slice + list(st.get("positions", {}).keys()) + list(st.get("shadow_positions", {}).keys()) )) watch_only = set(watch_all) for sym in scan_symbols: try: candles = fetch_coinbase_candles(sym, cfg["lookback_hours"], cfg["candle_granularity_seconds"]) price = candles[-1].close fv = fair_value(candles) fair_gap_pct = max(0.0, (fv - price) / fv * 100) if fv > 0 else 0.0 pullback_gap = pullback_gap_pct(candles) if cfg.get("use_pullback_gap_for_majors", True) else 0.0 gap_pct = max(fair_gap_pct, pullback_gap) rebound_pct, hour_change_pct = rebound_metrics(candles) sig = {"symbol": sym, "price": price, "fair_value": fv, "fair_value_gap_pct": fair_gap_pct, "pullback_gap_pct": pullback_gap, "gap_pct": gap_pct, "volatility_pct": volatility_pct(candles), "dollar_volume_24h": dollar_volume(candles), "rebound_from_recent_low_pct": rebound_pct, "hour_change_pct": hour_change_pct, "day_change_pct": day_change_pct(candles), "candles": len(candles), "source": "coinbase", "status": "ok", "watch_only": sym in watch_only} prices[sym] = price; signals.append(sig) except Exception as e: err = str(e) status = "skipped_low_data" if err.startswith("not enough candles for ") else "error" signals.append({"symbol": sym, "status": status, "error": err, "watch_only": sym in watch_only}) for sig in signals: if sig.get("status") == "ok": ev = close_position_if_needed(st, cfg, sig["symbol"], sig["price"]) if ev: events.append(ev) sev = close_shadow_position_if_needed(st, cfg, sig["symbol"], sig["price"]) if sev: events.append(sev) eq = equity(st, prices); blocked, reason = daily_loss_blocked(st, cfg, eq) missing_held = sorted(set(st.get("positions", {})) - set(prices)) if missing_held: blocked, reason = True, "missing_position_prices" if blocked: log_event({"type": "risk_block", "reason": reason, "equity_usd": eq}) else: tradeable = set(cfg["symbols"]) for sig in sorted([s for s in signals if s.get("status") == "ok" and s.get("symbol") in tradeable], key=lambda x: x["gap_pct"], reverse=True): eq = equity(st, prices) blocked, reason = daily_loss_blocked(st, cfg, eq) if blocked: break ev = maybe_open_position(st, cfg, sig, eq) if ev: events.append(ev) for sig in sorted([s for s in signals if s.get("status") == "ok" and s.get("symbol") in watch_only], key=lambda x: x["gap_pct"], reverse=True): ev = maybe_open_shadow_position(st, cfg, sig) if ev: events.append(ev) st["last_scan"] = {"ts": now_iso(), "equity_usd": equity(st, prices), "events": events, "entries_blocked": blocked, "block_reason": reason, "missing_position_prices": missing_held, "price_basis": "completed candles; stops checked only during scans"} st["last_signals"] = signals save_state(st) log_event({"type": "scan", "equity_usd": st["last_scan"]["equity_usd"], "signals": signals, "events_count": len(events)}) return st["last_scan"] def main(): p=argparse.ArgumentParser(); p.add_argument("--once", action="store_true"); p.add_argument("--loop", action="store_true"); p.add_argument("--config-check", action="store_true") args=p.parse_args(); cfg=load_config(); st=load_state(cfg) if args.config_check: print(json.dumps({"ok": True, "config": cfg, "state_path": str(STATE_PATH)}, indent=2)); return if not (args.once or args.loop): args.once=True while True: # Reload state every cycle so manual deposits/admin edits are not overwritten # by a long-running loop holding an old in-memory copy. if args.loop: st = load_state(cfg) DATA.mkdir(exist_ok=True) with LOCK_PATH.open("w") as lock: fcntl.flock(lock, fcntl.LOCK_EX) # Reload again after acquiring the lock so a concurrent manual scan/dashboard # request cannot double-buy from stale state. st = load_state(cfg) print(json.dumps(scan_once(cfg, st), indent=2)) if args.once: break time.sleep(cfg["scan_interval_seconds"]) if __name__ == "__main__": main()