From d6ee92dbb728892371a65606b84225388da860c2 Mon Sep 17 00:00:00 2001 From: pnannery Date: Fri, 11 Sep 2026 06:53:10 -0400 Subject: [PATCH] feat: deploy five-market paper trading profile --- .dockerignore | 5 + .env.example | 3 + .gitignore | 5 +- Dockerfile | 7 ++ README.md | 123 ++++++++++++++++++++ bot.py | 47 ++++++-- compose.yaml | 18 +++ config-five.json | 16 +++ config.json | 3 +- dashboard.py | 103 +++++++++++----- find_winners.py | 0 five_market.py | 264 ++++++++++++++++++++++++++++++++++++++++++ promote_winners.py | 0 test_five_market.py | 92 +++++++++++++++ test_risk_controls.py | 69 +++++++++++ test_watchlist.py | 24 ++++ validate.py | 0 watchlist.json | 33 ++++++ watchlist.py | 40 +++++++ 19 files changed, 811 insertions(+), 41 deletions(-) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 Dockerfile mode change 100755 => 100644 bot.py create mode 100644 compose.yaml create mode 100644 config-five.json mode change 100755 => 100644 dashboard.py mode change 100755 => 100644 find_winners.py create mode 100644 five_market.py mode change 100755 => 100644 promote_winners.py create mode 100644 test_five_market.py create mode 100644 test_risk_controls.py create mode 100644 test_watchlist.py mode change 100755 => 100644 validate.py create mode 100644 watchlist.json create mode 100644 watchlist.py 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 Crypto Dip Agent -

Local Crypto Dip Agent paper mode

Local dashboard. No live exchange execution.

Recent audit log


