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

+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()