Files
local-trading-agent/find_winners.py
T

81 lines
3.6 KiB
Python

#!/usr/bin/env python3
import json, math, time
from collections import defaultdict
from datetime import datetime
from pathlib import Path
from urllib.request import Request, urlopen
from zoneinfo import ZoneInfo
ROOT = Path(__file__).resolve().parent
CONFIG = ROOT / 'config.json'
TRADES = ROOT / 'data' / 'trades.jsonl'
LOCAL_TZ = ZoneInfo('America/New_York')
BAD = {'MDT-USD','HFT-USD','HIGH-USD','COTI-USD'}
def get(url, timeout=15):
with urlopen(Request(url, headers={'User-Agent':'local-trader-find-winners/0.1'}), timeout=timeout) as r:
return json.loads(r.read().decode())
def trade_perf():
perf=defaultdict(lambda:{'trades':0,'wins':0,'losses':0,'pnl':0.0})
if not TRADES.exists(): return perf
for line in TRADES.read_text().splitlines():
if not line.strip(): continue
try: e=json.loads(line)
except Exception: continue
if e.get('type')=='paper_sell':
p=float(e.get('realized_pnl_usd',0)); d=perf[e['symbol']]
d['trades']+=1; d['pnl']+=p; d['wins']+=p>=0; d['losses']+=p<0
return perf
def candles(sym):
end=int(time.time()); start=end-24*3600
url=f"https://api.exchange.coinbase.com/products/{sym}/candles?granularity=300&start={datetime.fromtimestamp(start,LOCAL_TZ).isoformat()}&end={datetime.fromtimestamp(end,LOCAL_TZ).isoformat()}"
c=sorted(get(url,10), key=lambda x:x[0])
if len(c)<80: return None
closes=[float(x[4]) for x in c]
if min(closes)<=0: return None
highs=[float(x[2]) for x in c]; lows=[float(x[1]) for x in c]
dollar_vol=sum(((float(x[1])+float(x[2])+float(x[4]))/3)*float(x[5]) for x in c)
move=(closes[-1]/closes[0]-1)*100
rng=(max(highs)/min(lows)-1)*100
rets=[math.log(closes[i]/closes[i-1]) for i in range(1,len(closes)) if closes[i-1]>0]
rv=(sum(r*r for r in rets)/len(rets))**0.5*math.sqrt(288)*100 if rets else 0
# Trend filter: avoid vertical pumps; prefer volatile but not already up >35%.
pump_penalty=0.45 if move>35 else 1.0
dump_penalty=0.65 if move<-20 else 1.0
liquidity=min(1.0, math.log10(max(dollar_vol,1))/6.0)
score=rv*liquidity*pump_penalty*dump_penalty
return {'symbol':sym,'price':closes[-1],'move24h':move,'range24h':rng,'realized_vol':rv,'dollar_vol':dollar_vol,'candles':len(c),'score':score}
def main():
cfg=json.loads(CONFIG.read_text())
current=set(cfg.get('symbols',[])); watch=set(cfg.get('watch_only_symbols',[]))
products=get('https://api.exchange.coinbase.com/products')
rows=[]
for p in products:
sym=p.get('id')
if p.get('quote_currency')!='USD' or p.get('status')!='online' or p.get('trading_disabled'): continue
if sym in current or sym in BAD: continue
try:
row=candles(sym)
if row and row['dollar_vol']>=300000:
rows.append(row)
except Exception:
pass
rows.sort(key=lambda r:r['score'], reverse=True)
perf=trade_perf()
print('Current proven winners from bot log:')
for sym,d in sorted(perf.items(), key=lambda kv: kv[1]['pnl'], reverse=True):
if d['pnl']>0:
print(f"{sym:10s} pnl=${d['pnl']:.2f} wins={d['wins']} losses={d['losses']} trades={d['trades']}")
print('\nBest new watch candidates, not auto-trade yet:')
for r in rows[:12]:
print(f"{r['symbol']:12s} score={r['score']:6.2f} price={r['price']:.8g} move={r['move24h']:+6.2f}% range={r['range24h']:6.2f}% rv={r['realized_vol']:6.2f}% vol~${r['dollar_vol']:,.0f}")
recommended=[r['symbol'] for r in rows[:5]]
print('\nRECOMMENDED_WATCH_ONLY=' + ','.join(recommended))
if __name__=='__main__':
main()