Files
local-trading-agent/dashboard.py
T

94 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
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
ROOT=Path(__file__).resolve().parent
STATE=ROOT/'data'/'state.json'
TRADES=ROOT/'data'/'trades.jsonl'
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>
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.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/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':
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):
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():
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()