feat: deploy five-market paper trading profile

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

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
.env
.git
data
__pycache__
*.zip
+3
View File
@@ -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=
+1 -4
View File
@@ -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*
+7
View File
@@ -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"]
+123
View File
@@ -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.
Executable → Regular
+39 -8
View File
@@ -38,7 +38,7 @@ def default_state(cfg):
"equity_high_watermark_usd": float(cfg["starting_cash_usd"]),
"positions": {}, "last_trade_at": {},
"shadow_positions": {}, "shadow_last_trade_at": {}, "shadow_realized_pnl_usd": 0.0,
"daily": {"date": datetime.now(LOCAL_TZ).date().isoformat(), "realized_pnl_usd": 0.0},
"daily": {"date": datetime.now(LOCAL_TZ).date().isoformat(), "realized_pnl_usd": 0.0, "starting_equity_usd": float(cfg["starting_cash_usd"]), "blocked": False},
"last_scan": None, "last_signals": []
}
@@ -72,7 +72,12 @@ def fetch_coinbase_candles(symbol, hours, granularity):
url = f"https://api.exchange.coinbase.com/products/{symbol}/candles?granularity={granularity}&start={start_s}&end={end_s}"
raw = http_json(url)
candles = [Candle(int(x[0]), float(x[1]), float(x[2]), float(x[3]), float(x[4]), float(x[5])) for x in raw]
candles = [c for c in candles if c.ts + granularity <= end]
candles.sort(key=lambda c: c.ts)
if candles and end - (candles[-1].ts + granularity) > granularity * 2:
raise RuntimeError(f"stale candles for {symbol}")
if any(not all(math.isfinite(v) and v > 0 for v in (c.open, c.high, c.low, c.close)) or c.low > min(c.open, c.close) or c.high < max(c.open, c.close) for c in candles):
raise RuntimeError(f"invalid candles for {symbol}")
if len(candles) < 10:
raise RuntimeError(f"not enough candles for {symbol}: {len(candles)}")
return candles
@@ -142,18 +147,32 @@ def equity(st, prices):
eq += float(pos["qty"]) * px
return eq
def daily_loss_blocked(st, cfg, eq):
def roll_daily(st, eq):
today = datetime.now(LOCAL_TZ).date().isoformat()
if st.get("daily", {}).get("date") != today:
st["daily"] = {"date": today, "realized_pnl_usd": 0.0}
daily_loss_limit = -abs(cfg["max_daily_loss_pct"]) / 100 * max(st["starting_cash_usd"], eq)
if st["daily"]["realized_pnl_usd"] <= daily_loss_limit: return True, "daily_loss_limit"
st["daily"] = {"date": today, "realized_pnl_usd": 0.0,
"starting_equity_usd": eq, "blocked": False}
# Existing accounts migrate without discarding today's realized losses.
st["daily"].setdefault("starting_equity_usd",
float((st.get("last_scan") or {}).get("equity_usd", st["starting_cash_usd"])))
st["daily"].setdefault("blocked", False)
def daily_loss_blocked(st, cfg, eq):
roll_daily(st, eq)
high = max(float(st.get("equity_high_watermark_usd", eq)), eq)
st["equity_high_watermark_usd"] = high
baseline = float(st["daily"]["starting_equity_usd"])
daily_loss = max(baseline - eq, -float(st["daily"]["realized_pnl_usd"]))
if daily_loss >= baseline * abs(cfg["max_daily_loss_pct"]) / 100:
st["daily"]["blocked"] = True
if st["daily"]["blocked"]:
return True, "daily_loss_limit"
dd = (high - eq) / high * 100 if high > 0 else 0
if dd >= cfg["max_drawdown_pct"]: return True, "max_drawdown"
return False, None
def in_cooldown(st, cfg, sym):
last = st.get("last_trade_at", {}).get(sym)
if not last: return False
@@ -249,6 +268,7 @@ def close_position_if_needed(st, cfg, sym, price):
reason = "breakeven_stop"
if not reason:
pos["last_price"] = price; return None
price *= 1 - float(cfg.get("slippage_bps", 0)) / 10000
qty = float(pos["qty"]); gross = qty * price; fee = gross * cfg["fee_bps"] / 10000
buy_fee = float(pos.get("buy_fee_usd", 0.0))
proceeds = gross - fee; realized = proceeds - qty * entry - buy_fee
@@ -277,6 +297,7 @@ def close_shadow_position_if_needed(st, cfg, sym, price):
reason = "breakeven_stop"
if not reason:
pos["last_price"] = price; return None
price *= 1 - float(cfg.get("slippage_bps", 0)) / 10000
qty = float(pos["qty"]); gross = qty * price; fee = gross * cfg["fee_bps"] / 10000
buy_fee = float(pos.get("buy_fee_usd", 0.0))
proceeds = gross - fee; realized = proceeds - qty * entry - buy_fee
@@ -287,7 +308,7 @@ def close_shadow_position_if_needed(st, cfg, sym, price):
log_event(ev); return ev
def signal_has_fee_aware_edge(cfg, signal):
round_trip_cost_pct = (2 * cfg["fee_bps"] + cfg["slippage_bps"]) / 100.0
round_trip_cost_pct = (2 * cfg["fee_bps"] + 2 * cfg["slippage_bps"]) / 100.0
required_gap = cfg["min_gap_pct"] + round_trip_cost_pct + cfg.get("min_edge_after_cost_pct", 0.0)
if signal["gap_pct"] < required_gap:
return False
@@ -317,12 +338,16 @@ def maybe_open_position(st, cfg, signal, eq):
return None
reliability = min(1.0, max(0.0, (signal["gap_pct"] - cfg["min_gap_pct"]) / max(0.01, cfg["strong_gap_pct"] - cfg["min_gap_pct"])))
reliability *= min(1.0, signal["gap_pct"] / max(signal["volatility_pct"], 0.01))
open_exposure = sum(float(p.get("notional_usd", 0.0)) for p in st.get("positions", {}).values())
open_exposure = sum(float(p["qty"]) * float(p.get("last_price", p["avg_entry"])) for p in st.get("positions", {}).values())
max_total_exposure = eq * cfg.get("max_total_position_pct_of_equity", 1.0)
remaining_exposure = max(0.0, max_total_exposure - open_exposure)
performance_multiplier = symbol_performance_multiplier(cfg, sym)
per_symbol_cap = eq * cfg.get("max_boosted_position_pct_of_equity", cfg["max_position_pct_of_equity"])
# Planned stop loss includes estimated entry/exit costs, not just price distance.
loss_fraction = abs(cfg["stop_loss_pct"]) / 100 + (2 * cfg["fee_bps"] + 2 * cfg["slippage_bps"]) / 10000
risk_cap = eq * float(cfg.get("max_risk_per_trade_pct", 0.5)) / 100 / max(loss_fraction, 0.000001)
notional = min(
risk_cap,
eq * cfg["max_position_pct_of_equity"] * performance_multiplier * max(0.25, reliability),
per_symbol_cap,
remaining_exposure,
@@ -363,6 +388,7 @@ def maybe_open_shadow_position(st, cfg, signal):
log_event(ev); return ev
def scan_once(cfg, st):
roll_daily(st, equity(st, {}))
signals=[]; prices={}; events=[]
watch_all = list(dict.fromkeys(cfg.get("watch_only_symbols", [])))
watch_limit = int(cfg.get("watch_scan_limit_per_cycle", 0) or 0)
@@ -401,17 +427,22 @@ def scan_once(cfg, st):
sev = close_shadow_position_if_needed(st, cfg, sig["symbol"], sig["price"])
if sev: events.append(sev)
eq = equity(st, prices); blocked, reason = daily_loss_blocked(st, cfg, eq)
missing_held = sorted(set(st.get("positions", {})) - set(prices))
if missing_held:
blocked, reason = True, "missing_position_prices"
if blocked: log_event({"type": "risk_block", "reason": reason, "equity_usd": eq})
else:
tradeable = set(cfg["symbols"])
for sig in sorted([s for s in signals if s.get("status") == "ok" and s.get("symbol") in tradeable], key=lambda x: x["gap_pct"], reverse=True):
eq = equity(st, prices)
blocked, reason = daily_loss_blocked(st, cfg, eq)
if blocked: break
ev = maybe_open_position(st, cfg, sig, eq)
if ev: events.append(ev)
for sig in sorted([s for s in signals if s.get("status") == "ok" and s.get("symbol") in watch_only], key=lambda x: x["gap_pct"], reverse=True):
ev = maybe_open_shadow_position(st, cfg, sig)
if ev: events.append(ev)
st["last_scan"] = {"ts": now_iso(), "equity_usd": equity(st, prices), "events": events}
st["last_scan"] = {"ts": now_iso(), "equity_usd": equity(st, prices), "events": events, "entries_blocked": blocked, "block_reason": reason, "missing_position_prices": missing_held, "price_basis": "completed candles; stops checked only during scans"}
st["last_signals"] = signals
save_state(st)
log_event({"type": "scan", "equity_usd": st["last_scan"]["equity_usd"], "signals": signals, "events_count": len(events)})
+18
View File
@@ -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:
+16
View File
@@ -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}
}
}
+2 -1
View File
@@ -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
}
Executable → Regular
+75 -28
View File
@@ -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 = '''<!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>
AGENT='bot.py'
SCAN_LOCK=threading.Lock()
INDEX='''<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Local Trading Agent</title><meta name="viewport" content="width=device-width,initial-scale=1"><style>
:root{color-scheme:dark}*{box-sizing:border-box}body{font:16px/1.5 system-ui;background:#0b1421;color:#e8eefc;margin:0;padding:24px;max-width:1500px;margin:auto}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px}.card{background:#152338;border:1px solid #30405a;border-radius:10px;padding:18px;margin-top:16px;min-width:0}h1{font-size:30px}h2{font-size:20px;margin-top:0}button,a.button{display:inline-block;background:#60ddb3;color:#071c14;border:0;border-radius:6px;padding:11px 16px;font:600 14px system-ui;cursor:pointer;text-decoration:none}button:disabled{opacity:.5}.muted{color:#a6b7d0}.good{color:#78e0b0}.bad{color:#ff9f9f}.big{font-size:30px}pre{white-space:pre-wrap;word-break:break-word;max-height:350px;overflow:auto;font-size:14px}table{width:100%;border-collapse:collapse;font-size:14px}td,th{padding:10px;border-bottom:1px solid #30405a;text-align:left}th{color:#a6b7d0}.scroll{overflow:auto}.note{border-left:3px solid #e2bd70;padding:10px 16px;background:#29271f;font-size:14px}#status{margin-top:12px}svg{width:100%;height:180px}@media(max-width:600px){body{padding:14px}h1{font-size:25px}td,th{padding:7px}}
</style></head><body><h1>Local Trading Agent <span class="good">/ paper</span></h1><p id="profile" class="muted">Loading account…</p><p class="note">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.</p><button id="scan">Run scan now</button> <button id="refresh">Refresh</button> <a class="button" href="/api/report" download="trading-report.txt">Download report</a><div id="status" role="status"></div><div id="app" class="grid"></div><section class="card"><h2>Equity history</h2><svg id="curve" viewBox="0 0 800 180" role="img" aria-label="Recorded paper equity"></svg></section><section class="card scroll"><h2>Positions</h2><table><thead><tr><th>Market</th><th>Quantity</th><th>Entry</th><th>Last mark</th><th>Stop</th><th>Unrealized*</th></tr></thead><tbody id="positions"></tbody></table><p class="muted">*Includes entry fees; excludes estimated exit costs.</p></section><section class="card scroll"><h2>Market signals</h2><table><thead><tr><th>Market</th><th>Strategy</th><th>Timeframe</th><th>Price</th><th>Decision / data status</th></tr></thead><tbody id="signals"></tbody></table></section><section class="card"><h2>Token research watchlist</h2><p class="note">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.</p><div id="watchlist" class="grid"></div><p id="watch-status" role="status"></p></section><section class="card"><h2>Recent audit log</h2><pre id="log"></pre></section>
<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)
const el=id=>document.getElementById(id),esc=x=>String(x??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const money=x=>Number.isFinite(Number(x))?'$'+Number(x).toFixed(2):'—';
async function request(u,o){let r=await fetch(u,o);if(!r.ok){let t=await r.text();throw Error(t)}return r.json()}
function card(title,value,note=''){return `<section class="card"><h2>${esc(title)}</h2><div class="big">${esc(value)}</div><p class="muted">${esc(note)}</p></section>`}
async function load(){try{let s=await request('/api/state'),scan=s.last_scan||{},initial=s.starting_cash_usd||100,eq=scan.equity_usd??s.cash_usd??initial,peak=Math.max(s.equity_high_watermark_usd||initial,eq),pct=(eq/initial-1)*100;el('profile').textContent=(s.profile==='five-market'?'Five markets: SPY · QQQ · BTC · GLD · USO':'Crypto dip profile')+' · Last scan: '+(scan.ts||'not run');el('app').innerHTML=card('Account equity',money(eq),pct.toFixed(2)+'% since start')+card('Available cash',money(s.cash_usd??initial),'One shared account; no leverage')+card('Realized P/L',money(s.realized_pnl_usd||0),'After modeled entry and exit costs')+card('Drawdown',((peak-eq)/peak*100).toFixed(2)+'%','From recorded equity peak');el('status').textContent=(scan.entries_blocked?'New entries paused: '+scan.block_reason:'Paper entries eligible when rules pass')+(scan.data_errors?' · '+scan.data_errors+' market data errors':'');el('positions').innerHTML=Object.entries(s.positions||{}).map(([symbol,p])=>`<tr><td>${esc(symbol)}</td><td>${Number(p.qty).toFixed(8)}</td><td>${money(p.avg_entry)}</td><td>${money(p.last_price??p.avg_entry)}</td><td>${p.stop_price?money(p.stop_price):'Scan rule'}</td><td>${money(p.qty*((p.last_price??p.avg_entry)-p.avg_entry)-(p.buy_fee_usd||0))}</td></tr>`).join('')||'<tr><td colspan="6">No open paper positions.</td></tr>';el('signals').innerHTML=(s.last_signals||[]).map(x=>`<tr><td>${esc(x.symbol)}</td><td>${esc(x.strategy||'dip')}</td><td>${x.timeframe_seconds?esc(x.timeframe_seconds/60)+'m':'—'}</td><td>${x.price?money(x.price):'—'}</td><td>${esc(x.status==='ok'?(x.entry_block||(x.exit?'Exit signal':x.entry?'Entry signal':'Wait')):x.error||x.status)}</td></tr>`).join('')||'<tr><td colspan="5">Run a scan to see signals. ETF data requires Alpaca credentials.</td></tr>';let h=(s.equity_history||[]).map(x=>x.equity_usd).filter(Number.isFinite);if(h.length>1){let min=Math.min(...h),max=Math.max(...h),range=max-min||1;let pts=h.map((v,i)=>`${20+i/(h.length-1)*760},${155-(v-min)/range*125}`).join(' ');el('curve').innerHTML=`<text x="20" y="16" fill="#a6b7d0">${money(min)} – ${money(max)}</text><polyline points="${pts}" fill="none" stroke="#60ddb3" stroke-width="2"/>`}else el('curve').innerHTML='<text x="20" y="90" fill="#a6b7d0">Two scans are needed to draw the equity history.</text>';let r=await fetch('/api/log');if(!r.ok)throw Error('Unable to load log');el('log').textContent=await r.text()}catch(e){el('status').textContent='Unable to refresh: '+e.message}}
async function loadWatch(){try{let data=await request('/api/watchlist');el('watchlist').innerHTML=data.items.map(x=>`<article class="card"><h2>${esc(x.id)} <span class="muted">${esc(x.name===x.id?'':x.name)}</span></h2><p>${esc(x.note)}</p><p class="muted">${esc(x.status.replaceAll('_',' '))}</p>${x.kind==='token'?`<label>Exact Solana mint<input id="mint-${esc(x.id)}" value="${esc(x.mint)}" maxlength="44" autocomplete="off" spellcheck="false" style="display:block;width:100%;padding:10px;margin:10px 0;font:14px monospace;background:#0b1421;color:white;border:1px solid #52647c"></label><button data-save-mint="${esc(x.id)}">Save mint</button>`:'<p>Platform or token? Identity needed.</p>'}</article>`).join('');el('watchlist').querySelectorAll('[data-save-mint]').forEach(b=>b.onclick=async()=>{b.disabled=true;try{await request('/api/watchlist',{method:'POST',headers:{'Content-Type':'application/json','X-Local-Scan':'1'},body:JSON.stringify({id:b.dataset.saveMint,mint:el('mint-'+b.dataset.saveMint).value})});await loadWatch();el('watch-status').textContent='Saved locally. Research only; trading remains disabled.'}catch(e){el('watch-status').textContent=e.message}finally{b.disabled=false}})}catch(e){el('watch-status').textContent='Unable to load watchlist: '+e.message}}
loadWatch();
el('scan').onclick=async()=>{el('scan').disabled=true;el('status').textContent='Scanning markets…';try{await request('/api/scan',{method:'POST',headers:{'X-Local-Scan':'1'}});await load()}catch(e){el('status').textContent='Scan failed: '+e.message}finally{el('scan').disabled=false}};el('refresh').onclick=load;load();setInterval(load,15000);
</script></body></html>'''
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<length<=2048:raise ValueError('Invalid request size')
body=json.loads(self.rfile.read(length))
if not isinstance(body,dict):raise ValueError('Expected an object')
updated=watchlist.update_mint(body.get('id'),body.get('mint'))
except (ValueError,TypeError) as exc:return self.send(400,json.dumps({'error':str(exc)}))
return self.send(200,json.dumps(updated))
if urlparse(self.path).path!='/api/scan':return self.send(404,'{}')
# Custom header prevents cross-origin HTML forms triggering scans. No CORS allowed.
if self.headers.get('X-Local-Scan')!='1':return self.send(403,json.dumps({'error':'Use the local dashboard scan button.'}))
if not SCAN_LOCK.acquire(blocking=False):return self.send(409,json.dumps({'error':'A dashboard scan is already running.'}))
try:
r=subprocess.run([sys.executable,str(ROOT/AGENT),'--once'],cwd=ROOT,capture_output=True,text=True,timeout=600)
self.send(200 if r.returncode==0 else 500,r.stdout if r.returncode==0 else json.dumps({'error':r.stderr or 'Scan failed'}))
except subprocess.TimeoutExpired:self.send(504,json.dumps({'error':'Scan timed out; check worker/data-provider health.'}))
finally:SCAN_LOCK.release()
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()
global STATE,TRADES,AGENT
ap=argparse.ArgumentParser();ap.add_argument('--host',default='127.0.0.1');ap.add_argument('--port',type=int,default=8765);ap.add_argument('--profile',choices=['crypto','five'],default='crypto');args=ap.parse_args()
if args.profile=='five':
STATE=ROOT/'data'/'five-market'/'state.json';TRADES=STATE.with_name('trades.jsonl');AGENT='five_market.py'
print(f'Listening on http://{args.host}:{args.port}',flush=True)
ThreadingHTTPServer((args.host,args.port),H).serve_forever()
if __name__=='__main__':main()
Executable → Regular
View File
File mode changed.
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python3
"""Five-market local paper agent. Never sends broker orders."""
import argparse
import fcntl
import json
import math
import os
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError
import bot
ROOT = Path(__file__).resolve().parent
MARKETS = {
'SPY': ('S&P 500 ETF', 'mean_reversion', 900),
'QQQ': ('Nasdaq-100 ETF', 'mean_reversion', 900),
'BTC-USD': ('Bitcoin', 'breakout', 3600),
'GLD': ('Gold ETF proxy', 'trend', 14400),
'USO': ('Oil ETF proxy', 'trend', 14400),
}
RISK_ON = {'SPY', 'QQQ', 'BTC-USD'}
def configure_storage():
bot.DATA = ROOT / 'data' / 'five-market'
bot.DATA.mkdir(parents=True, exist_ok=True)
bot.STATE_PATH = bot.DATA / 'state.json'
bot.TRADES_PATH = bot.DATA / 'trades.jsonl'
bot.LOCK_PATH = bot.DATA / 'scan.lock'
def load_config():
cfg = json.loads((ROOT / 'config-five.json').read_text())
for key, low, high in [('starting_cash_usd', 1, 1e7), ('risk_per_trade_pct', .01, 1),
('max_portfolio_risk_pct', .01, 3), ('max_position_pct', 1, 100),
('max_total_exposure_pct', 1, 100), ('stop_loss_pct', .1, 5),
('max_daily_loss_pct', .1, 20), ('max_drawdown_pct', .1, 50),
('scan_interval_seconds', 30, 3600), ('min_trade_usd', .01, 100)]:
value = cfg.get(key)
if not isinstance(value, (float, int)) or not math.isfinite(value) or not low <= value <= high:
raise ValueError('Invalid configuration: ' + key)
for name in ('crypto', 'etf'):
for key in ('fee_bps', 'slippage_bps'):
value = cfg['costs'][name][key]
if not isinstance(value, (float, int)) or not math.isfinite(value) or not 0 <= value <= 500:
raise ValueError('Invalid trading cost')
return cfg
def alpaca_json(path, query=None, trading=False):
key = os.environ.get('APCA_API_KEY_ID')
secret = os.environ.get('APCA_API_SECRET_KEY')
if not key or not secret:
raise RuntimeError('Set APCA_API_KEY_ID and APCA_API_SECRET_KEY for ETF data.')
host = 'https://paper-api.alpaca.markets' if trading else 'https://data.alpaca.markets'
req = Request(host + path + ('?' + urlencode(query) if query else ''),
headers={'APCA-API-KEY-ID': key, 'APCA-API-SECRET-KEY': secret})
try:
with urlopen(req, timeout=15) as response:
return json.load(response)
except HTTPError as exc:
raise RuntimeError(f'Alpaca HTTP {exc.code}; check data access and credentials.') from None
def timestamp(value):
return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp()
def valid_bars(candles):
candles = sorted(candles, key=lambda c: c.ts)
if len({c.ts for c in candles}) != len(candles):
raise RuntimeError('Duplicate candles')
for c in candles:
if 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):
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<cfg['min_trade_usd']:
sig['entry_block']='Below minimum order after cash/risk limits';continue
fee,_=costs(cfg,symbol);buy_fee=notional*fee;qty=notional/entry
st['cash_usd']-=notional+buy_fee
st['positions'][symbol]={'qty':qty,'avg_entry':entry,'last_price':sig['price'],
'buy_fee_usd':buy_fee,'notional_usd':notional,'opened_at':bot.now_iso(),
'stop_price':entry*(1-cfg['stop_loss_pct']/100),'planned_risk_usd':notional*loss_fraction,
'strategy':sig['strategy'],'signal_bar':sig['bar_ts']}
consumed[symbol]=sig['bar_ts']
ev={'type':'paper_buy','symbol':symbol,'price':entry,'qty':qty,'fee_usd':buy_fee,
'notional_usd':notional,'strategy':sig['strategy'],'signal_bar':sig['bar_ts']}
events.append(ev);bot.log_event(ev)
final_block,final_reason=bot.daily_loss_blocked(st,cfg,bot.equity(st,{}))
blocked=blocked or final_block;reason=reason or final_reason
eq=bot.equity(st,{})
st['profile']='five-market';st['mode']='paper';st['last_signals']=signals
st['last_scan']={'ts':bot.now_iso(),'equity_usd':eq,'events':events,'entries_blocked':blocked,
'block_reason':reason,'missing_position_prices':missing,'etf_session_open':is_open,
'data_errors':len(errors),'price_basis':'Latest trades; stops polled, not broker-held.'}
st.setdefault('equity_history',[]).append({'ts':bot.now_iso(),'equity_usd':eq})
st['equity_history']=st['equity_history'][-2000:]
bot.save_state(st);bot.log_event({'type':'scan',**st['last_scan']})
return st['last_scan']
def main():
ap=argparse.ArgumentParser();ap.add_argument('--once',action='store_true');ap.add_argument('--loop',action='store_true');ap.add_argument('--config-check',action='store_true');args=ap.parse_args()
cfg=load_config()
if args.config_check:
print(json.dumps({'ok':True,'mode':'paper','markets':MARKETS,
'etf_credentials_present':bool(os.environ.get('APCA_API_KEY_ID') and os.environ.get('APCA_API_SECRET_KEY'))},indent=2));return
configure_storage()
while True:
with bot.LOCK_PATH.open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
cfg=load_config();st=bot.load_state(cfg)
print(json.dumps(scan_once(cfg,st),indent=2),flush=True)
if not args.loop or args.once:break
time.sleep(cfg['scan_interval_seconds'])
if __name__=='__main__':main()
Executable → Regular
View File
File mode changed.
+92
View File
@@ -0,0 +1,92 @@
import copy
import unittest
from unittest.mock import patch
import bot
import five_market as fm
import dashboard
def bars(closes):
return [bot.Candle(i*900,p-.1,p+.1,p,p,100) for i,p in enumerate(closes)]
class FiveMarketTests(unittest.TestCase):
def setUp(self):
self.cfg=fm.load_config()
self.st=bot.default_state(self.cfg)
self.log=patch.object(bot,'log_event');self.log.start();self.addCleanup(self.log.stop)
self.save=patch.object(bot,'save_state');self.save.start();self.addCleanup(self.save.stop)
def test_mean_reversion_and_exit(self):
self.assertTrue(fm.strategy_signal(bars([100]*59+[90]),'SPY')['entry'])
self.assertTrue(fm.strategy_signal(bars([100]*59+[102]),'QQQ')['exit'])
def test_breakout_excludes_signal_bar_from_channel(self):
s=fm.strategy_signal(bars([100]*59+[103]),'BTC-USD')
self.assertTrue(s['entry'])
self.assertTrue(fm.strategy_signal(bars([100]*59+[95]),'BTC-USD')['exit'])
def test_trend_cross_and_exit(self):
self.assertTrue(fm.strategy_signal(bars([100]*59+[110]),'GLD')['entry'])
self.assertTrue(fm.strategy_signal(bars([100]*59+[90]),'USO')['exit'])
self.assertFalse(fm.strategy_signal(bars(list(range(100,160))),'GLD')['entry'])
def fetcher(self,symbol):
return bars([100]*59+([90] if symbol in {'SPY','QQQ'} else [110])),100
def test_shared_risk_on_filter_and_accounting(self):
fm.scan_once(self.cfg,self.st,self.fetcher,lambda:{'is_open':True})
self.assertEqual(set(self.st['positions']) & fm.RISK_ON,{'SPY'})
self.assertEqual(set(self.st['positions']),{'SPY','GLD','USO'})
spent=sum(p['notional_usd']+p['buy_fee_usd'] for p in self.st['positions'].values())
self.assertAlmostEqual(self.st['cash_usd']+spent,100)
self.assertLessEqual(sum(p['planned_risk_usd'] for p in self.st['positions'].values()),1.5)
self.assertTrue(all(p['stop_price']==p['avg_entry']*.99 for p in self.st['positions'].values()))
def test_signal_is_not_bought_twice(self):
fm.scan_once(self.cfg,self.st,self.fetcher,lambda:{'is_open':True})
fm.sell(self.st,self.cfg,'SPY',100,'test')
fm.scan_once(self.cfg,self.st,self.fetcher,lambda:{'is_open':True})
self.assertNotIn('SPY',self.st['positions'])
def test_closed_etfs_do_not_fetch_but_bitcoin_runs(self):
called=[]
def fetch(s):called.append(s);return self.fetcher(s)
fm.scan_once(self.cfg,self.st,fetch,lambda:{'is_open':False})
self.assertEqual(called,['BTC-USD'])
self.assertIn('BTC-USD',self.st['positions'])
def test_stale_held_market_blocks_new_entries(self):
fm.scan_once(self.cfg,self.st,self.fetcher,lambda:{'is_open':True})
def fetch(s):
if s=='GLD':raise RuntimeError('stale')
return self.fetcher(s)
result=fm.scan_once(self.cfg,self.st,fetch,lambda:{'is_open':True})
self.assertTrue(result['entries_blocked'])
self.assertEqual(result['block_reason'],'missing_position_prices')
def test_exit_stop_uses_actual_sampled_price_and_costs(self):
fm.scan_once(self.cfg,self.st,self.fetcher,lambda:{'is_open':True})
p=copy.deepcopy(self.st['positions']['SPY'])
def fetch(s):return bars([100]*60),95 if s=='SPY' else 100
result=fm.scan_once(self.cfg,self.st,fetch,lambda:{'is_open':True})
sale=next(e for e in result['events'] if e['symbol']=='SPY' and e['type']=='paper_sell')
self.assertEqual(sale['reason'],'stop_loss')
self.assertAlmostEqual(sale['price'],95*.9995)
self.assertAlmostEqual(sale['realized_pnl_usd'],p['qty']*(95*.9995-p['avg_entry'])-p['buy_fee_usd'])
def test_volatility_reduces_size(self):
low=fm.size_position(self.st,self.cfg,'SPY',100,.2)[0]
high=fm.size_position(self.st,self.cfg,'SPY',100,5)[0]
self.assertLess(high,low)
def test_nonpositive_bars_rejected(self):
with self.assertRaisesRegex(RuntimeError,'Invalid'):
fm.strategy_signal(bars([0]*60),'GLD')
def test_report_contains_profile_and_net(self):
fm.scan_once(self.cfg,self.st,self.fetcher,lambda:{'is_open':True})
report=dashboard.report_text(self.st)
self.assertIn('five-market',report)
self.assertIn('Realized net',report)
if __name__=='__main__':unittest.main()
+69
View File
@@ -0,0 +1,69 @@
"""Offline regression tests: python3 -m unittest test_risk_controls -v"""
import copy
import unittest
from unittest.mock import patch
import bot
class RiskControls(unittest.TestCase):
def setUp(self):
self.cfg = bot.load_config()
self.st = bot.default_state(self.cfg)
def test_daily_unrealized_loss_latches(self):
self.assertEqual(bot.daily_loss_blocked(self.st,self.cfg,97), (True,'daily_loss_limit'))
self.assertTrue(bot.daily_loss_blocked(self.st,self.cfg,100)[0])
def test_rollover_before_exit(self):
self.st['daily']={'date':'2020-01-01','realized_pnl_usd':-10}
bot.roll_daily(self.st,98)
self.assertEqual(self.st['daily']['realized_pnl_usd'],0)
self.assertEqual(self.st['daily']['starting_equity_usd'],98)
def test_exit_slippage_and_fees(self):
self.st['positions']['TST-USD']={'qty':10,'avg_entry':1,'buy_fee_usd':.04}
self.st['cash_usd']=89.96
with patch.object(bot,'log_event'):
ev=bot.close_position_if_needed(self.st,self.cfg,'TST-USD',1.04)
expected=10*1.04*(1-.0015)*(1-.004)-10-.04
self.assertAlmostEqual(ev['realized_pnl_usd'],expected)
self.assertAlmostEqual(self.st['cash_usd'],100+expected)
def test_shadow_exit_slippage(self):
self.st['shadow_positions']['TST-USD']={'qty':10,'avg_entry':1,'buy_fee_usd':.04}
with patch.object(bot,'log_event'):
ev=bot.close_shadow_position_if_needed(self.st,self.cfg,'TST-USD',1.04)
self.assertAlmostEqual(ev['price'],1.04*(1-.0015))
def test_fee_edge_counts_two_sides(self):
cfg={**self.cfg,'require_rebound_confirmation':False,'min_candles_24h':0,'min_dollar_volume_24h':0}
self.assertFalse(bot.signal_has_fee_aware_edge(cfg,{'gap_pct':2.55}))
self.assertTrue(bot.signal_has_fee_aware_edge(cfg,{'gap_pct':2.66}))
def test_risk_cap(self):
cfg={**self.cfg,'max_risk_per_trade_pct':.05,'min_trade_usd':.01}
sig={'symbol':'TST-USD','price':1,'gap_pct':5,'volatility_pct':1}
with patch.object(bot,'log_event'),patch.object(bot,'recent_symbol_loss_blocked',return_value=(False,None)),patch.object(bot,'signal_has_fee_aware_edge',return_value=True),patch.object(bot,'symbol_performance_multiplier',return_value=2):
ev=bot.maybe_open_position(self.st,cfg,sig,100)
self.assertLessEqual(ev['notional_usd']*.023,.05+1e-9)
def test_missing_held_price_blocks_entries(self):
cfg={**self.cfg,'symbols':['TST-USD'],'watch_only_symbols':[]}
self.st['positions']['TST-USD']={'qty':1,'avg_entry':1}
with patch.object(bot,'fetch_coinbase_candles',side_effect=RuntimeError('offline')),patch.object(bot,'save_state'),patch.object(bot,'log_event'),patch.object(bot,'maybe_open_position') as opener:
result=bot.scan_once(cfg,self.st)
self.assertEqual(result['block_reason'],'missing_position_prices')
opener.assert_not_called()
def test_stale_candles_rejected(self):
with patch.object(bot.time,'time',return_value=100000),patch.object(bot,'http_json',return_value=[[100,1,2,1.5,1.5,10]]*20):
with self.assertRaisesRegex(RuntimeError,'stale candles'):
bot.fetch_coinbase_candles('TST-USD',24,300)
def test_incomplete_candle_excluded(self):
rows=[[100000-i*300,1,2,1.5,1.5,10] for i in range(20)]
with patch.object(bot.time,'time',return_value=100010),patch.object(bot,'http_json',return_value=rows):
candles=bot.fetch_coinbase_candles('TST-USD',24,300)
self.assertEqual(len(candles),19)
self.assertEqual(candles[-1].ts,99700)
if __name__=='__main__': unittest.main()
+24
View File
@@ -0,0 +1,24 @@
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import watchlist
class WatchlistTests(unittest.TestCase):
def test_address_encoding(self):
self.assertTrue(watchlist.valid_mint('So11111111111111111111111111111111111111112'))
self.assertFalse(watchlist.valid_mint('XST'))
self.assertFalse(watchlist.valid_mint('1'*33))
def test_save_mint_keeps_execution_disabled(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp)
with patch.object(watchlist,'DATA',root),patch.object(watchlist,'SAVED',root/'watch.json'):
result=watchlist.update_mint('XST','So11111111111111111111111111111111111111112')
self.assertEqual(result['execution'],'disabled')
self.assertEqual(watchlist.read()['items'][0]['status'],'mint_supplied_not_verified')
with self.assertRaises(ValueError):watchlist.update_mint('FOMO','')
with self.assertRaises(ValueError):watchlist.update_mint('WOFI','bad')
self.assertEqual(watchlist.read()['items'][1]['mint'],'')
if __name__=='__main__':unittest.main()
Executable → Regular
View File
File mode changed.
+33
View File
@@ -0,0 +1,33 @@
{
"items": [
{
"id": "XST",
"name": "XST",
"kind": "token",
"chain": "solana",
"mint": "",
"status": "identity_unconfirmed",
"note": "User-supplied, unverified: promoted as a Solana/memecoin-style asset. A report of approximately 74% supply clustered in linked wallets requires a source and independent verification. Fomo visibility does not validate a token."
},
{
"id": "WOFI",
"name": "World Oil Fund Institution",
"kind": "token",
"chain": "solana",
"mint": "",
"status": "identity_unconfirmed",
"note": "User-supplied, unverified: oil/RWA branding and reported Coinbase DEX visibility. No oil backing, issuer legitimacy, custody or redemption rights have been verified."
},
{
"id": "UOTF",
"name": "United Oil Trust Fund",
"kind": "token",
"chain": "solana",
"mint": "",
"status": "identity_unconfirmed",
"note": "User-supplied, unverified: reportedly multiple tokens use this name. Exact mint, liquidity, authorities, holder concentration and legal oil/trust rights require verification."
}
],
"execution": "disabled",
"source": "User-supplied descriptions; not independently verified"
}
+40
View File
@@ -0,0 +1,40 @@
"""Research-only records. Never routed to either trading engine."""
import json
import fcntl
from pathlib import Path
ROOT=Path(__file__).resolve().parent
SEED=ROOT/'watchlist.json'
DATA=ROOT/'data'
SAVED=DATA/'research-watchlist.json'
ALPHABET='123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def read():
return json.loads((SAVED if SAVED.exists() else SEED).read_text())
def valid_mint(value):
if not isinstance(value,str) or not 32<=len(value)<=44 or any(c not in ALPHABET for c in value):
return False
n=0
for c in value:n=n*58+ALPHABET.index(c)
leading=len(value)-len(value.lstrip('1'))
length=leading+((n.bit_length()+7)//8 if n else 0)
return length==32
def update_mint(item_id,mint):
if not isinstance(item_id,str) or not isinstance(mint,str):raise ValueError('ID and mint must be text.')
mint=mint.strip()
if mint and not valid_mint(mint):raise ValueError('Enter a Solana address encoding exactly 32 bytes, or leave blank.')
DATA.mkdir(parents=True,exist_ok=True)
with (DATA/'watchlist.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
data=read()
item=next((x for x in data['items'] if x['id']==item_id),None)
if not item or item['kind']!='token':raise ValueError('Unknown research token.')
item['mint']=mint
item['status']='mint_supplied_not_verified' if mint else 'identity_unconfirmed'
temp=SAVED.with_suffix('.tmp')
temp.write_text(json.dumps(data,indent=2)+'\n');temp.replace(SAVED)
return data