feat: deploy five-market paper trading profile

This commit is contained in:
pnannery committed 2026-09-11 06:53:10 -04:00
1 parent 0591b75401
commit d6ee92dbb7
19 files changed
+811 -41

No files matched your search

Executable → Regular
+39 -8
View File
@@ -38,7 +38,7 @@ def default_state(cfg):
"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},
"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": []
}
@@ -72,7 +72,12 @@ def fetch_coinbase_candles(symbol, hours, granularity):
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
@@ -142,18 +147,32 @@ def equity(st, prices):
eq += float(pos["qty"]) * px
return eq
def daily_loss_blocked(st, cfg, 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}
daily_loss_limit = -abs(cfg["max_daily_loss_pct"]) / 100 * max(st["starting_cash_usd"], eq)
if st["daily"]["realized_pnl_usd"] <= daily_loss_limit: return True, "daily_loss_limit"
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
@@ -249,6 +268,7 @@ def close_position_if_needed(st, cfg, sym, price):
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
@@ -277,6 +297,7 @@ def close_shadow_position_if_needed(st, cfg, sym, price):
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
@@ -287,7 +308,7 @@ def close_shadow_position_if_needed(st, cfg, sym, price):
log_event(ev); return ev
def signal_has_fee_aware_edge(cfg, signal):
round_trip_cost_pct = (2 * cfg["fee_bps"] + cfg["slippage_bps"]) / 100.0
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
@@ -317,12 +338,16 @@ def maybe_open_position(st, cfg, signal, eq):
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.get("notional_usd", 0.0)) for p in st.get("positions", {}).values())
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,
@@ -363,6 +388,7 @@ def maybe_open_shadow_position(st, cfg, signal):
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)
@@ -401,17 +427,22 @@ def scan_once(cfg, st):
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}
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)})