diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3d265c8 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +.env +.git +data +__pycache__ +*.zip diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..bf5285a --- /dev/null +++ b/.env.example @@ -0,0 +1,3 @@ +# Alpaca PAPER account keys, used ONLY to read ETF market data and market clock. +APCA_API_KEY_ID= +APCA_API_SECRET_KEY= diff --git a/.gitignore b/.gitignore index 5ad42e4..8c26cc9 100644 --- a/.gitignore +++ b/.gitignore @@ -4,10 +4,7 @@ __pycache__/ .pytest_cache/ # Runtime trading state / audit logs -data/*.json -data/*.jsonl -data/*.lock -data/scan.lock +data/ # Local backups created during tuning config.json.bak* diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..caf42cb --- /dev/null +++ b/Dockerfile @@ -0,0 +1,7 @@ +FROM python:3.12-slim +WORKDIR /app +COPY *.py *.json /app/ +RUN useradd --uid 10001 --create-home trader && mkdir -p /app/data && chown trader:trader /app/data +USER trader +EXPOSE 8765 +CMD ["python", "dashboard.py", "--profile", "five", "--host", "0.0.0.0"] diff --git a/README.md b/README.md index 57b4de7..38b2ef1 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,111 @@ +# Local Trading Agent — five-market paper profile + +This update extends the existing app. It does not place real orders or promise income. +The original crypto-dip profile remains available via `python3 bot.py --loop`. + +## Five markets + +| Instrument | Strategy | Completed candle timeframe | +|---|---|---| +| SPY — S&P 500 ETF | Buy close below SMA(20) minus 2 standard deviations; exit at SMA(20) | 15 minutes | +| QQQ — Nasdaq-100 ETF | Same mean-reversion rule | 15 minutes | +| BTC-USD — Bitcoin | Buy close above previous 20 highs; exit below previous 10 lows | 1 hour | +| GLD — gold ETF proxy | Buy SMA(20) crossing above SMA(50); exit when below | 4 hours | +| USO — oil ETF proxy | Same trend-following rule | 4 hours | + +These are explicit implementations of the Reel's vague strategy descriptions, not a reproduction of verified proprietary rules. GLD and USO are ETFs, not spot gold/oil. USO's futures exposure and roll effects can diverge from spot oil. + +## Run locally (Python 3.10+ on Linux) + +No third-party Python packages are needed by the app. Set `APCA_API_KEY_ID` and +`APCA_API_SECRET_KEY` in the environment to your Alpaca **paper-account** keys. +Do not commit keys or paste them into chat. The keys are used only for read-only +market data and the market clock; this app has no order endpoint calls. + +```bash +python3 five_market.py --config-check +python3 five_market.py --once +python3 five_market.py --loop +``` + +Run the dashboard in another terminal: + +```bash +python3 dashboard.py --profile five --host 127.0.0.1 --port 8765 +``` + +Open http://127.0.0.1:8765. The worker scans every five minutes. The dashboard +can also request a scan and download a current text report. There is no automatic +email/Discord delivery or AI self-modification in this release. + +Without Alpaca keys, ETF rows report a setup error; BTC can still scan using +public Coinbase data. Existing ETF positions with unavailable market status block +new entries across the account. When the ETF session is legitimately closed, +those positions retain their previous marks and BTC may continue. + +## Docker / Unraid starting point + +Copy `.env.example` to `.env`, fill in the two paper-account credentials, then: + +```bash +docker compose up -d --build +``` + +The included Compose file runs a worker and dashboard sharing one persistent +`trading-data` volume. It binds the dashboard to the Docker host's loopback +interface only. Use your authenticated reverse proxy for remote access. The +app has no built-in authentication; do not expose it directly to the Internet. +This package is not an installed Unraid Community Applications template. +Docker image build and installation on your host were not tested here. + +## Account and risk controls + +- Separate $100 ledger in `data/five-market/`; original `data/state.json` is untouched. +- $0.50 maximum planned risk per trade at the initial balance; 1.5% aggregate planned risk. +- Stop trigger 1% below simulated entry. Current sampled price determines exit fills. +- Volatility (ATR 14) reduces position allocation; 35% individual and 75% total exposure caps. +- One position across SPY, QQQ and BTC combined. This is a fixed exposure group, + not a statistical rolling-correlation estimate. SPY receives priority when simultaneous signals compete. +- 2% daily equity-loss pause, latched until the next New York calendar day; 6% drawdown pause. +- Fees and slippage on both entry and exit, configurable separately for ETFs and crypto. +- Only completed strategy bars, fresh latest-trade checks, duplicate-entry prevention, + and a shared process lock around ledger updates. +- Unrealized gains/losses are included in portfolio equity; exit costs are charged on sale. + +**Stops are sampled every scan, not held at a broker.** They can be missed between +scans, during data failures or when the process stops, and losses can exceed the +planned risk. A provider/candle failure prevents action on that market, including +exits. ETFs only execute during Alpaca's regular-session clock; overnight gaps +remain exposed. Closed ETF marks can make portfolio equity stale. + +The IEX feed is not the consolidated stock market. Provider-aggregated 4-hour +bars may include activity outside regular trading hours; entries and exits in +this profile remain regular-session-only. Fees are configurable estimates, not +verified account-specific fees. Fractional paper sizes are not validated against +a broker's minimums, precision, cash settlement, account rules or order support. +There are no shorts, leverage, backtests or real-money execution in this release. + +## Verification + +```bash +python3 -m unittest test_five_market test_risk_controls test_watchlist -v +``` + +Offline tests cover all three signal families, timing, portfolio exposure, +cash accounting, costs, volatility sizing, duplicate entries, market closures, +stale data, daily loss handling and stop gaps. Real authenticated provider calls +and deployment still need validation on your host. The original pytest tests +remain included; pytest was not available in the build environment. + +Provider references: +- https://docs.alpaca.markets/us/reference/stockbars +- https://docs.alpaca.markets/us/docs/market-data-faq +- https://docs.cdp.coinbase.com/api-reference/exchange-api/rest-api/products/get-product-candles + +--- + +## Original app documentation + # Local Crypto Dip Agent Local-first autonomous **paper trading** agent for BTC/ETH dip detection. @@ -53,3 +161,18 @@ Do not add exchange keys with withdrawal permission. If live mode is ever added, - circuit breaker - external alerts - paper/live parity report + +## Research watchlist: XST, WOFI, UOTF + +The dashboard includes separate research records containing your supplied notes, +explicitly marked unverified. They are **not** added to either execution engine. +Enter and save the exact Solana mint for XST, WOFI and UOTF in the dashboard. +The app validates address encoding only; it does not confirm token identity or +mint-account ownership on chain. Fomo is a platform and is excluded from the watchlist. + +Records persist in `data/research-watchlist.json`, shared by dashboard profiles. +There is no on-chain analytics, price feed, liquidity inspection, rug detection, +sellability test, DEX swap integration or token endorsement in this watchlist. +Those require exact identities and further provider/execution work. Ticker names +alone must never select the asset to trade. Do not substitute these tokens for GLD +or USO: oil-themed token branding does not establish commodity ownership rights. diff --git a/bot.py b/bot.py old mode 100755 new mode 100644 index 82b37d1..cb6f6dd --- a/bot.py +++ b/bot.py @@ -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)}) diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..7793aea --- /dev/null +++ b/compose.yaml @@ -0,0 +1,18 @@ +services: + dashboard: + build: . + ports: + - "127.0.0.1:8765:8765" + env_file: .env + volumes: + - trading-data:/app/data + restart: unless-stopped + worker: + build: . + command: ["python", "five_market.py", "--loop"] + env_file: .env + volumes: + - trading-data:/app/data + restart: unless-stopped +volumes: + trading-data: diff --git a/config-five.json b/config-five.json new file mode 100644 index 0000000..3c4f58d --- /dev/null +++ b/config-five.json @@ -0,0 +1,16 @@ +{ + "starting_cash_usd": 100.0, + "scan_interval_seconds": 300, + "risk_per_trade_pct": 0.5, + "max_portfolio_risk_pct": 1.5, + "max_position_pct": 35.0, + "max_total_exposure_pct": 75.0, + "stop_loss_pct": 1.0, + "max_daily_loss_pct": 2.0, + "max_drawdown_pct": 6.0, + "min_trade_usd": 1.0, + "costs": { + "crypto": {"fee_bps": 40, "slippage_bps": 15}, + "etf": {"fee_bps": 0, "slippage_bps": 5} + } +} diff --git a/config.json b/config.json index 2e17b4c..e204703 100644 --- a/config.json +++ b/config.json @@ -87,5 +87,6 @@ "trailing_stop_trigger_pct": 1.6, "trailing_stop_giveback_pct": 0.85, "breakeven_stop_trigger_pct": 1.4, - "breakeven_stop_pct": 0.9 + "breakeven_stop_pct": 0.9, + "max_risk_per_trade_pct": 0.5 } diff --git a/dashboard.py b/dashboard.py old mode 100755 new mode 100644 index c5ccdc6..58b90d9 --- a/dashboard.py +++ b/dashboard.py @@ -1,5 +1,10 @@ #!/usr/bin/env python3 -import argparse, json, subprocess, sys +import argparse +import json +import subprocess +import sys +import threading +import watchlist from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler from pathlib import Path from urllib.parse import urlparse @@ -7,40 +12,82 @@ from urllib.parse import urlparse ROOT=Path(__file__).resolve().parent STATE=ROOT/'data'/'state.json' TRADES=ROOT/'data'/'trades.jsonl' - -INDEX = '''
Local dashboard. No live exchange execution.
Loading account…
No real orders. Stops are checked during scans and may fill beyond 1%. $100 → $3,000 requires 2,900% growth; it is a goal, not an expected result.
Download report| Market | Quantity | Entry | Last mark | Stop | Unrealized* |
|---|
*Includes entry fees; excludes estimated exit costs.
| Market | Strategy | Timeframe | Price | Decision / data status |
|---|
Research only — excluded from both trading engines. Notes below are user-supplied and unverified. Adding a mint records an identifier; it does not verify legitimacy, liquidity, sellability or ownership rights.