chore: initial local trading agent import
This commit is contained in:
commit
0591b75401
13 files changed
+1385
No files matched your search
+18
@@ -0,0 +1,18 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
|
||||
# Runtime trading state / audit logs
|
||||
data/*.json
|
||||
data/*.jsonl
|
||||
data/*.lock
|
||||
data/scan.lock
|
||||
|
||||
# Local backups created during tuning
|
||||
config.json.bak*
|
||||
|
||||
# Local environment/secrets
|
||||
.env
|
||||
*.pem
|
||||
*.key
|
||||
@@ -0,0 +1,55 @@
|
||||
# Local Crypto Dip Agent
|
||||
|
||||
Local-first autonomous **paper trading** agent for BTC/ETH dip detection.
|
||||
|
||||
This is deliberately paper-only by default. Live execution should not be enabled until the paper ledger proves edge after fees/slippage and risk limits are reviewed.
|
||||
|
||||
## What it does
|
||||
|
||||
Every run:
|
||||
- fetches recent BTC-USD and ETH-USD candles from public Coinbase Exchange API
|
||||
- computes a local fair value from EMA + VWAP
|
||||
- detects downside gaps below fair value
|
||||
- opens paper long positions only when the gap exceeds configured thresholds
|
||||
- scans watch-only candidates without opening new positions
|
||||
- sizes positions based on gap strength and recent volatility
|
||||
- applies fees/slippage assumptions
|
||||
- tracks cash, positions, realized/unrealized P/L, and audit logs
|
||||
|
||||
## Run once
|
||||
|
||||
```bash
|
||||
python3 bot.py --once
|
||||
```
|
||||
|
||||
## Run every 15 minutes
|
||||
|
||||
```bash
|
||||
python3 bot.py --loop
|
||||
```
|
||||
|
||||
## Dashboard
|
||||
|
||||
```bash
|
||||
python3 dashboard.py --host 127.0.0.1 --port 8765
|
||||
# open http://127.0.0.1:8765
|
||||
```
|
||||
|
||||
## Files
|
||||
|
||||
- `config.json` - strategy/risk settings
|
||||
- `bot.py` - scanner + paper execution engine
|
||||
- `dashboard.py` - local dashboard/API
|
||||
- `data/state.json` - paper account state
|
||||
- `data/trades.jsonl` - trade/audit log
|
||||
|
||||
## Live trading warning
|
||||
|
||||
Do not add exchange keys with withdrawal permission. If live mode is ever added, use:
|
||||
- trade-only API keys
|
||||
- tiny max position size
|
||||
- max daily loss
|
||||
- max drawdown
|
||||
- circuit breaker
|
||||
- external alerts
|
||||
- paper/live parity report
|
||||
@@ -0,0 +1,441 @@
|
||||
#!/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},
|
||||
"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.sort(key=lambda c: c.ts)
|
||||
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 daily_loss_blocked(st, cfg, 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"
|
||||
high = max(float(st.get("equity_high_watermark_usd", eq)), eq)
|
||||
st["equity_high_watermark_usd"] = high
|
||||
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
|
||||
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
|
||||
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"] + 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.get("notional_usd", 0.0)) 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"])
|
||||
notional = min(
|
||||
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):
|
||||
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)
|
||||
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)
|
||||
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_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()
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"starting_cash_usd": 100.0,
|
||||
"symbols": [
|
||||
"BTC-USD",
|
||||
"ETH-USD",
|
||||
"XRP-USD",
|
||||
"SOL-USD",
|
||||
"DOGE-USD",
|
||||
"ADA-USD",
|
||||
"LINK-USD",
|
||||
"XLM-USD",
|
||||
"LTC-USD",
|
||||
"BCH-USD",
|
||||
"AVAX-USD",
|
||||
"DOT-USD",
|
||||
"SUI-USD",
|
||||
"NEAR-USD",
|
||||
"ATOM-USD",
|
||||
"HBAR-USD",
|
||||
"ICP-USD",
|
||||
"RENDER-USD"
|
||||
],
|
||||
"watch_only_symbols": [
|
||||
"ARB-USD",
|
||||
"APT-USD",
|
||||
"INJ-USD",
|
||||
"SEI-USD",
|
||||
"ONDO-USD",
|
||||
"VET-USD",
|
||||
"FET-USD",
|
||||
"SAND-USD",
|
||||
"MANA-USD",
|
||||
"ZRO-USD"
|
||||
],
|
||||
"scan_interval_seconds": 300,
|
||||
"lookback_hours": 24,
|
||||
"candle_granularity_seconds": 300,
|
||||
"min_gap_pct": 0.75,
|
||||
"strong_gap_pct": 1.75,
|
||||
"max_position_pct_of_equity": 0.1,
|
||||
"max_total_position_pct_of_equity": 0.31,
|
||||
"min_trade_usd": 5.0,
|
||||
"shadow_trade_usd": 4.0,
|
||||
"fee_bps": 40,
|
||||
"slippage_bps": 15,
|
||||
"min_edge_after_cost_pct": 0.8,
|
||||
"require_rebound_confirmation": true,
|
||||
"rebound_lookback_candles": 3,
|
||||
"min_rebound_from_recent_low_pct": 0.3,
|
||||
"max_drop_last_hour_pct": 1.5,
|
||||
"min_dollar_volume_24h": 400000,
|
||||
"min_candles_24h": 180,
|
||||
"max_24h_pump_pct": 25.0,
|
||||
"max_24h_dump_pct": 15.0,
|
||||
"max_recent_symbol_losses": 2,
|
||||
"recent_symbol_window_trades": 4,
|
||||
"take_profit_pct": 3.0,
|
||||
"stop_loss_pct": 1.2,
|
||||
"max_daily_loss_pct": 2.5,
|
||||
"max_drawdown_pct": 6.0,
|
||||
"cooldown_minutes_after_trade": 180,
|
||||
"max_boosted_position_pct_of_equity": 0.16,
|
||||
"max_symbol_performance_multiplier": 2.0,
|
||||
"min_symbol_performance_multiplier": 0.45,
|
||||
"watch_scan_limit_per_cycle": 18,
|
||||
"use_pullback_gap_for_majors": true,
|
||||
"promotable_symbols": [
|
||||
"BTC-USD",
|
||||
"ETH-USD",
|
||||
"XRP-USD",
|
||||
"SOL-USD",
|
||||
"DOGE-USD",
|
||||
"ADA-USD",
|
||||
"LINK-USD",
|
||||
"XLM-USD",
|
||||
"LTC-USD",
|
||||
"BCH-USD",
|
||||
"AVAX-USD",
|
||||
"DOT-USD",
|
||||
"SUI-USD",
|
||||
"NEAR-USD",
|
||||
"ATOM-USD",
|
||||
"HBAR-USD",
|
||||
"ICP-USD",
|
||||
"RENDER-USD"
|
||||
],
|
||||
"trailing_stop_trigger_pct": 1.6,
|
||||
"trailing_stop_giveback_pct": 0.85,
|
||||
"breakeven_stop_trigger_pct": 1.4,
|
||||
"breakeven_stop_pct": 0.9
|
||||
}
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse, json, subprocess, sys
|
||||
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ROOT=Path(__file__).resolve().parent
|
||||
STATE=ROOT/'data'/'state.json'
|
||||
TRADES=ROOT/'data'/'trades.jsonl'
|
||||
|
||||
INDEX = '''<!doctype html><html><head><meta charset="utf-8"><title>Local Crypto Dip Agent</title><meta name="viewport" content="width=device-width,initial-scale=1"><style>
|
||||
body{font-family:system-ui,-apple-system,Segoe UI,sans-serif;background:#0b1020;color:#e8eefc;margin:0;padding:24px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px}.card{background:#151d33;border:1px solid #283652;border-radius:14px;padding:16px;box-shadow:0 10px 30px #0004}button{background:#4f8cff;color:white;border:0;border-radius:10px;padding:10px 14px;font-weight:700;cursor:pointer}.muted{color:#9fb0d0}.good{color:#78e08f}.bad{color:#ff7675}pre{white-space:pre-wrap;word-break:break-word;background:#09101f;padding:12px;border-radius:10px;max-height:360px;overflow:auto}table{width:100%;border-collapse:collapse}td,th{padding:8px;border-bottom:1px solid #283652;text-align:left}</style></head><body>
|
||||
<h1>Local Crypto Dip Agent <span class="muted">paper mode</span></h1><p class="muted">Local dashboard. No live exchange execution.</p><button onclick="runScan()">Run scan now</button> <button onclick="load()">Refresh</button><div id="app" class="grid"></div><h2>Recent audit log</h2><pre id="log"></pre>
|
||||
<script>
|
||||
async function j(u,o){const r=await fetch(u,o); if(!r.ok) throw new Error(await r.text()); return r.json()}
|
||||
function money(x){return '$'+Number(x||0).toFixed(2)}
|
||||
async function runScan(){document.querySelector('button').disabled=true; try{await j('/api/scan',{method:'POST'}); await load()} finally{document.querySelector('button').disabled=false}}
|
||||
async function load(){const s=await j('/api/state'); const app=document.getElementById('app'); const pos=s.positions||{}; const sig=s.last_signals||[]; app.innerHTML=`<div class=card><h2>Account</h2><p>Cash: <b>${money(s.cash_usd)}</b></p><p>Realized P/L: <b class="${(s.realized_pnl_usd||0)>=0?'good':'bad'}">${money(s.realized_pnl_usd)}</b></p><p>Last scan: ${s.last_scan?.ts||'never'}</p></div><div class=card><h2>Positions</h2>${Object.keys(pos).length?'<table><tr><th>Symbol</th><th>Qty</th><th>Entry</th></tr>'+Object.entries(pos).map(([k,p])=>`<tr><td>${k}</td><td>${Number(p.qty).toFixed(8)}</td><td>${money(p.avg_entry)}</td></tr>`).join('')+'</table>':'<p class=muted>No open positions</p>'}</div><div class=card><h2>Signals</h2><table><tr><th>Symbol</th><th>Price</th><th>Fair</th><th>Gap</th></tr>${sig.map(x=>x.status==='ok'?`<tr><td>${x.symbol}</td><td>${money(x.price)}</td><td>${money(x.fair_value)}</td><td>${Number(x.gap_pct).toFixed(3)}%</td></tr>`:`<tr><td>${x.symbol}</td><td colspan=3 class=bad>${x.error}</td></tr>`).join('')}</table></div><div class=card><h2>Last scan raw</h2><pre>${JSON.stringify(s.last_scan||{},null,2)}</pre></div>`; document.getElementById('log').textContent=(await fetch('/api/log').then(r=>r.text()))}
|
||||
load(); setInterval(load,15000)
|
||||
</script></body></html>'''
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def send(self, code, body, ctype='application/json'):
|
||||
b=body.encode(); self.send_response(code); self.send_header('content-type', ctype); self.send_header('content-length', str(len(b))); self.end_headers(); self.wfile.write(b)
|
||||
def do_GET(self):
|
||||
p=urlparse(self.path).path
|
||||
if p=='/': return self.send(200, INDEX, 'text/html; charset=utf-8')
|
||||
if p=='/api/state': return self.send(200, STATE.read_text() if STATE.exists() else '{}')
|
||||
if p=='/api/log':
|
||||
if not TRADES.exists(): return self.send(200, '', 'text/plain')
|
||||
return self.send(200, '\n'.join(TRADES.read_text().splitlines()[-100:]), 'text/plain')
|
||||
return self.send(404, json.dumps({'error':'not found'}))
|
||||
def do_POST(self):
|
||||
p=urlparse(self.path).path
|
||||
if p=='/api/scan':
|
||||
r=subprocess.run([sys.executable, str(ROOT/'bot.py'), '--once'], cwd=str(ROOT), capture_output=True, text=True, timeout=60)
|
||||
if r.returncode: return self.send(500, json.dumps({'error':r.stderr or r.stdout}))
|
||||
return self.send(200, r.stdout)
|
||||
return self.send(404, json.dumps({'error':'not found'}))
|
||||
def log_message(self, format, *args): print('%s - %s' % (self.address_string(), format%args))
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(); ap.add_argument('--host', default='127.0.0.1'); ap.add_argument('--port', type=int, default=8765); args=ap.parse_args()
|
||||
print(f'Listening on http://{args.host}:{args.port}')
|
||||
ThreadingHTTPServer((args.host,args.port), H).serve_forever()
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
from pathlib import Path
|
||||
import bot
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
cfg = json.loads((ROOT / 'config.json').read_text())
|
||||
st = json.loads((ROOT / 'data/state.json').read_text())
|
||||
required_gap = cfg['min_gap_pct'] + (2 * cfg['fee_bps'] + cfg['slippage_bps']) / 100.0 + cfg.get('min_edge_after_cost_pct', 0)
|
||||
print(f"Required entry gap after costs: {required_gap:.2f}%")
|
||||
print("Candidates now:")
|
||||
for s in sorted(st.get('last_signals', []), key=lambda x: x.get('gap_pct', -1), reverse=True):
|
||||
if s.get('status') != 'ok':
|
||||
label = 'SKIP' if s.get('status') == 'skipped_low_data' else 'ERROR'
|
||||
print(f"{s.get('symbol')}: {label} {s.get('error')}")
|
||||
continue
|
||||
ok = bot.signal_has_fee_aware_edge(cfg, s)
|
||||
reasons=[]
|
||||
if s['gap_pct'] < required_gap: reasons.append('gap too small')
|
||||
if s.get('candles',0) < cfg.get('min_candles_24h',0): reasons.append('not enough candles')
|
||||
if s.get('dollar_volume_24h',0) < cfg.get('min_dollar_volume_24h',0): reasons.append('volume too low')
|
||||
if s.get('day_change_pct',0) > cfg.get('max_24h_pump_pct',999): reasons.append('24h pump too hot')
|
||||
if s.get('day_change_pct',0) < -abs(cfg.get('max_24h_dump_pct',999)): reasons.append('24h dump too deep')
|
||||
if s.get('rebound_from_recent_low_pct',0) < cfg.get('min_rebound_from_recent_low_pct',0): reasons.append('no rebound')
|
||||
if s.get('hour_change_pct',0) < -abs(cfg.get('max_drop_last_hour_pct',100)): reasons.append('falling too fast')
|
||||
flag = 'PASS' if ok else 'BLOCK'
|
||||
if s.get('symbol') in cfg.get('symbols', []):
|
||||
mode = 'TRADE'
|
||||
elif s.get('watch_only'):
|
||||
mode = 'WATCH'
|
||||
else:
|
||||
mode = 'SHADOW'
|
||||
print(f"{s['symbol']:12s} {mode:6s} {flag:5s} gap={s['gap_pct']:.2f}% day={s.get('day_change_pct',0):+.2f}% rebound={s.get('rebound_from_recent_low_pct',0):.2f}% hour={s.get('hour_change_pct',0):+.2f}% vol24=${s.get('dollar_volume_24h',0):,.0f}" + (f" reason={','.join(reasons)}" if reasons else ''))
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
import json, math, time
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
CONFIG = ROOT / 'config.json'
|
||||
TRADES = ROOT / 'data' / 'trades.jsonl'
|
||||
LOCAL_TZ = ZoneInfo('America/New_York')
|
||||
|
||||
BAD = {'MDT-USD','HFT-USD','HIGH-USD','COTI-USD'}
|
||||
|
||||
def get(url, timeout=15):
|
||||
with urlopen(Request(url, headers={'User-Agent':'local-trader-find-winners/0.1'}), timeout=timeout) as r:
|
||||
return json.loads(r.read().decode())
|
||||
|
||||
def trade_perf():
|
||||
perf=defaultdict(lambda:{'trades':0,'wins':0,'losses':0,'pnl':0.0})
|
||||
if not TRADES.exists(): return perf
|
||||
for line in TRADES.read_text().splitlines():
|
||||
if not line.strip(): continue
|
||||
try: e=json.loads(line)
|
||||
except Exception: continue
|
||||
if e.get('type')=='paper_sell':
|
||||
p=float(e.get('realized_pnl_usd',0)); d=perf[e['symbol']]
|
||||
d['trades']+=1; d['pnl']+=p; d['wins']+=p>=0; d['losses']+=p<0
|
||||
return perf
|
||||
|
||||
def candles(sym):
|
||||
end=int(time.time()); start=end-24*3600
|
||||
url=f"https://api.exchange.coinbase.com/products/{sym}/candles?granularity=300&start={datetime.fromtimestamp(start,LOCAL_TZ).isoformat()}&end={datetime.fromtimestamp(end,LOCAL_TZ).isoformat()}"
|
||||
c=sorted(get(url,10), key=lambda x:x[0])
|
||||
if len(c)<80: return None
|
||||
closes=[float(x[4]) for x in c]
|
||||
if min(closes)<=0: return None
|
||||
highs=[float(x[2]) for x in c]; lows=[float(x[1]) for x in c]
|
||||
dollar_vol=sum(((float(x[1])+float(x[2])+float(x[4]))/3)*float(x[5]) for x in c)
|
||||
move=(closes[-1]/closes[0]-1)*100
|
||||
rng=(max(highs)/min(lows)-1)*100
|
||||
rets=[math.log(closes[i]/closes[i-1]) for i in range(1,len(closes)) if closes[i-1]>0]
|
||||
rv=(sum(r*r for r in rets)/len(rets))**0.5*math.sqrt(288)*100 if rets else 0
|
||||
# Trend filter: avoid vertical pumps; prefer volatile but not already up >35%.
|
||||
pump_penalty=0.45 if move>35 else 1.0
|
||||
dump_penalty=0.65 if move<-20 else 1.0
|
||||
liquidity=min(1.0, math.log10(max(dollar_vol,1))/6.0)
|
||||
score=rv*liquidity*pump_penalty*dump_penalty
|
||||
return {'symbol':sym,'price':closes[-1],'move24h':move,'range24h':rng,'realized_vol':rv,'dollar_vol':dollar_vol,'candles':len(c),'score':score}
|
||||
|
||||
def main():
|
||||
cfg=json.loads(CONFIG.read_text())
|
||||
current=set(cfg.get('symbols',[])); watch=set(cfg.get('watch_only_symbols',[]))
|
||||
products=get('https://api.exchange.coinbase.com/products')
|
||||
rows=[]
|
||||
for p in products:
|
||||
sym=p.get('id')
|
||||
if p.get('quote_currency')!='USD' or p.get('status')!='online' or p.get('trading_disabled'): continue
|
||||
if sym in current or sym in BAD: continue
|
||||
try:
|
||||
row=candles(sym)
|
||||
if row and row['dollar_vol']>=300000:
|
||||
rows.append(row)
|
||||
except Exception:
|
||||
pass
|
||||
rows.sort(key=lambda r:r['score'], reverse=True)
|
||||
perf=trade_perf()
|
||||
print('Current proven winners from bot log:')
|
||||
for sym,d in sorted(perf.items(), key=lambda kv: kv[1]['pnl'], reverse=True):
|
||||
if d['pnl']>0:
|
||||
print(f"{sym:10s} pnl=${d['pnl']:.2f} wins={d['wins']} losses={d['losses']} trades={d['trades']}")
|
||||
print('\nBest new watch candidates, not auto-trade yet:')
|
||||
for r in rows[:12]:
|
||||
print(f"{r['symbol']:12s} score={r['score']:6.2f} price={r['price']:.8g} move={r['move24h']:+6.2f}% range={r['range24h']:6.2f}% rv={r['realized_vol']:6.2f}% vol~${r['dollar_vol']:,.0f}")
|
||||
recommended=[r['symbol'] for r in rows[:5]]
|
||||
print('\nRECOMMENDED_WATCH_ONLY=' + ','.join(recommended))
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
Executable
+120
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
CONFIG = ROOT / "config.json"
|
||||
TRADES = ROOT / "data" / "trades.jsonl"
|
||||
|
||||
MIN_CLOSED = 3
|
||||
MIN_PNL = 0.25
|
||||
MIN_WIN_RATE = 0.66
|
||||
PRUNE_CLOSED = 2
|
||||
PRUNE_PNL = -0.20
|
||||
|
||||
|
||||
def load_events():
|
||||
if not TRADES.exists():
|
||||
return []
|
||||
out = []
|
||||
for line in TRADES.read_text().splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
out.append(json.loads(line))
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def shadow_stats(events):
|
||||
"""Return fee-adjusted shadow performance by symbol.
|
||||
|
||||
Older sell events only included sell fees in realized_pnl_usd. Newer sell
|
||||
events include buy_fee_usd. For old closed round trips, subtract the matching
|
||||
buy fees once so watch promotion/pruning is based on real net edge.
|
||||
"""
|
||||
stats = defaultdict(lambda: {"closed": 0, "wins": 0, "losses": 0, "pnl": 0.0})
|
||||
pending_buy_fees = defaultdict(list)
|
||||
for ev in events:
|
||||
sym = ev.get("symbol")
|
||||
if not sym:
|
||||
continue
|
||||
if ev.get("type") == "shadow_buy":
|
||||
pending_buy_fees[sym].append(float(ev.get("fee_usd", 0.0)))
|
||||
continue
|
||||
if ev.get("type") != "shadow_sell":
|
||||
continue
|
||||
buy_fee = float(ev.get("buy_fee_usd", 0.0))
|
||||
if "buy_fee_usd" not in ev and pending_buy_fees[sym]:
|
||||
buy_fee = pending_buy_fees[sym].pop(0)
|
||||
pnl = float(ev.get("realized_pnl_usd", 0.0)) - buy_fee
|
||||
d = stats[sym]
|
||||
d["closed"] += 1
|
||||
d["pnl"] += pnl
|
||||
if pnl >= 0:
|
||||
d["wins"] += 1
|
||||
else:
|
||||
d["losses"] += 1
|
||||
return stats
|
||||
|
||||
|
||||
def main():
|
||||
cfg = json.loads(CONFIG.read_text())
|
||||
watch = list(dict.fromkeys(cfg.get("watch_only_symbols", [])))
|
||||
trade = list(dict.fromkeys(cfg.get("symbols", [])))
|
||||
stats = shadow_stats(load_events())
|
||||
|
||||
promotable = set(cfg.get("promotable_symbols") or (trade + watch))
|
||||
promoted = []
|
||||
rejected = []
|
||||
pruned = []
|
||||
ignored = []
|
||||
for sym in list(watch):
|
||||
d = stats[sym]
|
||||
win_rate = (d["wins"] / d["closed"]) if d["closed"] else 0.0
|
||||
if d["closed"] >= MIN_CLOSED and d["pnl"] >= MIN_PNL and win_rate >= MIN_WIN_RATE:
|
||||
if sym in promotable:
|
||||
watch.remove(sym)
|
||||
if sym not in trade:
|
||||
trade.append(sym)
|
||||
promoted.append((sym, d))
|
||||
else:
|
||||
ignored.append((sym, d))
|
||||
elif d["closed"] >= PRUNE_CLOSED and d["pnl"] <= PRUNE_PNL:
|
||||
watch.remove(sym)
|
||||
pruned.append((sym, d))
|
||||
elif d["closed"] >= MIN_CLOSED and d["pnl"] < 0:
|
||||
rejected.append((sym, d))
|
||||
|
||||
if promoted or pruned:
|
||||
cfg["symbols"] = trade
|
||||
cfg["watch_only_symbols"] = watch
|
||||
CONFIG.write_text(json.dumps(cfg, indent=2) + "\n")
|
||||
|
||||
print("Promotion review")
|
||||
print(f"Active tradeable: {len(trade)} | watch-only: {len(watch)}")
|
||||
if promoted:
|
||||
print("Promoted to tradeable:")
|
||||
for sym, d in promoted:
|
||||
print(f"- {sym}: net shadow pnl=${d['pnl']:.2f}, wins={d['wins']}, losses={d['losses']}, closed={d['closed']}")
|
||||
else:
|
||||
print("No watch-only coin has enough winning shadow evidence yet.")
|
||||
if ignored:
|
||||
print("Ignored winners outside promotable allow-list:")
|
||||
for sym, d in ignored[:10]:
|
||||
print(f"- {sym}: net shadow pnl=${d['pnl']:.2f}, wins={d['wins']}, losses={d['losses']}, closed={d['closed']}")
|
||||
if rejected:
|
||||
print("Worst rejected watch-only losers:")
|
||||
for sym, d in sorted(rejected, key=lambda item: item[1]["pnl"])[:10]:
|
||||
print(f"- {sym}: net shadow pnl=${d['pnl']:.2f}, wins={d['wins']}, losses={d['losses']}, closed={d['closed']}")
|
||||
if pruned:
|
||||
print("Pruned from watch-only for losing shadow evidence:")
|
||||
for sym, d in pruned[:10]:
|
||||
print(f"- {sym}: net shadow pnl=${d['pnl']:.2f}, wins={d['wins']}, losses={d['losses']}, closed={d['closed']}")
|
||||
if watch:
|
||||
print("Watch-only sample: " + ", ".join(watch[:20]) + (" ..." if len(watch) > 20 else ""))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
import json, math, time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.error import HTTPError, URLError
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
CONFIG = ROOT / 'config.json'
|
||||
LOCAL_TZ = ZoneInfo('America/New_York')
|
||||
|
||||
# Avoid stablecoins, fiat/pegged assets, and chronic bad shadow/live names unless they later prove otherwise.
|
||||
BAD = {
|
||||
'MDT-USD','HFT-USD','HIGH-USD','COTI-USD',
|
||||
'USDT-USD','USDC-USD','DAI-USD','PYUSD-USD','GUSD-USD',
|
||||
'EURC-USD','GYEN-USD','PAX-USD','PAXG-USD'
|
||||
}
|
||||
|
||||
# Large majors are okay as baseline, but usually too slow for this small dip bot.
|
||||
MAJORS = {'BTC-USD','ETH-USD','SOL-USD','XRP-USD','ADA-USD','DOGE-USD','AVAX-USD','LINK-USD','LTC-USD','BCH-USD'}
|
||||
|
||||
def get(url, timeout=20):
|
||||
with urlopen(Request(url, headers={'User-Agent':'local-trader-coin-research/0.2'}), timeout=timeout) as r:
|
||||
return json.loads(r.read().decode())
|
||||
|
||||
def candle_metrics(sym):
|
||||
end = int(time.time())
|
||||
start = end - 24*3600
|
||||
url = f"https://api.exchange.coinbase.com/products/{sym}/candles?granularity=300&start={datetime.fromtimestamp(start,LOCAL_TZ).isoformat()}&end={datetime.fromtimestamp(end,LOCAL_TZ).isoformat()}"
|
||||
raw = sorted(get(url, 12), key=lambda x: x[0])
|
||||
if len(raw) < 180:
|
||||
return None
|
||||
lows = [float(x[1]) for x in raw]
|
||||
highs = [float(x[2]) for x in raw]
|
||||
opens = [float(x[3]) for x in raw]
|
||||
closes = [float(x[4]) for x in raw]
|
||||
vols = [float(x[5]) for x in raw]
|
||||
if min(closes) <= 0 or min(lows) <= 0:
|
||||
return None
|
||||
dollar_vols = [((lows[i]+highs[i]+closes[i])/3)*vols[i] for i in range(len(raw))]
|
||||
dollar_vol = sum(dollar_vols)
|
||||
if dollar_vol < 250000:
|
||||
return None
|
||||
move = (closes[-1]/closes[0]-1)*100
|
||||
range24 = (max(highs)/min(lows)-1)*100
|
||||
hour_change = (closes[-1]/opens[-12]-1)*100 if len(opens) >= 12 and opens[-12] > 0 else 0
|
||||
recent_low = min(lows[-4:])
|
||||
rebound = (closes[-1]/recent_low-1)*100 if recent_low > 0 else 0
|
||||
rets = [math.log(closes[i]/closes[i-1]) for i in range(1,len(closes)) if closes[i-1] > 0]
|
||||
rv = (sum(r*r for r in rets)/len(rets))**0.5*math.sqrt(288)*100 if rets else 0
|
||||
# Local bot's fair-value proxy, matched to bot.py.
|
||||
def ema(vals, span):
|
||||
a=2/(span+1); out=vals[0]
|
||||
for v in vals[1:]: out=a*v+(1-a)*out
|
||||
return out
|
||||
total_vol=sum(vols)
|
||||
vwap=sum(((highs[i]+lows[i]+closes[i])/3)*vols[i] for i in range(len(raw)))/total_vol if total_vol else closes[-1]
|
||||
fv = 0.45*ema(closes,12)+0.35*ema(closes,48)+0.20*vwap
|
||||
gap = max(0.0, (fv-closes[-1])/fv*100) if fv > 0 else 0
|
||||
# Scoring: want enough volatility and range, not a vertical pump, not death dump, liquid enough but not dead-stable mega cap.
|
||||
liquidity = min(1.25, math.log10(max(dollar_vol,1))/6.0)
|
||||
vol_band = min(rv, 220) / 100.0
|
||||
range_band = min(range24, 35) / 12.0
|
||||
pump_penalty = 0.45 if move > 25 else 0.75 if move > 15 else 1.0
|
||||
dump_penalty = 0.45 if move < -20 else 0.75 if move < -12 else 1.0
|
||||
major_penalty = 0.65 if sym in MAJORS else 1.0
|
||||
micro_penalty = 0.65 if dollar_vol < 500000 else 1.0
|
||||
score = 100 * liquidity * vol_band * range_band * pump_penalty * dump_penalty * major_penalty * micro_penalty
|
||||
return {
|
||||
'symbol': sym, 'price': closes[-1], 'move24h': move, 'range24h': range24,
|
||||
'realized_vol': rv, 'dollar_vol': dollar_vol, 'hour_change_pct': hour_change,
|
||||
'rebound_from_recent_low_pct': rebound, 'current_gap_pct': gap,
|
||||
'candles': len(raw), 'score': score
|
||||
}
|
||||
|
||||
def main():
|
||||
cfg = json.loads(CONFIG.read_text())
|
||||
current = set(cfg.get('symbols', []))
|
||||
watch = set(cfg.get('watch_only_symbols', []))
|
||||
products = get('https://api.exchange.coinbase.com/products')
|
||||
candidates=[]; skipped=0; errors=0
|
||||
usd = [p for p in products if p.get('quote_currency') == 'USD' and p.get('status') == 'online' and not p.get('trading_disabled')]
|
||||
for p in sorted(usd, key=lambda x: x.get('id','')):
|
||||
sym = p.get('id')
|
||||
if not sym or sym in BAD:
|
||||
continue
|
||||
try:
|
||||
row = candle_metrics(sym)
|
||||
if row:
|
||||
row['already_trade'] = sym in current
|
||||
row['already_watch'] = sym in watch
|
||||
candidates.append(row)
|
||||
else:
|
||||
skipped += 1
|
||||
except Exception:
|
||||
errors += 1
|
||||
candidates.sort(key=lambda r: r['score'], reverse=True)
|
||||
new = [r for r in candidates if not r['already_trade'] and not r['already_watch']]
|
||||
watch_plus = [r for r in candidates if r['already_watch']]
|
||||
trade = [r for r in candidates if r['already_trade']]
|
||||
report = {
|
||||
'generated_at': datetime.now(LOCAL_TZ).isoformat(),
|
||||
'usd_products_checked': len(usd),
|
||||
'ranked': len(candidates),
|
||||
'skipped_low_data_or_volume': skipped,
|
||||
'errors': errors,
|
||||
'top_new_watch_only': new[:15],
|
||||
'current_watch_ranked': watch_plus[:20],
|
||||
'current_trade_ranked': trade[:20],
|
||||
'recommended_watch_symbols': [r['symbol'] for r in new[:10]],
|
||||
'recommended_trade_promotions_now': []
|
||||
}
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
import copy
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import bot
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def test_config_check():
|
||||
r = subprocess.run([sys.executable, str(ROOT / 'bot.py'), '--config-check'], cwd=ROOT, capture_output=True, text=True, timeout=20)
|
||||
assert r.returncode == 0, r.stderr
|
||||
data = json.loads(r.stdout)
|
||||
assert data['ok'] is True
|
||||
assert 'symbols' in data['config']
|
||||
|
||||
|
||||
def test_once_live_public_data():
|
||||
# Coinbase scans can take longer when the watch list is large and the
|
||||
# service is also holding the file lock during its own cycle.
|
||||
r = subprocess.run([sys.executable, str(ROOT / 'bot.py'), '--once'], cwd=ROOT, capture_output=True, text=True, timeout=180)
|
||||
assert r.returncode == 0, r.stderr
|
||||
data = json.loads(r.stdout)
|
||||
assert 'equity_usd' in data
|
||||
state = json.loads((ROOT / 'data' / 'state.json').read_text())
|
||||
assert state['last_signals']
|
||||
|
||||
|
||||
def test_close_position_subtracts_buy_and_sell_fees(monkeypatch):
|
||||
events = []
|
||||
monkeypatch.setattr(bot, 'log_event', lambda ev: events.append(copy.deepcopy(ev)))
|
||||
st = {
|
||||
'cash_usd': 0.0,
|
||||
'realized_pnl_usd': 0.0,
|
||||
'daily': {'realized_pnl_usd': 0.0},
|
||||
'positions': {
|
||||
'TST-USD': {
|
||||
'qty': 10.0,
|
||||
'avg_entry': 1.0,
|
||||
'buy_fee_usd': 0.04,
|
||||
}
|
||||
},
|
||||
'last_trade_at': {},
|
||||
}
|
||||
cfg = {'take_profit_pct': 1.0, 'stop_loss_pct': 1.0, 'fee_bps': 40}
|
||||
ev = bot.close_position_if_needed(st, cfg, 'TST-USD', 1.02)
|
||||
assert ev is not None
|
||||
# gross gain = $0.20, sell fee = $0.0408, buy fee = $0.04, net = $0.1192
|
||||
assert round(ev['realized_pnl_usd'], 4) == 0.1192
|
||||
assert ev['buy_fee_usd'] == 0.04
|
||||
assert round(st['realized_pnl_usd'], 4) == 0.1192
|
||||
|
||||
|
||||
def test_close_shadow_position_subtracts_buy_and_sell_fees(monkeypatch):
|
||||
events = []
|
||||
monkeypatch.setattr(bot, 'log_event', lambda ev: events.append(copy.deepcopy(ev)))
|
||||
st = {
|
||||
'shadow_realized_pnl_usd': 0.0,
|
||||
'shadow_positions': {
|
||||
'TST-USD': {
|
||||
'qty': 10.0,
|
||||
'avg_entry': 1.0,
|
||||
'buy_fee_usd': 0.04,
|
||||
}
|
||||
},
|
||||
'shadow_last_trade_at': {},
|
||||
}
|
||||
cfg = {'take_profit_pct': 1.0, 'stop_loss_pct': 1.0, 'fee_bps': 40}
|
||||
ev = bot.close_shadow_position_if_needed(st, cfg, 'TST-USD', 1.02)
|
||||
assert ev is not None
|
||||
assert round(ev['realized_pnl_usd'], 4) == 0.1192
|
||||
assert ev['buy_fee_usd'] == 0.04
|
||||
assert round(st['shadow_realized_pnl_usd'], 4) == 0.1192
|
||||
|
||||
|
||||
def test_trailing_stop_locks_in_winner_before_full_take_profit(monkeypatch):
|
||||
events = []
|
||||
monkeypatch.setattr(bot, 'log_event', lambda ev: events.append(copy.deepcopy(ev)))
|
||||
st = {
|
||||
'cash_usd': 0.0,
|
||||
'realized_pnl_usd': 0.0,
|
||||
'daily': {'realized_pnl_usd': 0.0},
|
||||
'positions': {
|
||||
'TST-USD': {
|
||||
'qty': 10.0,
|
||||
'avg_entry': 1.0,
|
||||
'buy_fee_usd': 0.04,
|
||||
'peak_price': 1.02,
|
||||
}
|
||||
},
|
||||
'last_trade_at': {},
|
||||
}
|
||||
cfg = {
|
||||
'take_profit_pct': 3.0,
|
||||
'stop_loss_pct': 1.2,
|
||||
'fee_bps': 40,
|
||||
'trailing_stop_trigger_pct': 1.6,
|
||||
'trailing_stop_giveback_pct': 0.85,
|
||||
'breakeven_stop_trigger_pct': 1.4,
|
||||
'breakeven_stop_pct': 0.9,
|
||||
}
|
||||
ev = bot.close_position_if_needed(st, cfg, 'TST-USD', 1.011)
|
||||
assert ev is not None
|
||||
assert ev['reason'] == 'trailing_stop'
|
||||
assert ev['realized_pnl_usd'] > 0
|
||||
|
||||
|
||||
def test_breakeven_stop_cuts_roundtrip_before_it_turns_negative(monkeypatch):
|
||||
events = []
|
||||
monkeypatch.setattr(bot, 'log_event', lambda ev: events.append(copy.deepcopy(ev)))
|
||||
st = {
|
||||
'cash_usd': 0.0,
|
||||
'realized_pnl_usd': 0.0,
|
||||
'daily': {'realized_pnl_usd': 0.0},
|
||||
'positions': {
|
||||
'TST-USD': {
|
||||
'qty': 10.0,
|
||||
'avg_entry': 1.0,
|
||||
'buy_fee_usd': 0.04,
|
||||
'peak_price': 1.015,
|
||||
}
|
||||
},
|
||||
'last_trade_at': {},
|
||||
}
|
||||
cfg = {
|
||||
'take_profit_pct': 3.0,
|
||||
'stop_loss_pct': 1.2,
|
||||
'fee_bps': 40,
|
||||
'trailing_stop_trigger_pct': 1.6,
|
||||
'trailing_stop_giveback_pct': 0.85,
|
||||
'breakeven_stop_trigger_pct': 1.4,
|
||||
'breakeven_stop_pct': 0.9,
|
||||
}
|
||||
ev = bot.close_position_if_needed(st, cfg, 'TST-USD', 1.009)
|
||||
assert ev is not None
|
||||
assert ev['reason'] == 'breakeven_stop'
|
||||
assert ev['realized_pnl_usd'] > 0
|
||||
@@ -0,0 +1,29 @@
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
import validate
|
||||
|
||||
|
||||
@pytest.mark.parametrize('prefix', ['paper', 'shadow'])
|
||||
@pytest.mark.parametrize('events, expected', [
|
||||
([('buy', {'fee_usd': .04}), ('sell', {'buy_fee_usd': .04, 'realized_pnl_usd': .1192})], '$0.12'),
|
||||
([('buy', {'fee_usd': .04}), ('sell', {'realized_pnl_usd': .1592})], '$0.12'),
|
||||
([('buy', {'fee_usd': .04}), ('sell', {'buy_fee_usd': .04, 'realized_pnl_usd': .1192}),
|
||||
('buy', {'fee_usd': .08}), ('sell', {'realized_pnl_usd': .20})], '$0.24'),
|
||||
])
|
||||
def test_closed_report_counts_entry_fee_once(tmp_path, monkeypatch, capsys, prefix, events, expected):
|
||||
trades = tmp_path / 'trades.jsonl'
|
||||
trades.write_text('\n'.join(json.dumps(dict(type=prefix+'_'+kind, symbol='TST-USD', **values)) for kind, values in events))
|
||||
monkeypatch.setattr(validate, 'TRADES', trades)
|
||||
monkeypatch.setattr(validate, 'load_json', lambda path, default: {'watch_only_symbols': ['TST-USD']} if path == validate.CONFIG else {'last_scan': {'ts': validate.datetime.now(validate.LOCAL_TZ).isoformat()}})
|
||||
monkeypatch.setattr(validate, 'sh', lambda *a, **kw: SimpleNamespace(stdout='active\nactive\nactive\n', returncode=0))
|
||||
class Response:
|
||||
status = 200
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *args): pass
|
||||
def read(self, size): return b'Local Crypto Dip Agent'
|
||||
monkeypatch.setattr(validate, 'urlopen', lambda *a, **kw: Response())
|
||||
assert validate.main() == 0
|
||||
output = capsys.readouterr().out
|
||||
label = 'Fee-adjusted closed net: paper ' if prefix == 'paper' else 'Fee-adjusted shadow net: '
|
||||
assert label + expected + ' |' in output
|
||||
@@ -0,0 +1,44 @@
|
||||
from datetime import datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
import validate
|
||||
|
||||
@pytest.fixture
|
||||
def report(monkeypatch, tmp_path, capsys):
|
||||
cfg = {'starting_cash_usd':100, 'scan_interval_seconds':900}
|
||||
state = {'mode':'paper', 'starting_cash_usd':100, 'cash_usd':96,
|
||||
'equity_high_watermark_usd':120,
|
||||
'last_scan':{'ts':datetime.now(validate.LOCAL_TZ).isoformat(), 'equity_usd':96}}
|
||||
monkeypatch.setattr(validate, 'load_json', lambda path, default: cfg if path == validate.CONFIG else state)
|
||||
monkeypatch.setattr(validate, 'TRADES', tmp_path/'absent')
|
||||
monkeypatch.setattr(validate, 'sh', lambda *a, **kw: SimpleNamespace(stdout='active\nactive\nactive\n', returncode=0))
|
||||
class Response:
|
||||
status=200
|
||||
def __enter__(self): return self
|
||||
def __exit__(self,*a): pass
|
||||
def read(self,n): return b'Local Crypto Dip Agent'
|
||||
monkeypatch.setattr(validate, 'urlopen', lambda *a,**kw: Response())
|
||||
def run():
|
||||
status=validate.main()
|
||||
return status, capsys.readouterr().out
|
||||
return state, run
|
||||
|
||||
|
||||
def test_report_separates_health_return_and_peak_drawdown(report):
|
||||
state, run = report
|
||||
status, text = run()
|
||||
assert status == 0
|
||||
assert 'Operational checks: OK | Performance: BELOW START' in text
|
||||
assert 'return -4.00%' in text
|
||||
assert 'drawdown from recorded peak 20.00%' in text
|
||||
assert 'Mode: paper' in text
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stamp', [None, 'bad', '2020-01-01T00:00:00+00:00', '2999-01-01T00:00:00+00:00'])
|
||||
def test_untrustworthy_scan_reports_attention(report, stamp):
|
||||
state, run = report
|
||||
state['last_scan']['ts'] = stamp
|
||||
status, text = run()
|
||||
assert status == 1
|
||||
assert 'Operational checks: ATTENTION' in text
|
||||
assert 'scan timestamp' in text
|
||||
Executable
+172
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.request import urlopen
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
STATE = ROOT / "data" / "state.json"
|
||||
TRADES = ROOT / "data" / "trades.jsonl"
|
||||
CONFIG = ROOT / "config.json"
|
||||
LOCAL_TZ = ZoneInfo("America/New_York")
|
||||
|
||||
|
||||
def sh(cmd, timeout=20):
|
||||
return subprocess.run(cmd, shell=True, cwd=str(ROOT), text=True, capture_output=True, timeout=timeout)
|
||||
|
||||
|
||||
def money(x):
|
||||
return f"${float(x):.2f}"
|
||||
|
||||
|
||||
def load_json(path, default):
|
||||
try:
|
||||
return json.loads(path.read_text())
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
|
||||
def main():
|
||||
now = datetime.now(LOCAL_TZ).isoformat()
|
||||
cfg = load_json(CONFIG, {})
|
||||
st = load_json(STATE, {})
|
||||
lines = []
|
||||
problems = []
|
||||
|
||||
services = ["local-trading-agent.service", "local-trading-dashboard.service", "trader-reverse-tunnel.service"]
|
||||
svc = sh("systemctl is-active " + " ".join(services), timeout=20)
|
||||
svc_states = svc.stdout.strip().splitlines()
|
||||
for name, state in zip(services, svc_states):
|
||||
if state != "active":
|
||||
problems.append(f"{name} is {state or 'unknown'}")
|
||||
|
||||
public_ok = False
|
||||
public_code = "ERR"
|
||||
try:
|
||||
with urlopen("https://trader.nannery.pro", timeout=20) as r:
|
||||
body = r.read(200).decode("utf-8", "ignore")
|
||||
public_code = str(r.status)
|
||||
public_ok = r.status == 200 and "Local Crypto Dip Agent" in body
|
||||
except Exception as e:
|
||||
public_code = type(e).__name__
|
||||
if not public_ok:
|
||||
problems.append(f"public dashboard validation failed: {public_code}")
|
||||
|
||||
cfg_check = sh("python3 bot.py --config-check", timeout=30)
|
||||
if cfg_check.returncode != 0:
|
||||
problems.append("bot config-check failed")
|
||||
|
||||
last_scan = st.get("last_scan") or {}
|
||||
scan_age = None
|
||||
stale_after = max(900.0, 3 * float(cfg.get("scan_interval_seconds", 300)))
|
||||
try:
|
||||
stamp = datetime.fromisoformat(last_scan.get("ts") or "")
|
||||
if stamp.tzinfo is None:
|
||||
raise ValueError("timezone missing")
|
||||
scan_age = (datetime.fromisoformat(now) - stamp).total_seconds()
|
||||
if scan_age < -60:
|
||||
problems.append("scan timestamp is in the future")
|
||||
elif scan_age > stale_after:
|
||||
problems.append(f"scan timestamp is stale: {scan_age / 60:.1f} minutes old")
|
||||
except (ValueError, TypeError):
|
||||
problems.append("scan timestamp missing or invalid")
|
||||
lines.append(f"Last scan: {last_scan.get('ts') or 'unknown'} | stale threshold {stale_after / 60:.1f} minutes")
|
||||
signals = st.get("last_signals") or []
|
||||
bad_signals = [x for x in signals if x.get("status") == "error"]
|
||||
if bad_signals:
|
||||
problems.append("bad market signals: " + ", ".join(x.get("symbol", "?") for x in bad_signals))
|
||||
|
||||
cash = float(st.get("cash_usd", 0))
|
||||
start = float(st.get("starting_cash_usd", cfg.get("starting_cash_usd", 0) or 0))
|
||||
equity = float(last_scan.get("equity_usd", cash))
|
||||
realized = float(st.get("realized_pnl_usd", 0))
|
||||
return_pct = ((equity - start) / start * 100) if start else 0.0
|
||||
peak = max(float(st.get("equity_high_watermark_usd", start)), equity)
|
||||
drawdown_pct = ((peak - equity) / peak * 100) if peak else 0.0
|
||||
positions = st.get("positions", {})
|
||||
exposure = sum(float(p.get("notional_usd", 0)) for p in positions.values())
|
||||
max_exposure = equity * float(cfg.get("max_total_position_pct_of_equity", 1.0))
|
||||
if exposure > max_exposure + 0.01:
|
||||
problems.append(f"exposure too high: {money(exposure)} > cap {money(max_exposure)}")
|
||||
|
||||
# Summarize closed losses since log start.
|
||||
events = []
|
||||
if TRADES.exists():
|
||||
for line in TRADES.read_text().splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
events.append(json.loads(line))
|
||||
except Exception:
|
||||
pass
|
||||
sells = [e for e in events if e.get("type") == "paper_sell"]
|
||||
losses = [e for e in sells if float(e.get("realized_pnl_usd", 0)) < 0]
|
||||
wins = [e for e in sells if float(e.get("realized_pnl_usd", 0)) >= 0]
|
||||
shadow_sells = [e for e in events if e.get("type") == "shadow_sell"]
|
||||
shadow_wins = [e for e in shadow_sells if float(e.get("realized_pnl_usd", 0)) >= 0]
|
||||
shadow_losses = [e for e in shadow_sells if float(e.get("realized_pnl_usd", 0)) < 0]
|
||||
shadow_positions = st.get("shadow_positions", {})
|
||||
|
||||
def fee_adjusted_net(prefix):
|
||||
pending_buy_fees = {}
|
||||
net = 0.0
|
||||
for e in events:
|
||||
sym = e.get("symbol")
|
||||
if e.get("type") == prefix + "_buy":
|
||||
pending_buy_fees.setdefault(sym, []).append(float(e.get("fee_usd", 0)))
|
||||
elif e.get("type") == prefix + "_sell":
|
||||
# Consume the matching entry even when the sell is already net.
|
||||
matched_fee = pending_buy_fees[sym].pop(0) if pending_buy_fees.get(sym) else 0.0
|
||||
# Current engine events include entry fees in realized P&L.
|
||||
# Legacy sells lack buy_fee_usd and need the entry fee deducted.
|
||||
buy_fee = 0.0 if "buy_fee_usd" in e else matched_fee
|
||||
net += float(e.get("realized_pnl_usd", 0)) - buy_fee
|
||||
return net
|
||||
|
||||
paper_buy_fees = sum(float(e.get("fee_usd", 0)) for e in events if e.get("type") == "paper_buy")
|
||||
shadow_buy_fees = sum(float(e.get("fee_usd", 0)) for e in events if e.get("type") == "shadow_buy")
|
||||
net_paper = fee_adjusted_net("paper")
|
||||
net_shadow = fee_adjusted_net("shadow")
|
||||
|
||||
status = "OK" if not problems else "ATTENTION"
|
||||
performance = "UNKNOWN" if start <= 0 else "BELOW START" if equity < start else "ABOVE START" if equity > start else "FLAT"
|
||||
lines.append(f"Trader hourly validation — Operational checks: {status} | Performance: {performance}")
|
||||
lines.append(f"Mode: {st.get('mode', 'unknown')}")
|
||||
lines.append(f"Local time: {now}")
|
||||
lines.append(f"Public: https://trader.nannery.pro ({public_code})")
|
||||
lines.append(f"Capital: start {money(start)} | equity {money(equity)} | cash {money(cash)} | realized {money(realized)} | return {return_pct:+.2f}% | drawdown from recorded peak {drawdown_pct:.2f}%")
|
||||
lines.append(f"Open: {len(positions)} positions | exposure {money(exposure)}")
|
||||
if positions:
|
||||
for sym, p in positions.items():
|
||||
entry = float(p.get("avg_entry", 0)); last = float(p.get("last_price", entry)); qty = float(p.get("qty", 0))
|
||||
pnl = (last - entry) * qty
|
||||
pct = ((last / entry - 1) * 100) if entry else 0
|
||||
lines.append(f"- {sym}: unreal {money(pnl)} ({pct:.2f}%)")
|
||||
lines.append(f"Closed trades: {len(sells)} total | wins {len(wins)} | losses {len(losses)} | loss total {money(sum(float(e.get('realized_pnl_usd',0)) for e in losses))}")
|
||||
lines.append(f"Fee-adjusted closed net: paper {money(net_paper)} | paper buy fees paid {money(paper_buy_fees)}")
|
||||
if cfg.get("watch_only_symbols"):
|
||||
shadow_pnl = float(st.get("shadow_realized_pnl_usd", 0.0))
|
||||
lines.append(f"Watch-only shadow: realized {money(shadow_pnl)} | closed {len(shadow_sells)} | wins {len(shadow_wins)} | losses {len(shadow_losses)} | open {len(shadow_positions)}")
|
||||
lines.append(f"Fee-adjusted shadow net: {money(net_shadow)} | shadow buy fees paid {money(shadow_buy_fees)}")
|
||||
for sym, p in shadow_positions.items():
|
||||
entry = float(p.get("avg_entry", 0)); last = float(p.get("last_price", entry)); qty = float(p.get("qty", 0))
|
||||
pnl = (last - entry) * qty
|
||||
pct = ((last / entry - 1) * 100) if entry else 0
|
||||
lines.append(f"- WATCH {sym}: unreal {money(pnl)} ({pct:.2f}%)")
|
||||
if bad_signals:
|
||||
lines.append("Signal errors: " + ", ".join(f"{x.get('symbol')}={x.get('error')}" for x in bad_signals))
|
||||
if problems:
|
||||
lines.append("Problems:")
|
||||
lines.extend(f"- {p}" for p in problems)
|
||||
else:
|
||||
lines.append("No service/config/public-route problems detected.")
|
||||
|
||||
print("\n".join(lines))
|
||||
return 1 if problems else 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user