fix: handle ETF data without Alpaca credentials
This commit is contained in:
1 parent
d6ee92dbb7
commit
26a30f534b
2 files changed
+74
-3
No files matched your search
+58
-3
@@ -65,6 +65,55 @@ def alpaca_json(path, query=None, trading=False):
|
|||||||
raise RuntimeError(f'Alpaca HTTP {exc.code}; check data access and credentials.') from None
|
raise RuntimeError(f'Alpaca HTTP {exc.code}; check data access and credentials.') from None
|
||||||
|
|
||||||
|
|
||||||
|
def credentials_present():
|
||||||
|
return bool(os.environ.get('APCA_API_KEY_ID') and os.environ.get('APCA_API_SECRET_KEY'))
|
||||||
|
|
||||||
|
|
||||||
|
def inferred_us_regular_session_open(now=None):
|
||||||
|
"""Credential-free fallback clock for ETF paper scanning.
|
||||||
|
|
||||||
|
This deliberately only approximates regular NYSE hours. It avoids reporting
|
||||||
|
missing Alpaca credentials as a runtime error while the market is closed, and
|
||||||
|
lets the app keep running BTC-only after hours.
|
||||||
|
"""
|
||||||
|
now = now or datetime.now(bot.LOCAL_TZ)
|
||||||
|
if now.weekday() >= 5:
|
||||||
|
return False
|
||||||
|
minutes = now.hour * 60 + now.minute
|
||||||
|
return 9 * 60 + 30 <= minutes < 16 * 60
|
||||||
|
|
||||||
|
|
||||||
|
def market_clock():
|
||||||
|
if credentials_present():
|
||||||
|
return alpaca_json('/v2/clock', trading=True)
|
||||||
|
return {'is_open': inferred_us_regular_session_open(), 'source': 'local_regular_hours'}
|
||||||
|
|
||||||
|
|
||||||
|
def yahoo_chart(symbol, seconds):
|
||||||
|
interval = '15m' if seconds == 900 else '1h'
|
||||||
|
span = '5d' if seconds == 900 else '6mo'
|
||||||
|
url = f'https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?range={span}&interval={interval}&includePrePost=false&events='
|
||||||
|
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
|
||||||
|
with urlopen(req, timeout=15) as response:
|
||||||
|
data = json.load(response)
|
||||||
|
chart = data.get('chart') or {}
|
||||||
|
err = chart.get('error')
|
||||||
|
if err:
|
||||||
|
raise RuntimeError(f'Yahoo chart error for {symbol}: {err}')
|
||||||
|
result = (chart.get('result') or [None])[0]
|
||||||
|
if not result:
|
||||||
|
raise RuntimeError(f'Yahoo chart returned no data for {symbol}')
|
||||||
|
timestamps = result.get('timestamp') or []
|
||||||
|
quote = ((result.get('indicators') or {}).get('quote') or [{}])[0]
|
||||||
|
rows = []
|
||||||
|
for ts, op, hi, lo, cl, vol in zip(timestamps, quote.get('open') or [], quote.get('high') or [], quote.get('low') or [], quote.get('close') or [], quote.get('volume') or []):
|
||||||
|
values = (op, hi, lo, cl)
|
||||||
|
if any(v is None for v in values):
|
||||||
|
continue
|
||||||
|
rows.append(bot.Candle(int(ts), float(lo), float(hi), float(op), float(cl), float(vol or 0)))
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
def timestamp(value):
|
def timestamp(value):
|
||||||
return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp()
|
return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp()
|
||||||
|
|
||||||
@@ -88,6 +137,10 @@ def fetch_market(symbol):
|
|||||||
candles = bot.fetch_coinbase_candles(symbol, 250, seconds)
|
candles = bot.fetch_coinbase_candles(symbol, 250, seconds)
|
||||||
ticker = bot.http_json('https://api.exchange.coinbase.com/products/BTC-USD/ticker')
|
ticker = bot.http_json('https://api.exchange.coinbase.com/products/BTC-USD/ticker')
|
||||||
price, price_ts = float(ticker['price']), timestamp(ticker['time'])
|
price, price_ts = float(ticker['price']), timestamp(ticker['time'])
|
||||||
|
elif not credentials_present():
|
||||||
|
candles = yahoo_chart(symbol, seconds)
|
||||||
|
price = float(candles[-1].close)
|
||||||
|
price_ts = candles[-1].ts + seconds
|
||||||
else:
|
else:
|
||||||
start = datetime.now(timezone.utc) - timedelta(days=180 if seconds == 14400 else 14)
|
start = datetime.now(timezone.utc) - timedelta(days=180 if seconds == 14400 else 14)
|
||||||
query = {'timeframe': '4Hour' if seconds == 14400 else '15Min',
|
query = {'timeframe': '4Hour' if seconds == 14400 else '15Min',
|
||||||
@@ -98,7 +151,9 @@ def fetch_market(symbol):
|
|||||||
for b in response.get('bars') or [] if timestamp(b['t']) + seconds <= now]
|
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']
|
trade = alpaca_json(f'/v2/stocks/{symbol}/trades/latest', {'feed':'iex'})['trade']
|
||||||
price, price_ts = float(trade['p']), timestamp(trade['t'])
|
price, price_ts = float(trade['p']), timestamp(trade['t'])
|
||||||
if not math.isfinite(price) or price <= 0 or not -60 <= now-price_ts <= 900:
|
if not math.isfinite(price) or price <= 0:
|
||||||
|
raise RuntimeError('Latest trade missing, stale or invalid; no orders simulated.')
|
||||||
|
if credentials_present() and not -60 <= now-price_ts <= 900:
|
||||||
raise RuntimeError('Latest trade missing, stale or invalid; no orders simulated.')
|
raise RuntimeError('Latest trade missing, stale or invalid; no orders simulated.')
|
||||||
candles = valid_bars(candles)
|
candles = valid_bars(candles)
|
||||||
# Allow previous-session bars at the open, but reject data older than a long weekend.
|
# Allow previous-session bars at the open, but reject data older than a long weekend.
|
||||||
@@ -180,7 +235,7 @@ def scan_once(cfg,st,fetcher=None,clock=None):
|
|||||||
bot.roll_daily(st,bot.equity(st,{}))
|
bot.roll_daily(st,bot.equity(st,{}))
|
||||||
events=[]; signals=[]; good={}; closed=set(); errors=set()
|
events=[]; signals=[]; good={}; closed=set(); errors=set()
|
||||||
try:
|
try:
|
||||||
is_open=bool((clock or (lambda:alpaca_json('/v2/clock',trading=True)))()['is_open'])
|
is_open=bool((clock or market_clock)()['is_open'])
|
||||||
clock_error=None
|
clock_error=None
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
is_open=False;clock_error=str(exc)
|
is_open=False;clock_error=str(exc)
|
||||||
@@ -251,7 +306,7 @@ def main():
|
|||||||
cfg=load_config()
|
cfg=load_config()
|
||||||
if args.config_check:
|
if args.config_check:
|
||||||
print(json.dumps({'ok':True,'mode':'paper','markets':MARKETS,
|
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
|
'etf_credentials_present':credentials_present()},indent=2));return
|
||||||
configure_storage()
|
configure_storage()
|
||||||
while True:
|
while True:
|
||||||
with bot.LOCK_PATH.open('a') as lock:
|
with bot.LOCK_PATH.open('a') as lock:
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import copy
|
import copy
|
||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
from datetime import datetime
|
||||||
import bot
|
import bot
|
||||||
import five_market as fm
|
import five_market as fm
|
||||||
import dashboard
|
import dashboard
|
||||||
@@ -55,6 +56,21 @@ class FiveMarketTests(unittest.TestCase):
|
|||||||
self.assertEqual(called,['BTC-USD'])
|
self.assertEqual(called,['BTC-USD'])
|
||||||
self.assertIn('BTC-USD',self.st['positions'])
|
self.assertIn('BTC-USD',self.st['positions'])
|
||||||
|
|
||||||
|
def test_missing_alpaca_credentials_after_hours_is_not_data_error(self):
|
||||||
|
called=[]
|
||||||
|
def fetch(s):called.append(s);return self.fetcher(s)
|
||||||
|
with patch.object(fm,'credentials_present',return_value=False), \
|
||||||
|
patch.object(fm,'inferred_us_regular_session_open',return_value=False):
|
||||||
|
result=fm.scan_once(self.cfg,self.st,fetch)
|
||||||
|
self.assertEqual(called,['BTC-USD'])
|
||||||
|
self.assertEqual(result['data_errors'],0)
|
||||||
|
self.assertFalse(result['entries_blocked'])
|
||||||
|
|
||||||
|
def test_local_regular_hours_fallback_clock(self):
|
||||||
|
self.assertTrue(fm.inferred_us_regular_session_open(datetime(2026,9,11,10,0)))
|
||||||
|
self.assertFalse(fm.inferred_us_regular_session_open(datetime(2026,9,11,16,1)))
|
||||||
|
self.assertFalse(fm.inferred_us_regular_session_open(datetime(2026,9,12,10,0)))
|
||||||
|
|
||||||
def test_stale_held_market_blocks_new_entries(self):
|
def test_stale_held_market_blocks_new_entries(self):
|
||||||
fm.scan_once(self.cfg,self.st,self.fetcher,lambda:{'is_open':True})
|
fm.scan_once(self.cfg,self.st,self.fetcher,lambda:{'is_open':True})
|
||||||
def fetch(s):
|
def fetch(s):
|
||||||
|
|||||||
Reference in new issue
Block a user