+AGENT='bot.py'
+SCAN_LOCK=threading.Lock()
+INDEX='''Local Trading Agent

Local Trading Agent / paper

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

Equity history

Positions

MarketQuantityEntryLast markStopUnrealized*

*Includes entry fees; excludes estimated exit costs.

Market signals

MarketStrategyTimeframePriceDecision / data status

Token research watchlist

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.

Recent audit log

''' + +def report_text(st): + scan=st.get('last_scan') or {} + eq=scan.get('equity_usd',st.get('cash_usd',st.get('starting_cash_usd',100))) + start=st.get('starting_cash_usd',100) + lines=['LOCAL TRADING AGENT — PAPER REPORT',f"Profile: {st.get('profile','crypto-dip')}", + f"Last scan: {scan.get('ts','never')}",f'Equity: ${eq:.2f}', + f"Cash: ${st.get('cash_usd',0):.2f}",f'Return: {(eq/start-1)*100:.2f}%', + f"Realized net: ${st.get('realized_pnl_usd',0):.2f}", + f"Entry pause: {scan.get('block_reason') or 'none'}",''] + for sig in st.get('last_signals',[]): + lines.append(f"{sig['symbol']}: {sig.get('strategy','dip')} — {sig.get('error') or sig.get('entry_block') or ('entry signal' if sig.get('entry') else 'wait')}") + lines+=['','ETF marks may be old while sessions are closed. Stops are polled, not broker-held.', + 'Fees/slippage are estimates. No real orders. No income guarantee.'] + return '\n'.join(lines) + + 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 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.send_header('Cache-Control','no-store');self.send_header('X-Content-Type-Options','nosniff');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=='/':return self.send(200,INDEX,'text/html; charset=utf-8') + if p=='/api/watchlist':return self.send(200,json.dumps(watchlist.read())) + if p=='/api/state':return self.send(200,STATE.read_text() if STATE.exists() else '{}') + if p=='/api/report':return self.send(200,report_text(json.loads(STATE.read_text()) if STATE.exists() else {}),'text/plain; charset=utf-8') 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'})) + from collections import deque + if not TRADES.exists():return self.send(200,'','text/plain') + with TRADES.open() as f:body=''.join(deque(f,maxlen=100)) + return self.send(200,body,'text/plain; charset=utf-8') + 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)) + if urlparse(self.path).path=='/api/watchlist': + if self.headers.get('X-Local-Scan')!='1':return self.send(403,'{}') + try: + length=int(self.headers.get('Content-Length','0')) + if not 0 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): + raise RuntimeError('Invalid candle prices') + if len(candles) < 60: + raise RuntimeError('Need at least 60 completed candles') + return candles + + +def fetch_market(symbol): + seconds = MARKETS[symbol][2] + now = time.time() + if symbol == 'BTC-USD': + candles = bot.fetch_coinbase_candles(symbol, 250, seconds) + ticker = bot.http_json('https://api.exchange.coinbase.com/products/BTC-USD/ticker') + price, price_ts = float(ticker['price']), timestamp(ticker['time']) + else: + start = datetime.now(timezone.utc) - timedelta(days=180 if seconds == 14400 else 14) + query = {'timeframe': '4Hour' if seconds == 14400 else '15Min', + 'start': start.isoformat(), 'end': datetime.now(timezone.utc).isoformat(), + 'limit': 1000, 'sort': 'desc', 'adjustment': 'raw', 'feed': 'iex'} + response = alpaca_json(f'/v2/stocks/{symbol}/bars', query) + candles = [bot.Candle(int(timestamp(b['t'])), b['l'], b['h'], b['o'], b['c'], b['v']) + for b in response.get('bars') or [] if timestamp(b['t']) + seconds <= now] + trade = alpaca_json(f'/v2/stocks/{symbol}/trades/latest', {'feed':'iex'})['trade'] + price, price_ts = float(trade['p']), timestamp(trade['t']) + if not math.isfinite(price) or price <= 0 or not -60 <= now-price_ts <= 900: + raise RuntimeError('Latest trade missing, stale or invalid; no orders simulated.') + candles = valid_bars(candles) + # Allow previous-session bars at the open, but reject data older than a long weekend. + max_age = seconds*2 if symbol == 'BTC-USD' else max(seconds*2, 4*86400) + if now-(candles[-1].ts+seconds) > max_age: + raise RuntimeError('Strategy candles are stale') + return candles, price + + +def strategy_signal(candles, symbol): + c = valid_bars(candles) + closes = [x.close for x in c] + mean = lambda a: sum(a)/len(a) + sma20, sma50 = mean(closes[-20:]), mean(closes[-50:]) + atr = mean([max(c[i].high-c[i].low, abs(c[i].high-c[i-1].close), abs(c[i].low-c[i-1].close)) for i in range(len(c)-14,len(c))]) + kind = MARKETS[symbol][1] + if kind == 'mean_reversion': + sd = math.sqrt(mean([(v-sma20)**2 for v in closes[-20:]])) + enter, leave = closes[-1] < sma20-2*sd, closes[-1] >= sma20 + reason = 'Close below 20-bar mean minus 2 standard deviations; exit at mean.' + elif kind == 'breakout': + enter = closes[-1] > max(x.high for x in c[-21:-1]) + leave = closes[-1] < min(x.low for x in c[-11:-1]) + reason = 'Close above previous 20 highs; exit below previous 10 lows.' + else: + prev20, prev50 = mean(closes[-21:-1]), mean(closes[-51:-1]) + enter = sma20 > sma50 and prev20 <= prev50 + leave = sma20 < sma50 + reason = '20-bar average crosses above 50; exit when 20 is below 50.' + return {'entry':enter, 'exit':leave, 'atr_pct':atr/closes[-1]*100, + 'bar_ts':c[-1].ts, 'strategy':kind, 'rule':reason, + 'fair_value':sma20, 'gap_pct':(sma20-closes[-1])/sma20*100} + + +def costs(cfg, symbol): + c = cfg['costs']['crypto' if symbol == 'BTC-USD' else 'etf'] + return c['fee_bps']/10000, c['slippage_bps']/10000 + + +def size_position(st, cfg, symbol, price, atr_pct): + eq = bot.equity(st,{}) + fee, slip = costs(cfg,symbol) + entry = price*(1+slip) + stop_fraction = cfg['stop_loss_pct']/100 + # Includes both fees and an allowance for both sides of slippage; gaps remain unbounded. + loss_fraction = stop_fraction + 2*fee + 2*slip + risk_budget = eq*cfg['risk_per_trade_pct']/100 + used_risk = sum(p.get('planned_risk_usd',0) for p in st['positions'].values()) + risk_budget = min(risk_budget, max(0,eq*cfg['max_portfolio_risk_pct']/100-used_risk)) + exposure = sum(p['qty']*p.get('last_price',p['avg_entry']) for p in st['positions'].values()) + volatility_factor = min(1, cfg['stop_loss_pct']/max(atr_pct*2,.0001)) + notional = min(risk_budget/max(loss_fraction,.0001), + eq*cfg['max_position_pct']/100*volatility_factor, + max(0,eq*cfg['max_total_exposure_pct']/100-exposure), + st['cash_usd']/(1+fee)) + return max(0,notional), entry, loss_fraction + + +def sell(st,cfg,symbol,price,reason): + p=st['positions'][symbol] + fee,slip=costs(cfg,symbol) + fill=price*(1-slip) + exit_fee=p['qty']*fill*fee + proceeds=p['qty']*fill-exit_fee + pnl=proceeds-p['qty']*p['avg_entry']-p['buy_fee_usd'] + st['cash_usd']+=proceeds + st['realized_pnl_usd']+=pnl + st['daily']['realized_pnl_usd']+=pnl + st.setdefault('last_trade_at',{})[symbol]=bot.now_iso() + del st['positions'][symbol] + ev={'type':'paper_sell','symbol':symbol,'price':fill,'qty':p['qty'],'fee_usd':exit_fee, + 'buy_fee_usd':p['buy_fee_usd'],'realized_pnl_usd':pnl,'reason':reason,'strategy':p['strategy']} + bot.log_event(ev) + return ev + + +def scan_once(cfg,st,fetcher=None,clock=None): + fetcher=fetcher or fetch_market + bot.roll_daily(st,bot.equity(st,{})) + events=[]; signals=[]; good={}; closed=set(); errors=set() + try: + is_open=bool((clock or (lambda:alpaca_json('/v2/clock',trading=True)))()['is_open']) + clock_error=None + except Exception as exc: + is_open=False;clock_error=str(exc) + for symbol,(name,kind,seconds) in MARKETS.items(): + if symbol!='BTC-USD' and not is_open: + signals.append({'symbol':symbol,'status':'error' if clock_error else 'closed', + 'error':clock_error or 'ETF session closed; existing marks retained.', + 'strategy':kind,'timeframe_seconds':seconds}) + if clock_error: errors.add(symbol) + continue + try: + candles,price=fetcher(symbol) + sig=strategy_signal(candles,symbol) + sig.update(symbol=symbol,name=name,price=price,status='ok',timeframe_seconds=seconds) + signals.append(sig);good[symbol]=sig + if symbol in st['positions']:st['positions'][symbol]['last_price']=price + except Exception as exc: + signals.append({'symbol':symbol,'status':'error','error':str(exc),'strategy':kind}) + errors.add(symbol) + bot.daily_loss_blocked(st,cfg,bot.equity(st,{})) + for symbol,sig in good.items(): + if symbol in st['positions']: + p=st['positions'][symbol] + reason='stop_loss' if sig['price']<=p['stop_price'] else 'strategy_exit' if sig['exit'] else None + if reason:events.append(sell(st,cfg,symbol,sig['price'],reason));closed.add(symbol) + blocked,reason=bot.daily_loss_blocked(st,cfg,bot.equity(st,{})) + missing=sorted(set(st['positions']) & errors) + if missing:blocked,reason=True,'missing_position_prices' + consumed=st.setdefault('last_entry_signal_bar',{}) + for symbol,sig in good.items(): + if symbol in st['positions'] or symbol in closed or not sig['entry']: + continue + if consumed.get(symbol)==sig['bar_ts']: + sig['entry_block']='Signal already processed';continue + risk_block,risk_reason=bot.daily_loss_blocked(st,cfg,bot.equity(st,{})) + if blocked or risk_block: + sig['entry_block']=reason or risk_reason;continue + if symbol in RISK_ON and RISK_ON.intersection(st['positions']): + sig['entry_block']='Risk-on group already holds SPY, QQQ or BTC';continue + notional,entry,loss_fraction=size_position(st,cfg,symbol,sig['price'],sig['atr_pct']) + if notional