From 799c69f506db97422d1dc253af47425e41ed950c Mon Sep 17 00:00:00 2001 From: Abid Ali Awan <36753484+kingabzpro@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:06:06 +0500 Subject: [PATCH] feat: Alpaca paper account portfolio with manual and automated trading The Portfolio page now shows the real Alpaca paper account (cash, buying power, equity, positions) and submits paper market orders: manually from a trade form priced at the latest Alpaca trade, or automatically from an opt-in watcher that every five minutes picks the top gainer with a B+ market cap, runs one decision on it, and acts on the signal with the existing suggested sizing. An interactive equity chart records account snapshots with hover and keyboard inspection. The browser-local practice portfolio stays on the decision card; its fills export and reset move to a footer of the Portfolio page. --- CHANGELOG.md | 3 + fasttrade/market.py | 27 +++ fasttrade/paper.py | 160 ++++++++++++++++++ fasttrade/static/app.js | 328 +++++++++++++++++++++++++++++++----- fasttrade/static/index.html | 2 +- fasttrade/static/style.css | 18 +- fasttrade/web.py | 67 ++++++++ tests/test_paper.py | 129 ++++++++++++++ tests/test_web.py | 58 +++++++ tests/ui.test.cjs | 177 +++++++++++++------ 10 files changed, 869 insertions(+), 100 deletions(-) create mode 100644 fasttrade/paper.py create mode 100644 tests/test_paper.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9814811..70a5e43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ - Added CSV export for analysis history and simulated paper fills. - Added unrealized P&L, total P&L, and return against starting cash to the Portfolio page. - Fixed the phone card order so paper trading follows the decision, chart, indicators and evidence cards instead of appearing first. +- Rebuilt the Portfolio page around the Alpaca paper trading account: cash, buying power, equity and positions come from Alpaca, and manual BUY/SELL submits real paper market orders at the latest Alpaca trade price. +- Added automated paper trading: an opt-in toggle that every five minutes picks the top gainer with a market cap of $1B or more, runs one decision on it, and submits BUY, SELL or HOLD as a paper order, with an activity log and a Run now button. +- Added an interactive equity history chart to the Portfolio page, built from account snapshots stored in the browser, with hover and keyboard inspection. ## 0.2.0 (2026-11-07) diff --git a/fasttrade/market.py b/fasttrade/market.py index 47b6a97..54d1563 100644 --- a/fasttrade/market.py +++ b/fasttrade/market.py @@ -234,6 +234,33 @@ def history(): return frame, details, news +_cap_cache = OrderedDict() +_cap_cache_lock = Lock() + + +def market_cap(symbol): + """Return the company market cap in USD from Yahoo fundamentals, cached for an hour.""" + symbol = symbol.upper() + with _cap_cache_lock: + cached = _cap_cache.get(symbol) + if cached and monotonic() < cached[0]: + return cached[1] + import yfinance as yf + result = _yahoo_request(lambda: yf.Ticker(symbol).info) + try: + cap = float(result['marketCap']) + except (KeyError, TypeError, ValueError, OverflowError) as exc: + raise ValueError('Market cap unavailable for this symbol') from exc + if not math.isfinite(cap) or cap <= 0: + raise ValueError('Market cap unavailable for this symbol') + with _cap_cache_lock: + _cap_cache[symbol] = (monotonic() + 3600, cap) + _cap_cache.move_to_end(symbol) + while len(_cap_cache) > 64: + _cap_cache.popitem(last=False) + return cap + + def alpaca(symbol, timeframe, as_of, *, credentials=None): key, secret = credentials if credentials is not None else (os.getenv('ALPACA_API_KEY'), os.getenv('ALPACA_SECRET_KEY')) if not key or not secret: diff --git a/fasttrade/paper.py b/fasttrade/paper.py new file mode 100644 index 0000000..b95aa4c --- /dev/null +++ b/fasttrade/paper.py @@ -0,0 +1,160 @@ +"""Alpaca paper-trading account access, quotes and order execution. + +Everything here submits to the paper API only; the dashboard never places live orders. +""" +import math +import os +import re + +import httpx + +from . import market +from .resilience import CircuitOpen, pooled_get, pooled_post, request + +PAPER_BASE = 'https://paper-api.alpaca.markets' +DATA_BASE = 'https://data.alpaca.markets' +MIN_MARKET_CAP = 1_000_000_000 +_symbol_re = re.compile(r'[A-Z0-9.\-]{1,20}') + + +def _symbol(symbol): + symbol = str(symbol).upper() + if not _symbol_re.fullmatch(symbol): + raise ValueError('Invalid stock symbol') + return symbol + + +def _headers(): + headers = {'APCA-API-KEY-ID': os.getenv('ALPACA_API_KEY'), 'APCA-API-SECRET-KEY': os.getenv('ALPACA_SECRET_KEY')} + if not all(headers.values()): + raise ValueError('Alpaca credentials are missing') + return headers + + +def _error_detail(response): + try: + detail = ' '.join(str(response.json().get('message', '')).split())[:200] + except Exception: + return '' + return f': {detail}' if detail else '' + + +def _call(method, url, **kwargs): + headers = _headers() + try: + response = request(method, url, service='alpaca-paper', credentials=list(headers.values()), retry_transport=True, headers=headers, timeout=15, **kwargs) + if response.status_code in (400, 401, 403, 404, 422): + detail = _error_detail(response) + if response.status_code == 401 or (response.status_code == 403 and not detail): + raise ValueError('Alpaca rejected the paper trading credentials') + raise ValueError('Alpaca rejected the request' + detail) + if response.status_code == 429: + raise ValueError('Alpaca paper trading rate limit reached') + response.raise_for_status() + try: + data = response.json() + except ValueError as exc: + raise ValueError('Invalid Alpaca paper trading response') from exc + if not isinstance(data, (dict, list)): + raise ValueError('Invalid Alpaca paper trading response') + return data + except httpx.TimeoutException as exc: + raise ValueError('Alpaca paper trading timed out') from exc + except ValueError: + raise + except CircuitOpen as exc: + raise ValueError('Alpaca paper trading rate limited' if 'rate limit' in str(exc).lower() else 'Alpaca paper trading request failed') from exc + except (httpx.HTTPError, TypeError, AttributeError, OverflowError) as exc: + raise ValueError('Alpaca paper trading request failed') from exc + + +def overview(): + """Return paper account cash, equity, buying power and open positions.""" + account = _call(pooled_get, f'{PAPER_BASE}/v2/account') + rows = _call(pooled_get, f'{PAPER_BASE}/v2/positions') + if not isinstance(account, dict) or not isinstance(rows, list): + raise ValueError('Invalid Alpaca paper account response') + positions = [] + for row in rows: + try: + entry = {'symbol': _symbol(row['symbol']), 'quantity': float(row['qty']), 'avg_price': float(row['avg_entry_price']), + 'price': float(row['current_price']), 'value': float(row['market_value']), 'unrealized': float(row['unrealized_pl'])} + except (KeyError, TypeError, ValueError, OverflowError, AttributeError): + continue + if all(math.isfinite(entry[field]) and entry[field] >= 0 for field in ('quantity', 'avg_price', 'price')): + positions.append(entry) + result = {'positions': positions} + try: + for field in ('cash', 'equity', 'buying_power'): + result[field] = float(account[field]) + except (KeyError, TypeError, ValueError, OverflowError) as exc: + raise ValueError('Invalid Alpaca paper account response') from exc + if not all(math.isfinite(result[field]) and result[field] >= 0 for field in ('cash', 'equity', 'buying_power')): + raise ValueError('Invalid Alpaca paper account response') + return result + + +def last_price(symbol): + """Return the latest Alpaca trade price for a symbol.""" + symbol = _symbol(symbol) + data = _call(pooled_get, f'{DATA_BASE}/v2/stocks/trades/latest', params={'symbols': symbol, 'feed': 'iex'}) + try: + price = float(data['trades'][symbol]['p']) + except (KeyError, TypeError, ValueError, OverflowError, AttributeError) as exc: + raise ValueError('No Alpaca trade price available for this symbol') from exc + if not math.isfinite(price) or price <= 0: + raise ValueError('No Alpaca trade price available for this symbol') + return {'symbol': symbol, 'price': price} + + +def submit_order(symbol, side, quantity): + """Submit a paper market order; Alpaca fills it at the next available price.""" + symbol = _symbol(symbol) + if side not in ('BUY', 'SELL'): + raise ValueError('Order side must be BUY or SELL') + quantity = float(quantity) + if not math.isfinite(quantity) or quantity <= 0: + raise ValueError('Order quantity must be positive') + data = _call(pooled_post, f'{PAPER_BASE}/v2/orders', json={'symbol': symbol, 'qty': str(quantity), 'side': side.lower(), 'type': 'market', 'time_in_force': 'day'}) + try: + order_id, status = str(data['id']), str(data['status']) + except (KeyError, TypeError, AttributeError) as exc: + raise ValueError('Invalid Alpaca order response') from exc + try: + filled_quantity = float(data['filled_qty']) + filled_avg_price = float(data['filled_avg_price']) if data['filled_avg_price'] else None + except (TypeError, ValueError, OverflowError): + filled_quantity, filled_avg_price = 0.0, None + return {'symbol': symbol, 'side': side, 'quantity': quantity, 'order_id': order_id, 'status': status, 'filled_quantity': filled_quantity, 'filled_avg_price': filled_avg_price} + + +def movers(limit=8, minimum_cap=MIN_MARKET_CAP): + """Return today's top gainer with a market cap of at least minimum_cap. + + Cap candidates come from Yahoo fundamentals; entries with an unknown cap are + reported in `considered` but never picked. + """ + data = _call(pooled_get, f'{DATA_BASE}/v1beta1/screener/stocks/movers') + gainers = data.get('gainers') if isinstance(data, dict) else None + if not isinstance(gainers, list): + raise ValueError('Invalid Alpaca movers response') + considered = [] + for row in gainers: + if len(considered) >= limit: + break + try: + symbol = _symbol(row['symbol']) + price, change_percent = float(row['price']), float(row['percent_change']) + except (KeyError, TypeError, ValueError, OverflowError, AttributeError): + continue + if not math.isfinite(price) or price <= 0 or not math.isfinite(change_percent) or change_percent <= 0: + continue + entry = {'symbol': symbol, 'price': price, 'change_percent': change_percent, 'market_cap': None} + try: + entry['market_cap'] = market.market_cap(symbol) + except ValueError: + pass + considered.append(entry) + if entry['market_cap'] is not None and entry['market_cap'] >= minimum_cap: + return {'pick': entry, 'considered': considered, 'minimum_cap': minimum_cap} + return {'pick': None, 'considered': considered, 'minimum_cap': minimum_cap} diff --git a/fasttrade/static/app.js b/fasttrade/static/app.js index a681a59..58e6cc7 100644 --- a/fasttrade/static/app.js +++ b/fasttrade/static/app.js @@ -87,7 +87,6 @@ const history = []; const results = new Map(); const failures = new Map(); const runningSymbols = new Set(); -const lastPrices = new Map(); let requestedSymbols = []; let activeSymbol = null; const setText = (id, text) => { $(id).textContent = text; }; @@ -248,7 +247,6 @@ function render(result, record = true, replay = false) { selectedCandle = null; if (replay) { activeSymbol = null; $('batch-results').hidden = true; } else if (results.has(result.market.symbol)) activeSymbol = result.market.symbol; - if (!replay && Number.isFinite(result.market.features?.price)) lastPrices.set(result.market.symbol, result.market.features.price); const market = result.market, feature = market.features, decision = result.decision; const stale = Boolean(result.stale_preview), sample = result.source === 'Synthetic sample CSV'; const source = sample ? 'SYNTHETIC SAMPLE' : result.source === 'CSV' ? 'HISTORICAL CSV' : result.source === 'Yahoo Finance' ? 'YAHOO FINANCE' : 'ALPACA IEX'; @@ -336,7 +334,7 @@ function render(result, record = true, replay = false) { renderHistory(); } renderPaper(); - renderPortfolio(); + renderPractice(); if (!replay) renderTabs(); } @@ -508,7 +506,7 @@ function placePaper(side) { const saved = savePaper(); say(`${side} ${number(qty)} ${symbol} at ${number(price)} simulated against the last completed close. ${saved ? 'Stored in this browser.' : 'Browser storage is unavailable; it was not saved.'}`, true); renderPaper(); - renderPortfolio(); + renderPractice(); } $('paper-qty').addEventListener('input', renderPaper); $('paper-buy').addEventListener('click', () => placePaper('BUY')); @@ -520,7 +518,7 @@ $('portfolio-reset').addEventListener('click', () => { paperLoadWarning = ''; const status = $('paper-status'); status.textContent = ''; status.className = 'paper-status'; setPortfolioStatus(''); - renderPaper(); renderPortfolio(); + renderPaper(); renderPractice(); }); $('portfolio-export').addEventListener('click', () => { if (!paper.fills.length) { setPortfolioStatus('No paper fills to export yet.', 'warning'); return; } @@ -530,51 +528,297 @@ $('portfolio-export').addEventListener('click', () => { setPortfolioStatus(`Exported ${paper.fills.length} simulated ${paper.fills.length === 1 ? 'fill' : 'fills'} to CSV.`); }); -/* Portfolio page: paper cash, open positions and simulated fills. */ -function renderPortfolio() { - const entries = Object.entries(paper.positions); +/* Portfolio page: Alpaca paper account, manual trades, auto-trade watcher and equity history. */ +function renderPractice() { + setText('portfolio-note', paperLoadWarning || ''); +} + +/* Alpaca paper account: real paper trading through the local server. */ +const autoKey = 'fasttrade-auto'; +const autoLogKey = 'fasttrade-auto-log'; +const equityKey = 'fasttrade-equity'; +const AUTO_INTERVAL_MS = 5 * 60 * 1000; +let account = null; +let accountBusy = false; +let auto = {enabled: false, running: false}; +let autoLog = []; +let equityHistory = []; +let selectedSnapshot = null; +let equityLayoutState = null; +let tradeDebounce = null; +try { + const storedLog = JSON.parse(localStorage.getItem(autoLogKey) || '[]'); + if (Array.isArray(storedLog)) autoLog = storedLog.filter(entry => entry && typeof entry.time === 'string' && typeof entry.action === 'string' && typeof entry.detail === 'string').slice(0, 50); +} catch { /* start with an empty activity log */ } +try { + const storedEquity = JSON.parse(localStorage.getItem(equityKey) || '[]'); + if (Array.isArray(storedEquity)) equityHistory = storedEquity.filter(point => point && typeof point.time === 'string' && Number.isFinite(point.equity) && Number.isFinite(point.cash) && Number.isFinite(point.value)).slice(-500); +} catch { /* start without history */ } +try { auto.enabled = localStorage.getItem(autoKey) === 'on'; } catch { /* default off */ } +function saveAutoLog() { try { localStorage.setItem(autoLogKey, JSON.stringify(autoLog.slice(0, 50))); } catch { /* keep in memory only */ } } +function saveEquity() { try { localStorage.setItem(equityKey, JSON.stringify(equityHistory)); } catch { /* keep in memory only */ } } +function formatCap(value) { + if (!Number.isFinite(value) || value <= 0) return 'unknown'; + if (value >= 1e12) return `${number(value / 1e12)}T`; + if (value >= 1e9) return `${number(value / 1e9)}B`; + return `${number(value / 1e6)}M`; +} +function renderAccount() { + const has = Boolean(account); + $('account-empty').hidden = has; + $('account-content').hidden = !has; + if (!has) return; + setText('account-cash', number(account.cash)); + setText('account-buying-power', number(account.buying_power)); + setText('account-equity', number(account.equity)); + setText('account-value', number(account.equity - account.cash)); + const entries = account.positions; $('positions-empty').hidden = entries.length > 0; $('positions').hidden = entries.length === 0; const body = $('positions').querySelector('tbody'); body.replaceChildren(); - let marketValue = 0, unrealized = 0, allPriced = true; - for (const [symbol, held] of entries) { - const last = lastPrices.get(symbol); - const avg = held.cost / held.shares; - const value = last != null ? held.shares * last : held.cost; - if (last == null) allPriced = false; - else unrealized += (last - avg) * held.shares; - marketValue += value; + for (const held of entries) { const row = document.createElement('tr'); - for (const [label, text] of [['Symbol', symbol], ['Shares', number(held.shares)], ['Avg cost', number(avg)], ['Last price', last != null ? number(last) : 'No price yet'], ['Value', number(value)], ['Unrealized P&L', last != null ? `${last >= avg ? '+' : ''}${number((last - avg) * held.shares)}` : 'n/a']]) { + for (const [label, text] of [['Symbol', held.symbol], ['Shares', number(held.quantity, 4)], ['Avg price', number(held.avg_price)], ['Last price', number(held.price)], ['Value', number(held.value)], ['Unrealized P&L', `${held.unrealized >= 0 ? '+' : ''}${number(held.unrealized)}`]]) { const cell = document.createElement('td'); cell.dataset.label = label; cell.textContent = text; row.append(cell); } body.append(row); } - const equity = paper.cash + marketValue; - const total = equity - PAPER_START_CASH; - const totalPct = total / PAPER_START_CASH * 100; - const priced = !entries.length || allPriced; - setText('portfolio-cash', number(paper.cash)); - setText('portfolio-value', number(marketValue)); - setText('portfolio-equity', number(equity)); - setText('portfolio-realized', `${paper.realized >= 0 ? '+' : ''}${number(paper.realized)}`); - setText('portfolio-unrealized', priced ? `${unrealized >= 0 ? '+' : ''}${number(unrealized)}` : 'Unavailable'); - setText('portfolio-total', priced ? `${total >= 0 ? '+' : ''}${number(total)}` : 'Unavailable'); - setText('portfolio-total-pct', priced ? `${total >= 0 ? '+' : ''}${number(totalPct)}% of starting cash` : 'Some positions have no analyzed price'); - setText('portfolio-note', paperLoadWarning || (allPriced ? '' : 'Symbols without a recent analysis are valued at cost.')); - const fillsBody = $('fills').querySelector('tbody'); fillsBody.replaceChildren(); - $('fills').hidden = paper.fills.length === 0; - $('fills-empty').hidden = paper.fills.length > 0; - for (const fill of paper.fills) { - const row = document.createElement('tr'); - for (const [label, text] of [['Time', formatTime(fill.time)], ['Symbol', fill.symbol], ['Side', fill.side], ['Shares', number(fill.quantity)], ['Price', number(fill.price)], ['Value', number(fill.value)]]) { - const cell = document.createElement('td'); cell.dataset.label = label; cell.textContent = text; row.append(cell); +} +async function refreshAccount() { + if (accountBusy) return; + accountBusy = true; + try { + const response = await fetch('/api/paper/account'); + const data = await response.json(); + if (!response.ok) throw new Error(data.error || 'Alpaca paper account unavailable'); + account = data; + setPortfolioStatus(''); + renderAccount(); + snapshotEquity(); + } catch (error) { + if (!account) $('account-empty').textContent = error.message; + setPortfolioStatus(error.message, 'bad'); + } finally { + accountBusy = false; + } +} +$('portfolio-refresh').addEventListener('click', () => refreshAccount()); + +/* Manual trade form: market orders on the Alpaca paper account. */ +function tradeSymbol() { return $('trade-symbol').value.trim().toUpperCase(); } +function heldQuantity(symbol) { return account?.positions?.find(entry => entry.symbol === symbol)?.quantity || 0; } +function renderTrade() { + const symbol = tradeSymbol(); + const qty = Number($('trade-qty').value); + const price = Number($('trade-price').dataset.price); + const held = heldQuantity(symbol); + const valid = Boolean(symbol) && Number.isFinite(qty) && qty > 0; + const priced = Number.isFinite(price) && price > 0; + setText('trade-estimate', !symbol ? '' : !valid ? 'Enter a share quantity greater than zero.' : priced ? `Estimated ${number(qty * price)} · Alpaca fills market orders at the next available price` : 'No Alpaca price for this symbol yet.'); + $('trade-buy').disabled = !(valid && priced && qty * price <= (account?.buying_power ?? 0) + 1e-9); + $('trade-sell').disabled = !(valid && held > 0 && qty <= held + 1e-9); +} +async function fetchTradePrice() { + const symbol = tradeSymbol(); + const el = $('trade-price'); + if (!symbol) { delete el.dataset.price; el.textContent = ''; renderTrade(); return; } + el.textContent = 'Fetching Alpaca price...'; + try { + const data = await jsonRequest(`/api/paper/price?symbol=${encodeURIComponent(symbol)}`); + el.dataset.price = String(data.price); + el.textContent = `Last trade ${number(data.price)}`; + } catch (error) { + delete el.dataset.price; + el.textContent = error.message; + } + renderTrade(); +} +async function placeTrade(side) { + const symbol = tradeSymbol(); + const qty = Number($('trade-qty').value); + if (!symbol || !Number.isFinite(qty) || !(qty > 0)) return; + try { + const order = await jsonRequest('/api/paper/order', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({symbol, side, quantity: qty})}); + await refreshAccount(); + setPortfolioStatus(`${side} order for ${number(qty)} ${symbol} submitted · status ${order.status}${order.filled_avg_price ? ` · filled ${number(order.filled_avg_price)}` : ''}.`, 'good'); + } catch (error) { + setPortfolioStatus(error.message, 'bad'); + } +} +$('trade-symbol').addEventListener('input', () => { clearTimeout(tradeDebounce); tradeDebounce = setTimeout(fetchTradePrice, 500); renderTrade(); }); +$('trade-qty').addEventListener('input', renderTrade); +$('trade-buy').addEventListener('click', () => placeTrade('BUY')); +$('trade-sell').addEventListener('click', () => placeTrade('SELL')); + +/* Auto-trade watcher: every 5 minutes, decide on the strongest $1B+ gainer and act on it. */ +async function jsonRequest(url, options) { + const response = await fetch(url, options); + const data = await response.json(); + if (!response.ok) throw new Error(data.error || `${response.status} request failed`); + return data; +} +function autoQuantity(action, symbol, price) { + if (!Number.isFinite(price) || !(price > 0)) return 0; + if (action === 'BUY') return Math.floor((account?.cash ?? 0) * 0.1 / price); + return Math.floor(heldQuantity(symbol) * 0.1 * 10000) / 10000; +} +function autoNote(entry) { + autoLog.unshift(entry); + if (autoLog.length > 50) autoLog.length = 50; + saveAutoLog(); + renderAuto(); +} +function renderAuto() { + $('auto-toggle').checked = auto.enabled; + $('auto-run').disabled = !auto.enabled || auto.running; + setText('auto-status', auto.running ? 'Auto-trade tick in progress...' : auto.enabled ? 'Watching every 5 minutes for a $1B+ gainer. Each tick runs one real decision.' : 'Turn on to auto-trade the strongest $1B+ gainer every 5 minutes.'); + const list = $('auto-log'); + list.hidden = autoLog.length === 0; + list.replaceChildren(); + for (const entry of autoLog) { + const row = document.createElement('li'); + const badge = document.createElement('span'); + badge.className = `auto-badge ${entry.action === 'BUY' ? 'up' : entry.action === 'SELL' ? 'down' : ''}`.trim(); + badge.textContent = entry.action; + const text = document.createElement('span'); + text.textContent = `${formatTime(entry.time)} · ${entry.symbol || 'market'} · ${entry.detail}`; + row.append(badge, text); + list.append(row); + } +} +async function autoTick(force = false) { + if (!auto.enabled || auto.running || (!force && document.hidden)) return; + auto.running = true; + renderAuto(); + try { + const movers = await jsonRequest('/api/paper/movers'); + const pick = movers.pick; + if (!pick) { + autoNote({time: new Date().toISOString(), symbol: '', action: 'WAIT', detail: `No gainer with a $1B+ cap today (${movers.considered.length} candidates checked).`}); + return; } - fillsBody.append(row); + const analysis = await jsonRequest('/api/analyze', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({symbol: pick.symbol, timeframe: '5m', source: 'alpaca'})}); + const action = analysis.actionable_signal ?? analysis.decision?.action ?? 'HOLD'; + let detail = `cap ${formatCap(pick.market_cap)} · +${number(pick.change_percent)}%`; + if (action === 'HOLD') detail += ' · decision: hold, no trade'; + else { + const price = Number.isFinite(analysis.market?.features?.price) ? analysis.market.features.price : pick.price; + const quantity = autoQuantity(action, pick.symbol, price); + if (!(quantity > 0)) detail += ` · decision: ${action.toLowerCase()}, skipped (no size available)`; + else { + const order = await jsonRequest('/api/paper/order', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({symbol: pick.symbol, side: action, quantity})}); + detail += ` · decision: ${action.toLowerCase()} ${number(quantity)} shares · order ${order.status}`; + } + } + autoNote({time: new Date().toISOString(), symbol: pick.symbol, action, detail}); + } catch (error) { + autoNote({time: new Date().toISOString(), symbol: '', action: 'ERROR', detail: error.message}); + } finally { + auto.running = false; + renderAuto(); + refreshAccount(); + } +} +function setAutoEnabled(enabled) { + auto.enabled = enabled; + try { localStorage.setItem(autoKey, enabled ? 'on' : 'off'); } catch { /* keep in memory only */ } + renderAuto(); + if (enabled) autoTick(); +} +$('auto-toggle').addEventListener('change', () => setAutoEnabled($('auto-toggle').checked)); +$('auto-run').addEventListener('click', () => autoTick(true)); +setInterval(autoTick, AUTO_INTERVAL_MS); +renderAuto(); +renderTrade(); + +/* Equity history: snapshots of the Alpaca paper account, stored in this browser. */ +function snapshotEquity() { + if (!account || !Number.isFinite(account.equity)) return; + const now = Date.now(); + const last = equityHistory[equityHistory.length - 1]; + if (last && now - new Date(last.time).getTime() < 60000 && last.equity === account.equity) return; + equityHistory.push({time: new Date(now).toISOString(), equity: account.equity, cash: account.cash, value: account.equity - account.cash}); + if (equityHistory.length > 500) equityHistory.length = 500; + saveEquity(); + drawEquity(); +} +function drawEquity() { + const canvas = $('equity-chart'), ctx = canvas.getContext('2d'); + const w = canvas.clientWidth, h = canvas.clientHeight, scale = window.devicePixelRatio || 1; + if (!w || !h) return; + canvas.width = Math.round(w * scale); canvas.height = Math.round(h * scale); + ctx.setTransform(scale, 0, 0, scale, 0, 0); ctx.clearRect(0, 0, w, h); + const points = equityHistory; + $('equity-empty').hidden = points.length > 0; + $('equity-readout').hidden = points.length === 0; + if (!points.length) return; + const values = points.map(point => point.equity); + const rawLow = Math.min(...values), rawHigh = Math.max(...values); + const padding = rawHigh > rawLow ? (rawHigh - rawLow) * .07 : Math.max(Math.abs(rawHigh) * .005, 1e-8); + const low = rawLow - padding, high = rawHigh + padding, span = high - low; + const precision = ChartMath.priceDigits(span); + ctx.font = '10px ui-monospace, monospace'; + const axisWidth = Math.max(62, ctx.measureText(number(high, precision)).width + 12, ctx.measureText(number(low, precision)).width + 12); + const layout = ChartMath.chartLayout(w, h, points.length, axisWidth); + equityLayoutState = layout; + const {left, plotWidth, top, priceBottom, volumeTop, volumeBottom, step} = layout; + const y = value => top + (high - value) / span * (priceBottom - top); + const x = index => left + step * (index + .5); + ctx.font = '10px ui-monospace, monospace'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; + for (let n = 0; n <= 4; n++) { + const value = high - span * n / 4, py = y(value); + ctx.strokeStyle = '#dce3ed'; ctx.lineWidth = .7; + ctx.beginPath(); ctx.moveTo(left, py); ctx.lineTo(left + plotWidth, py); ctx.stroke(); + ctx.fillStyle = '#506177'; ctx.fillText(number(value, precision), w - 2, py); + } + ctx.strokeStyle = '#245de0'; ctx.lineWidth = 1.6; + ctx.beginPath(); + points.forEach((point, i) => i ? ctx.lineTo(x(i), y(point.equity)) : ctx.moveTo(x(0), y(points[0].equity))); + ctx.stroke(); + ctx.lineTo(x(points.length - 1), priceBottom); ctx.lineTo(x(0), priceBottom); ctx.closePath(); + ctx.fillStyle = 'rgba(36, 93, 224, .08)'; ctx.fill(); + ctx.fillStyle = '#506177'; ctx.textBaseline = 'bottom'; + const labels = ChartMath.timeLabels(points.map(point => ({timestamp: point.time})), plotWidth >= 450 ? 3 : 2); + labels.forEach((label, i) => { + ctx.textAlign = i === 0 ? 'left' : i === labels.length - 1 ? 'right' : 'center'; + const pos = i === 0 ? left : i === labels.length - 1 ? left + plotWidth : x(label.index); + ctx.fillText(label.text, pos, h - 3); + }); + if (selectedSnapshot !== null) { + selectedSnapshot = Math.min(selectedSnapshot, points.length - 1); + ctx.save(); ctx.setLineDash([3, 3]); ctx.strokeStyle = '#1c3155bb'; ctx.beginPath(); + ctx.moveTo(x(selectedSnapshot), top); ctx.lineTo(x(selectedSnapshot), volumeBottom); ctx.stroke(); ctx.restore(); } + const selected = points[selectedSnapshot === null ? points.length - 1 : selectedSnapshot]; + const change = selected.equity - points[0].equity; + setText('snapshot-time', `SNAPSHOT ${formatTime(selected.time)}`); + setText('snapshot-equity', number(selected.equity)); + setText('snapshot-cash', number(selected.cash)); + setText('snapshot-value', number(selected.value)); + setText('snapshot-change', `${change >= 0 ? '+' : ''}${number(change)} since first snapshot`); + $('snapshot-change').className = change >= 0 ? 'signal-buy' : 'signal-sell'; +} +function selectSnapshot(event) { + const canvas = $('equity-chart'), points = equityHistory; + if (!points.length) return; + const rect = canvas.getBoundingClientRect(); + const layout = equityLayoutState || ChartMath.chartLayout(canvas.clientWidth, canvas.clientHeight, points.length); + selectedSnapshot = ChartMath.candleAtX(event.clientX - rect.left, layout, points.length); + drawEquity(); } -for (const entry of savedHistory) if (!lastPrices.has(entry.market.symbol) && Number.isFinite(entry.market?.features?.price)) lastPrices.set(entry.market.symbol, entry.market.features.price); -renderPortfolio(); +$('equity-chart').addEventListener('pointermove', event => { if (event.pointerType === 'mouse') selectSnapshot(event); }); +$('equity-chart').addEventListener('pointerdown', selectSnapshot); +$('equity-chart').addEventListener('pointerleave', () => { selectedSnapshot = null; drawEquity(); }); +$('equity-chart').addEventListener('keydown', event => { + if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return; + const points = equityHistory; + if (!points.length) return; + event.preventDefault(); + const index = selectedSnapshot === null ? points.length - 1 : selectedSnapshot; + selectedSnapshot = event.key === 'Home' ? 0 : event.key === 'End' ? points.length - 1 : Math.max(0, Math.min(points.length - 1, index + (event.key === 'ArrowLeft' ? -1 : 1))); + drawEquity(); +}); +renderPractice(); function visibleCandles() { return current?.candles?.slice(-Number($('chart-window').value)) || []; @@ -728,7 +972,7 @@ $('chart').addEventListener('keydown', event => { selectedCandle = event.key === 'Home' ? 0 : event.key === 'End' ? candles.length - 1 : Math.max(0, Math.min(candles.length - 1, index + (event.key === 'ArrowLeft' ? -1 : 1))); drawChart(); }); -window.addEventListener('resize', drawChart); +window.addEventListener('resize', () => { drawChart(); drawEquity(); }); $('chart-window').addEventListener('change', () => { selectedCandle = null; drawChart(); }); $('chart-overlay').addEventListener('change', drawChart); $('chart-window').disabled = true; $('chart-overlay').disabled = true; @@ -746,6 +990,7 @@ function syncNavigation() { else link.removeAttribute('aria-current'); } if (!$('analysis-view').hidden && current) drawChart(); + if (destination === '#portfolio-panel') { refreshAccount(); drawEquity(); } if (analysisWasHidden && destination === '#chart-panel') $('chart-panel').scrollIntoView(); } window.addEventListener('hashchange', syncNavigation); @@ -812,7 +1057,6 @@ $('analysis-form').addEventListener('submit', async (event) => { data._notice = data.stale_preview ? ['The latest candle is stale. This is a historical research preview; portfolio actions are blocked.', 'warning'] : data.source === 'Synthetic sample CSV' ? ['Synthetic sample candles are displayed. The model response is real; this is not live market data.', 'warning'] : [`Analysis complete. Candle started ${formatTime(data.market.candle_timestamp)}. Model preferences are not trading outcomes.`, 'success']; - if (Number.isFinite(data.market?.features?.price)) lastPrices.set(symbol, data.market.features.price); } catch (error) { failures.set(symbol, error instanceof TypeError ? 'Could not reach the local server. Check that FastTrade is running, then try again.' : error instanceof Error && error.message ? error.message : 'The request failed.'); @@ -836,7 +1080,7 @@ $('analysis-form').addEventListener('submit', async (event) => { if (!succeeded.length) { const message = failures.get(symbols[0]) || 'The analysis failed.'; showNotice(symbols.length > 1 ? `${symbols[0]}: ${message}` : `${message} No actionable signal is available.`, 'error'); - renderTabs(); renderPortfolio(); + renderTabs(); renderPractice(); return; } const selected = results.has(activeSymbol) ? activeSymbol : succeeded[0]; diff --git a/fasttrade/static/index.html b/fasttrade/static/index.html index b5fbf78..49617f4 100644 --- a/fasttrade/static/index.html +++ b/fasttrade/static/index.html @@ -85,7 +85,7 @@ - + diff --git a/fasttrade/static/style.css b/fasttrade/static/style.css index c2c5d27..3573878 100644 --- a/fasttrade/static/style.css +++ b/fasttrade/static/style.css @@ -551,7 +551,7 @@ body { background: #f2f5f8; } .paper-status.good { color: #146444; } .paper-status.bad { color: #972d3d; } .portfolio-card { margin-top: 8px; } -.portfolio-strip { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 8px; margin-top: 14px; } +.portfolio-strip { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-top: 14px; } .portfolio-strip .summary-card { min-width: 0; min-height: 0; padding: 12px 14px; border: 1px solid #e5eff8; border-radius: 7px; background: var(--surface); display: flex; flex-direction: column; color: #566a7c; font: 10px var(--mono); letter-spacing: .04em; } .portfolio-strip .summary-card strong { margin-top: 6px; color: #121b27; font: 600 18px/1.25 system-ui, sans-serif; letter-spacing: 0; overflow-wrap: anywhere; } .portfolio-note { min-height: 1.2em; margin: 8px 0 0; color: #7b520d; font-size: 12px; } @@ -568,6 +568,22 @@ body { background: #f2f5f8; } .paper-details[open] summary::before { content: '▾'; } .paper-details summary:hover { text-decoration: underline; } .paper-details p { margin: 8px 0 0; } +.trade-form { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto auto; gap: 8px; align-items: end; margin-top: 12px; } +.trade-form label { min-width: 0; } +.trade-form input { margin-top: 6px; } +#trade-buy, #trade-sell { min-height: 44px; padding: 0 18px; border-radius: 7px; border: 1px solid transparent; font-weight: 700; } +#trade-buy:not(:disabled) { background: #edf8f1; color: #146444; border-color: #b9dfc9; } +#trade-sell:not(:disabled) { background: #fff1f2; color: #972d3d; border-color: #e9bfc5; } +#trade-buy:not(:disabled):hover, #trade-sell:not(:disabled):hover { filter: brightness(.97); } +#trade-buy:disabled, #trade-sell:disabled { background: #f2f5f8; color: #66748b; border-color: #d8e1ea; cursor: not-allowed; } +.auto-controls { margin-top: 12px; } +.auto-log { margin: 12px 0 0; padding: 0; list-style: none; display: grid; gap: 8px; } +.auto-log li { display: flex; gap: 8px; align-items: baseline; padding: 8px 10px; border: 1px solid #e3e9ef; border-radius: 7px; color: #3d4d61; font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; } +.auto-badge { flex: none; padding: 2px 8px; border-radius: 5px; font: 700 10px var(--mono); letter-spacing: .03em; background: #f2f5f8; color: #45566b; border: 1px solid #d8e1ea; } +.auto-badge.up { background: #edf8f1; color: #146444; border-color: #b9dfc9; } +.auto-badge.down { background: #fff1f2; color: #972d3d; border-color: #e9bfc5; } +.equity-wrap { height: 200px; } +@media (max-width: 760px) { .equity-wrap { height: 160px; } .trade-form { grid-template-columns: 1fr 1fr; } } .portfolio-strip { gap: 0; border-block: 1px solid #e3e9ef; margin-top: 16px; } .portfolio-strip .summary-card { padding: 12px; border: 0; border-radius: 0; background: transparent; } .portfolio-strip .summary-card + .summary-card { border-left: 1px solid #e3e9ef; } diff --git a/fasttrade/web.py b/fasttrade/web.py index e6c30f5..88d60e9 100644 --- a/fasttrade/web.py +++ b/fasttrade/web.py @@ -26,6 +26,7 @@ from .decisions import predict from .indicators import features, rule_signal from .market import INTERVALS, alpaca, alpaca_news, validate_candles +from . import paper ROOT = Path(__file__).resolve().parent PORT = 8765 @@ -115,6 +116,13 @@ class SpySignalsRequest(BaseModel): model_config = ConfigDict(extra='forbid') +class PaperOrderRequest(BaseModel): + model_config = ConfigDict(extra='forbid', allow_inf_nan=False) + symbol: str = Field(min_length=1, max_length=20, pattern=r'^[A-Za-z0-9.\^=\-]+$', description='US stock ticker symbol') + side: Literal['BUY', 'SELL'] + quantity: float = Field(gt=0) + + class DecisionResponse(BaseModel): action: Literal['BUY', 'HOLD', 'SELL'] probabilities: dict[str, float] @@ -437,6 +445,65 @@ def spy_signals(body: SpySignalsRequest): return result +_paper_cache = None +_movers_cache = None +_paper_lock = Lock() + + +@app.get('/api/paper/account', tags=['Paper']) +def paper_account(): + """Return the Alpaca paper account overview, cached for 10 seconds.""" + global _paper_cache + with _paper_lock: + if _paper_cache is not None and monotonic() - _paper_cache[0] < 10: + return _paper_cache[1] + try: + result = paper.overview() + except ValueError as exc: + return JSONResponse({'error': str(exc)}, status_code=503) + with _paper_lock: + _paper_cache = (monotonic(), result) + return result + + +@app.post('/api/paper/order', tags=['Paper']) +async def paper_order(body: PaperOrderRequest): + """Submit a market order to the Alpaca paper account. Paper trading only, never live.""" + try: + result = await run_in_threadpool(paper.submit_order, body.symbol, body.side, body.quantity) + except ValueError as exc: + return JSONResponse({'error': str(exc)}, status_code=503) + global _paper_cache + with _paper_lock: + _paper_cache = None + return result + + +@app.get('/api/paper/price', tags=['Paper']) +async def paper_price(symbol: str): + """Return the latest Alpaca trade price used to size manual orders.""" + try: + return await run_in_threadpool(paper.last_price, symbol) + except ValueError as exc: + return JSONResponse({'error': str(exc)}, status_code=503) + + +@app.get('/api/paper/movers', tags=['Paper']) +def paper_movers(): + """Return today's qualifying gainer among stocks with a market cap of $1B or more, cached for 60 seconds.""" + global _movers_cache + with _paper_lock: + if _movers_cache is not None and monotonic() - _movers_cache[0] < 60: + return _movers_cache[1] + try: + result = paper.movers() + except ValueError as exc: + return JSONResponse({'error': str(exc)}, status_code=503) + with _paper_lock: + _movers_cache = (monotonic(), result) + return result + + async def analyze(body: AnalysisRequest): """Analyze completed candles; incomplete risk inputs produce signal-only results.""" args = parser().parse_args(['analyze', body.symbol.upper(), '--timeframe', body.timeframe]) diff --git a/tests/test_paper.py b/tests/test_paper.py new file mode 100644 index 0000000..e3981d2 --- /dev/null +++ b/tests/test_paper.py @@ -0,0 +1,129 @@ +from collections import OrderedDict + +import httpx +import pytest + +from fasttrade import market, paper + + +@pytest.fixture(autouse=True) +def isolated_caches(monkeypatch): + monkeypatch.setattr(market, '_cap_cache', OrderedDict()) + + +def test_overview_sums_account_and_positions(monkeypatch): + def get(url, **kwargs): + assert kwargs['headers']['APCA-API-KEY-ID'] == 'key' and kwargs['headers']['APCA-API-SECRET-KEY'] == 'secret' + assert url.endswith('/v2/account') or url.endswith('/v2/positions') + if url.endswith('/account'): + return httpx.Response(200, json={'cash': '950.50', 'equity': '1075.25', 'buying_power': '2000'}, request=httpx.Request('GET', url)) + return httpx.Response(200, json=[ + {'symbol': 'NVDA', 'qty': '2', 'avg_entry_price': '100', 'current_price': '62.375', 'market_value': '124.75', 'unrealized_pl': '-75.25'}, + {'symbol': 'BAD'}, + ], request=httpx.Request('GET', url)) + monkeypatch.setattr(paper, 'pooled_get', get) + monkeypatch.setenv('ALPACA_API_KEY', 'key') + monkeypatch.setenv('ALPACA_SECRET_KEY', 'secret') + result = paper.overview() + assert result['cash'] == 950.5 and result['equity'] == 1075.25 and result['buying_power'] == 2000 + assert result['positions'] == [{'symbol': 'NVDA', 'quantity': 2.0, 'avg_price': 100.0, 'price': 62.375, 'value': 124.75, 'unrealized': -75.25}] + + +def test_overview_maps_errors_without_leaking_secrets(monkeypatch): + monkeypatch.setenv('ALPACA_API_KEY', 'private-key') + monkeypatch.setenv('ALPACA_SECRET_KEY', 'private-secret') + monkeypatch.setattr(paper, 'pooled_get', lambda url, **kwargs: httpx.Response(403, text='private-secret', request=httpx.Request('GET', url))) + with pytest.raises(ValueError, match='rejected the paper trading credentials') as error: + paper.overview() + assert 'private-secret' not in str(error.value) + monkeypatch.delenv('ALPACA_API_KEY', raising=False) + with pytest.raises(ValueError, match='credentials are missing'): + paper.overview() + + +def test_last_price_reads_latest_trade(monkeypatch): + monkeypatch.setenv('ALPACA_API_KEY', 'key') + monkeypatch.setenv('ALPACA_SECRET_KEY', 'secret') + seen = {} + def get(url, **kwargs): + seen['url'], seen['params'] = url, kwargs.get('params') + return httpx.Response(200, json={'trades': {'AAPL': {'t': '2026-01-02T15:00:00Z', 'p': '142.85', 's': 100}}}, request=httpx.Request('GET', url)) + monkeypatch.setattr(paper, 'pooled_get', get) + assert paper.last_price('aapl') == {'symbol': 'AAPL', 'price': 142.85} + assert seen['url'].endswith('/v2/stocks/trades/latest') and seen['params']['symbols'] == 'AAPL' + monkeypatch.setattr(paper, 'pooled_get', lambda url, **kwargs: httpx.Response(200, json={'trades': {}}, request=httpx.Request('GET', url))) + with pytest.raises(ValueError, match='No Alpaca trade price'): + paper.last_price('AAPL') + + +def test_submit_order_posts_market_order_and_reports_fill(monkeypatch): + posted = {} + def post(url, **kwargs): + posted['url'], posted['json'] = url, kwargs['json'] + return httpx.Response(200, json={'id': 'order-1', 'status': 'accepted', 'filled_qty': '1', 'filled_avg_price': None}, request=httpx.Request('POST', url)) + monkeypatch.setattr(paper, 'pooled_post', post) + monkeypatch.setenv('ALPACA_API_KEY', 'key') + monkeypatch.setenv('ALPACA_SECRET_KEY', 'secret') + result = paper.submit_order('nvda', 'BUY', 1.5) + assert posted['json'] == {'symbol': 'NVDA', 'qty': '1.5', 'side': 'buy', 'type': 'market', 'time_in_force': 'day'} + assert result == {'symbol': 'NVDA', 'side': 'BUY', 'quantity': 1.5, 'order_id': 'order-1', 'status': 'accepted', 'filled_quantity': 1.0, 'filled_avg_price': None} + with pytest.raises(ValueError, match='side must be BUY or SELL'): + paper.submit_order('NVDA', 'HOLD', 1) + with pytest.raises(ValueError, match='quantity must be positive'): + paper.submit_order('NVDA', 'BUY', 0) + + +def test_submit_order_reports_rejection_reason(monkeypatch): + monkeypatch.setenv('ALPACA_API_KEY', 'key') + monkeypatch.setenv('ALPACA_SECRET_KEY', 'secret') + monkeypatch.setattr(paper, 'pooled_post', lambda url, **kwargs: httpx.Response(403, json={'message': 'insufficient buying power'}, request=httpx.Request('POST', url))) + with pytest.raises(ValueError, match='insufficient buying power'): + paper.submit_order('NVDA', 'BUY', 100) + + +def test_movers_picks_top_gainer_with_required_cap(monkeypatch): + monkeypatch.setenv('ALPACA_API_KEY', 'key') + monkeypatch.setenv('ALPACA_SECRET_KEY', 'secret') + monkeypatch.setattr(paper, 'pooled_get', lambda url, **kwargs: httpx.Response(200, json={'gainers': [ + {'symbol': 'SMALL', 'price': 12.0, 'percent_change': 9.1, 'change': 1.0}, + {'symbol': 'MYSTERY', 'price': 30.0, 'percent_change': 6.2, 'change': 1.5}, + {'symbol': 'BIGCO', 'price': 220.0, 'percent_change': 3.2, 'change': 6.8}, + ]}, request=httpx.Request('GET', url))) + def cap(symbol): + if symbol == 'SMALL': + return 5e8 + if symbol == 'MYSTERY': + raise ValueError('cap unavailable') + return 3.4e12 + monkeypatch.setattr(paper.market, 'market_cap', cap) + result = paper.movers() + assert result['pick']['symbol'] == 'BIGCO' and result['pick']['market_cap'] == 3.4e12 + assert [entry['symbol'] for entry in result['considered']] == ['SMALL', 'MYSTERY', 'BIGCO'] + assert result['considered'][1]['market_cap'] is None + + +def test_movers_without_qualifying_cap_reports_none(monkeypatch): + monkeypatch.setenv('ALPACA_API_KEY', 'key') + monkeypatch.setenv('ALPACA_SECRET_KEY', 'secret') + monkeypatch.setattr(paper, 'pooled_get', lambda url, **kwargs: httpx.Response(200, json={'gainers': [ + {'symbol': 'SMALL', 'price': 12.0, 'percent_change': 9.1, 'change': 1.0}, + ]}, request=httpx.Request('GET', url))) + monkeypatch.setattr(paper.market, 'market_cap', lambda symbol: 5e8) + result = paper.movers() + assert result['pick'] is None and result['considered'][0]['market_cap'] == 5e8 + monkeypatch.setattr(paper, 'pooled_get', lambda url, **kwargs: httpx.Response(200, json={'gainers': []}, request=httpx.Request('GET', url))) + assert paper.movers()['pick'] is None + + +def test_market_cap_caches_per_symbol(monkeypatch): + calls = [] + def info(operation): + calls.append(1) + return {'marketCap': 3.4e12} + monkeypatch.setattr(market, '_yahoo_request', info) + assert market.market_cap('nvda') == 3.4e12 + assert market.market_cap('NVDA') == 3.4e12 + assert len(calls) == 1 + monkeypatch.setattr(market, '_yahoo_request', lambda operation: {}) + with pytest.raises(ValueError, match='Market cap unavailable'): + market.market_cap('OTHER') diff --git a/tests/test_web.py b/tests/test_web.py index 2d30773..d4b514f 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -597,3 +597,61 @@ def test_network_binding_refuses_missing_hashed_keys(monkeypatch): monkeypatch.delenv('FASTTRADE_BATCH_KEY_HASHES', raising=False) with pytest.raises(SystemExit, match='valid hashed API keys'): web.serve() + + +def test_paper_account_endpoint_caches_and_reports_errors(monkeypatch): + from fasttrade import web + calls = [] + def overview(): + calls.append(1) + return {'cash': 950.5, 'equity': 1075.25, 'buying_power': 2000.0, 'positions': []} + monkeypatch.setattr(web, '_paper_cache', None) + monkeypatch.setattr(web.paper, 'overview', overview) + client = TestClient(web.app, base_url='http://127.0.0.1:8765', client=('127.0.0.1', 50000)) + first = client.get('/api/paper/account') + assert first.status_code == 200 and first.json()['equity'] == 1075.25 + monkeypatch.setattr(web.paper, 'overview', lambda: (_ for _ in ()).throw(AssertionError('must use cache'))) + assert client.get('/api/paper/account').status_code == 200 + assert len(calls) == 1 + monkeypatch.setattr(web, '_paper_cache', None) + monkeypatch.setattr(web.paper, 'overview', lambda: (_ for _ in ()).throw(ValueError('Alpaca credentials are missing'))) + failed = client.get('/api/paper/account') + assert failed.status_code == 503 and failed.json()['error'] == 'Alpaca credentials are missing' + + +def test_paper_order_endpoint_validates_and_clears_cache(monkeypatch): + from fasttrade import web + submitted = [] + def submit_order(symbol, side, quantity): + submitted.append((symbol, side, quantity)) + return {'symbol': symbol, 'side': side, 'quantity': quantity, 'order_id': 'order-9', 'status': 'accepted', 'filled_quantity': 0.0, 'filled_avg_price': None} + monkeypatch.setattr(web, '_paper_cache', (0.0, {'cash': 1})) + monkeypatch.setattr(web.paper, 'submit_order', submit_order) + client = TestClient(web.app, base_url='http://127.0.0.1:8765', client=('127.0.0.1', 50000)) + good = client.post('/api/paper/order', json={'symbol': 'nvda', 'side': 'BUY', 'quantity': 1.5}) + assert good.status_code == 200 and good.json()['order_id'] == 'order-9' + assert submitted == [('nvda', 'BUY', 1.5)] + assert web._paper_cache is None + assert client.post('/api/paper/order', json={'symbol': 'NVDA', 'side': 'HOLD', 'quantity': 1}).status_code == 422 + assert client.post('/api/paper/order', json={'symbol': 'NVDA', 'side': 'BUY', 'quantity': 0}).status_code == 422 + assert client.post('/api/paper/order', json={'symbol': 'BAD SYMBOL!', 'side': 'BUY', 'quantity': 1}).status_code == 422 + assert client.post('/api/paper/order', json={'symbol': 'NVDA', 'side': 'BUY', 'quantity': 1, 'extra': 1}).status_code == 422 + monkeypatch.setattr(web.paper, 'submit_order', lambda *args: (_ for _ in ()).throw(ValueError('Alpaca rejected the request: insufficient buying power'))) + rejected = client.post('/api/paper/order', json={'symbol': 'NVDA', 'side': 'BUY', 'quantity': 1000}) + assert rejected.status_code == 503 and 'insufficient buying power' in rejected.json()['error'] + + +def test_paper_price_and_movers_endpoints(monkeypatch): + from fasttrade import web + monkeypatch.setattr(web, '_movers_cache', None) + monkeypatch.setattr(web.paper, 'last_price', lambda symbol: {'symbol': 'AAPL', 'price': 142.85}) + monkeypatch.setattr(web.paper, 'movers', lambda: {'pick': {'symbol': 'BIGCO', 'price': 220.0, 'change_percent': 3.2, 'market_cap': 3.4e12}, 'considered': [], 'minimum_cap': 1_000_000_000}) + client = TestClient(web.app, base_url='http://127.0.0.1:8765', client=('127.0.0.1', 50000)) + price = client.get('/api/paper/price', params={'symbol': 'aapl'}) + assert price.status_code == 200 and price.json()['price'] == 142.85 + movers = client.get('/api/paper/movers') + assert movers.status_code == 200 and movers.json()['pick']['symbol'] == 'BIGCO' + monkeypatch.setattr(web, '_movers_cache', None) + monkeypatch.setattr(web.paper, 'movers', lambda: (_ for _ in ()).throw(ValueError('Alpaca paper trading rate limited'))) + limited = client.get('/api/paper/movers') + assert limited.status_code == 503 and 'rate limited' in limited.json()['error'] diff --git a/tests/ui.test.cjs b/tests/ui.test.cjs index 7b3982e..49c8096 100644 --- a/tests/ui.test.cjs +++ b/tests/ui.test.cjs @@ -54,6 +54,12 @@ function result(symbol = 'NVDA') { }; } +function accountData() { + return {cash: 25000, equity: 26100, buying_power: 50000, positions: [ + {symbol: 'NVDA', quantity: 2, avg_price: 100, price: 550, value: 1100, unrealized: 900}, + ]}; +} + test('dashboard defaults to Alpaca and can analyze with Yahoo Finance', async () => { assert.equal(await page.locator('#chart-window').isDisabled(), true); assert.equal(await page.locator('#chart-overlay').isDisabled(), true); @@ -733,13 +739,13 @@ test('paper trading fills at the analyzed close and only sells held shares', asy await page.locator('#paper-sell').click(); await page.waitForFunction(() => document.getElementById('paper-position').textContent.includes('None held')); assert.equal(await page.locator('#paper-sell').isDisabled(), true); - await page.locator('.desktop-rail a[href="#portfolio-panel"]').click(); - await page.waitForFunction(() => !document.getElementById('fills').hidden); - assert.match(await page.locator('#fills tbody').innerText(), /NVDA/); - assert.match(await page.locator('#portfolio-realized').innerText(), /\+0\.00/); + const stored = JSON.parse(await page.evaluate(() => localStorage.getItem('fasttrade-paper'))); + assert.equal(stored.fills.length, 2); + assert.equal(stored.fills[0].side, 'SELL'); + assert.equal(stored.cash, 10000); }); -test('paper cash limits buys and the portfolio persists across reloads', async () => { +test('paper cash limits buys and the practice portfolio persists across reloads', async () => { const data = result('NVDA'); data.actionable_signal = null; await page.route('**/api/analyze', route => route.fulfill({json: data})); await page.locator('#analyze').click(); @@ -750,25 +756,10 @@ test('paper cash limits buys and the portfolio persists across reloads', async ( await page.locator('#paper-buy').click(); await page.waitForFunction(() => document.getElementById('paper-position').textContent.includes('2.00 shares')); await page.reload(); - await page.waitForFunction(() => document.getElementById('portfolio-cash').textContent.includes('9,714')); - assert.match(await page.locator('#positions tbody').innerText(), /NVDA/); + await page.waitForFunction(() => JSON.parse(localStorage.getItem('fasttrade-paper')).cash === 9714.30); await openView('portfolio-panel'); await page.locator('#portfolio-reset').click(); - await page.waitForFunction(() => document.getElementById('portfolio-cash').textContent.includes('10,000.00')); - assert.equal(await page.locator('#positions').isHidden(), true); -}); - -test('portfolio shows unrealized and total profit and loss', async () => { - await page.evaluate(() => localStorage.setItem('fasttrade-paper', JSON.stringify({version: 1, cash: 9800, positions: {NVDA: {shares: 2, cost: 200}}, realized: 0, fills: []}))); - await page.reload(); - const data = result('NVDA'); - await page.route('**/api/analyze', route => route.fulfill({json: data})); - await page.locator('#analyze').click(); - await page.waitForFunction(() => !document.getElementById('decision-content').hidden); - await openView('portfolio-panel'); - assert.match(await page.locator('#portfolio-unrealized').innerText(), /\+85\.70/); - assert.match(await page.locator('#portfolio-total').innerText(), /\+85\.70/); - assert.match(await page.locator('#portfolio-total-pct').innerText(), /\+0\.86% of starting cash/); + await page.waitForFunction(() => JSON.parse(localStorage.getItem('fasttrade-paper')).cash === 10000); }); test('history exports the displayed analyses as CSV', async () => { @@ -828,30 +819,6 @@ test('history export marks example risk inputs', async () => { assert.match(text, /HOLD,true,,1/); }); -test('portfolio marks profit and loss unavailable when a position has no price', async () => { - await page.evaluate(() => localStorage.setItem('fasttrade-paper', JSON.stringify({version: 1, cash: 9800, positions: {NVDA: {shares: 2, cost: 200}}, realized: 0, fills: []}))); - await page.reload(); - await openView('portfolio-panel'); - assert.equal(await page.locator('#portfolio-unrealized').innerText(), 'Unavailable'); - assert.equal(await page.locator('#portfolio-total').innerText(), 'Unavailable'); - assert.match(await page.locator('#portfolio-total-pct').innerText(), /no analyzed price/); -}); - -test('saved history prices survive reload for the portfolio', async () => { - await openView('history-panel'); - await page.locator('#history-save').check(); - await openView('workspace'); - const data = result('NVDA'); - await page.route('**/api/analyze', route => route.fulfill({json: data})); - await page.locator('#analyze').click(); - await page.waitForFunction(() => document.querySelectorAll('#history tbody tr').length === 1); - await page.evaluate(() => localStorage.setItem('fasttrade-paper', JSON.stringify({version: 1, cash: 9800, positions: {NVDA: {shares: 2, cost: 200}}, realized: 0, fills: []}))); - await page.reload(); - await openView('portfolio-panel'); - assert.match(await page.locator('#portfolio-unrealized').innerText(), /\+85\.70/); - assert.match(await page.locator('#portfolio-total').innerText(), /\+85\.70/); -}); - test('paper fills export as CSV with an explicit empty state', async () => { await openView('portfolio-panel'); await page.locator('#portfolio-export').click(); @@ -909,13 +876,13 @@ test('replayed history entries cannot be paper traded', async () => { assert.equal(await page.locator('#paper-sell').isDisabled(), true); }); -test('existing paper positions and fills remain visible after reload', async () => { +test('existing practice fills remain stored after reload', async () => { await page.evaluate(() => localStorage.setItem('fasttrade-paper', JSON.stringify({version: 1, cash: 9714.30, positions: {NVDA: {shares: 2, cost: 285.70}}, realized: 0, fills: [{time: '2026-01-02T20:55:00Z', symbol: 'NVDA', side: 'BUY', quantity: 2, price: 142.85, value: 285.70}]}))); await page.reload(); - await openView('portfolio-panel'); - assert.match(await page.locator('#positions tbody').innerText(), /NVDA/); - assert.match(await page.locator('#fills tbody').innerText(), /NVDA/); - assert.match(await page.locator('#portfolio-cash').innerText(), /9,714/); + const stored = JSON.parse(await page.evaluate(() => localStorage.getItem('fasttrade-paper'))); + assert.equal(stored.cash, 9714.30); + assert.equal(stored.fills.length, 1); + assert.equal(stored.fills[0].symbol, 'NVDA'); }); test('a corrupt paper portfolio is reported and reset restores storage', async () => { @@ -924,9 +891,7 @@ test('a corrupt paper portfolio is reported and reset restores storage', async ( await page.waitForFunction(() => document.getElementById('portfolio-note').textContent.includes('invalid')); await openView('portfolio-panel'); await page.locator('#portfolio-reset').click(); - await page.waitForFunction(() => document.getElementById('portfolio-cash').textContent.includes('10,000.00')); - const stored = JSON.parse(await page.evaluate(() => localStorage.getItem('fasttrade-paper'))); - assert.equal(stored.cash, 10000); + await page.waitForFunction(() => JSON.parse(localStorage.getItem('fasttrade-paper')).cash === 10000); }); test('history and portfolio pages are reachable from both navigations', async () => { @@ -949,10 +914,14 @@ test('history and portfolio pages are reachable from both navigations', async () await page.setViewportSize({width: 1440, height: 1000}); }); -test('paper trading controls are present and the existing portfolio remains readable', async () => { +test('paper trading controls are present and the account view reports missing credentials', async () => { assert.equal(await page.locator('.paper-card').count(), 1); + await page.route('**/api/paper/account', route => route.fulfill({status: 503, json: {error: 'Alpaca credentials are missing'}})); + await page.reload(); await openView('portfolio-panel'); - assert.equal(await page.locator('#portfolio-cash').innerText(), '10,000.00'); + assert.equal(await page.locator('#account-empty').isHidden(), false); + assert.match(await page.locator('#account-empty').innerText(), /Alpaca credentials are missing/); + assert.equal(await page.locator('#account-content').isHidden(), true); }); test('paper controls follow the current signal and do not offer a blocked trade', async () => { @@ -987,3 +956,99 @@ test('paper quantity and estimated value are suggested and remain editable', asy await page.locator('#paper-qty').fill('2'); assert.match(await page.locator('#paper-estimate').innerText(), /285\.70/); }); + +test('alpaca paper account renders cash, buying power, equity and positions', async () => { + await page.route('**/api/paper/account', route => route.fulfill({json: accountData()})); + await openView('portfolio-panel'); + await page.waitForFunction(() => !document.getElementById('account-content').hidden); + assert.match(await page.locator('#account-cash').innerText(), /25,000/); + assert.match(await page.locator('#account-buying-power').innerText(), /50,000/); + assert.match(await page.locator('#account-equity').innerText(), /26,100/); + assert.match(await page.locator('#positions tbody').innerText(), /NVDA/); + assert.match(await page.locator('#positions tbody').innerText(), /1,100\.00/); +}); + +test('manual trade submits an alpaca market order with the fetched price', async () => { + let order; + await page.route('**/api/paper/account', route => route.fulfill({json: accountData()})); + await page.route('**/api/paper/price**', route => route.fulfill({json: {symbol: 'AAPL', price: 142.85}})); + await page.route('**/api/paper/order', route => { order = route.request().postDataJSON(); return route.fulfill({json: {symbol: 'AAPL', side: 'BUY', quantity: 2, order_id: 'o1', status: 'accepted', filled_quantity: 0, filled_avg_price: null}}); }); + await openView('portfolio-panel'); + await page.waitForFunction(() => !document.getElementById('account-content').hidden); + await page.fill('#trade-symbol', 'aapl'); + await page.fill('#trade-qty', '2'); + await page.waitForFunction(() => document.getElementById('trade-price').textContent.includes('142.85')); + assert.equal(await page.locator('#trade-buy').isEnabled(), true); + assert.equal(await page.locator('#trade-sell').isDisabled(), true); + await page.locator('#trade-buy').click(); + await page.waitForFunction(() => document.getElementById('portfolio-status').textContent.includes('submitted')); + assert.deepEqual(order, {symbol: 'AAPL', side: 'BUY', quantity: 2}); + assert.match(await page.locator('#portfolio-status').innerText(), /submitted · status accepted/); +}); + +test('manual sell is limited to held shares and buy to buying power', async () => { + await page.route('**/api/paper/account', route => route.fulfill({json: accountData()})); + await page.route('**/api/paper/price**', route => route.fulfill({json: {symbol: 'NVDA', price: 550}})); + await openView('portfolio-panel'); + await page.waitForFunction(() => !document.getElementById('account-content').hidden); + await page.fill('#trade-symbol', 'NVDA'); + await page.fill('#trade-qty', '3'); + await page.waitForFunction(() => document.getElementById('trade-price').textContent.includes('550')); + assert.equal(await page.locator('#trade-sell').isDisabled(), true); + await page.fill('#trade-qty', '2'); + assert.equal(await page.locator('#trade-sell').isEnabled(), true); + await page.fill('#trade-qty', '200'); + assert.equal(await page.locator('#trade-buy').isDisabled(), true); +}); + +test('auto-trade run now decides on the qualifying $1B+ gainer and places the order', async () => { + let order; + const analysis = result('BIGCO'); analysis.actionable_signal = 'BUY'; + await page.route('**/api/paper/account', route => route.fulfill({json: accountData()})); + await page.route('**/api/paper/movers', route => route.fulfill({json: {pick: {symbol: 'BIGCO', price: 220, change_percent: 3.2, market_cap: 3.4e12}, considered: [], minimum_cap: 1e9}})); + await page.route('**/api/analyze', route => route.fulfill({json: analysis})); + await page.route('**/api/paper/order', route => { order = route.request().postDataJSON(); return route.fulfill({json: {symbol: 'BIGCO', side: 'BUY', quantity: 17, order_id: 'o2', status: 'accepted', filled_quantity: 0, filled_avg_price: null}}); }); + await openView('portfolio-panel'); + await page.waitForFunction(() => !document.getElementById('account-content').hidden); + await page.locator('#auto-toggle').check(); + await page.waitForFunction(() => document.getElementById('auto-log').children.length > 0); + assert.deepEqual(order, {symbol: 'BIGCO', side: 'BUY', quantity: 17}); + const entry = await page.locator('#auto-log li').first().innerText(); + assert.match(entry, /BIGCO/); + assert.match(entry, /3\.40T/); + assert.match(entry, /decision: buy 17\.00 shares · order accepted/); + assert.equal(await page.evaluate(() => localStorage.getItem('fasttrade-auto')), 'on'); +}); + +test('auto-trade records a wait entry when no $1B+ gainer qualifies', async () => { + let analysisCalls = 0; + await page.route('**/api/paper/account', route => route.fulfill({json: accountData()})); + await page.route('**/api/paper/movers', route => route.fulfill({json: {pick: null, considered: [{symbol: 'SMALL', market_cap: null}], minimum_cap: 1e9}})); + await page.route('**/api/analyze', route => { analysisCalls += 1; return route.fulfill({json: result()}); }); + await openView('portfolio-panel'); + await page.waitForFunction(() => !document.getElementById('account-content').hidden); + await page.locator('#auto-toggle').check(); + await page.waitForFunction(() => document.getElementById('auto-log').children.length > 0); + assert.match(await page.locator('#auto-log li').first().innerText(), /No gainer with a \$1B\+ cap today \(1 candidates checked\)/); + assert.equal(analysisCalls, 0); +}); + +test('equity history renders snapshots with a keyboard-inspectable readout', async () => { + const points = [ + {time: '2026-01-02T15:00:00Z', equity: 25000, cash: 20000, value: 5000}, + {time: '2026-01-02T16:00:00Z', equity: 25500, cash: 20000, value: 5500}, + {time: '2026-01-02T17:00:00Z', equity: 26000, cash: 20000, value: 6000}, + ]; + await page.evaluate(data => localStorage.setItem('fasttrade-equity', JSON.stringify(data)), points); + await page.route('**/api/paper/account', route => route.fulfill({status: 503, json: {error: 'Alpaca credentials are missing'}})); + await page.reload(); + await openView('portfolio-panel'); + await page.waitForFunction(() => document.getElementById('equity-empty').hidden); + assert.equal(await page.locator('#equity-readout').isHidden(), false); + assert.match(await page.locator('#snapshot-equity').innerText(), /26,000/); + assert.match(await page.locator('#snapshot-time').innerText(), /02 Jan 2026, 17:00/); + await page.locator('#equity-chart').focus(); + await page.keyboard.press('ArrowLeft'); + assert.match(await page.locator('#snapshot-equity').innerText(), /25,500/); + assert.match(await page.locator('#snapshot-change').innerText(), /\+500\.00 since first snapshot/); +});