Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion fasttrade/paper.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,17 @@ def last_price(symbol):
return {'symbol': symbol, 'price': price}


def market_clock():
"""Return whether the US market is open and when it next opens."""
data = _call(pooled_get, f'{PAPER_BASE}/v2/clock')
try:
is_open = data['is_open'] is True
next_open = str(data['next_open']) if data['next_open'] else None
except (KeyError, TypeError, AttributeError) as exc:
raise ValueError('Invalid Alpaca clock response') from exc
return {'is_open': is_open, 'next_open': next_open}


def submit_order(symbol, side, quantity):
"""Submit a paper market order; Alpaca fills it at the next available price."""
symbol = _symbol(symbol)
Expand All @@ -125,7 +136,13 @@ def submit_order(symbol, side, quantity):
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}
pending, next_open = False, None
try:
clock = market_clock()
pending, next_open = not clock['is_open'], clock['next_open']
except ValueError:
pass
return {'symbol': symbol, 'side': side, 'quantity': quantity, 'order_id': order_id, 'status': status, 'filled_quantity': filled_quantity, 'filled_avg_price': filled_avg_price, 'pending': pending, 'next_open': next_open}


def movers(limit=8, minimum_cap=MIN_MARKET_CAP):
Expand Down
18 changes: 16 additions & 2 deletions fasttrade/static/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -633,14 +633,24 @@ async function fetchTradePrice() {
}
renderTrade();
}
function pendingBadge(nextOpen) {
const badge = document.createElement('span');
badge.className = 'pending-badge';
badge.textContent = 'PENDING';
badge.title = nextOpen ? `Market is closed. The trade will perform when the market opens (${formatTime(nextOpen)}).` : 'Market is closed. The trade will perform when the market opens.';
return badge;
}
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');
setPortfolioStatus(order.pending
? `${side} order for ${number(qty)} ${symbol} accepted · it will perform when the market opens.`
: `${side} order for ${number(qty)} ${symbol} submitted · status ${order.status}${order.filled_avg_price ? ` · filled ${number(order.filled_avg_price)}` : ''}.`, 'good');
if (order.pending) $('portfolio-status').append(pendingBadge(order.next_open));
} catch (error) {
setPortfolioStatus(error.message, 'bad');
}
Expand Down Expand Up @@ -683,13 +693,15 @@ function renderAuto() {
const text = document.createElement('span');
text.textContent = `${formatTime(entry.time)} · ${entry.symbol || 'market'} · ${entry.detail}`;
row.append(badge, text);
if (entry.pending) row.append(pendingBadge(entry.next_open));
list.append(row);
}
}
async function autoTick(force = false) {
if (!auto.enabled || auto.running || (!force && document.hidden)) return;
auto.running = true;
renderAuto();
let pending = {};
try {
const movers = await jsonRequest('/api/paper/movers');
const pick = movers.pick;
Expand All @@ -708,9 +720,11 @@ async function autoTick(force = false) {
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}`;
if (order.pending) detail += ' · will perform when the market opens';
pending = {pending: order.pending, next_open: order.next_open};
}
}
autoNote({time: new Date().toISOString(), symbol: pick.symbol, action, detail});
autoNote({time: new Date().toISOString(), symbol: pick.symbol, action, detail, ...pending});
} catch (error) {
autoNote({time: new Date().toISOString(), symbol: '', action: 'ERROR', detail: error.message});
} finally {
Expand Down
1 change: 1 addition & 0 deletions fasttrade/static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,7 @@ body { background: #f2f5f8; }
.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; }
.pending-badge { flex: none; margin-left: 4px; padding: 2px 8px; border-radius: 5px; font: 700 10px var(--mono); letter-spacing: .03em; background: #fff8e8; color: #7b520d; border: 1px solid #e8d3a4; cursor: help; }
.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; }
Expand Down
25 changes: 24 additions & 1 deletion tests/test_paper.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,21 +58,44 @@ def get(url, **kwargs):

def test_submit_order_posts_market_order_and_reports_fill(monkeypatch):
posted = {}
urls = []
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))
def get(url, **kwargs):
urls.append(url)
return httpx.Response(200, json={'is_open': True, 'next_open': '2026-11-16T09:30:00-05:00'}, request=httpx.Request('GET', url))
monkeypatch.setattr(paper, 'pooled_post', post)
monkeypatch.setattr(paper, 'pooled_get', get)
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}
assert urls[-1].endswith('/v2/clock')
assert result == {'symbol': 'NVDA', 'side': 'BUY', 'quantity': 1.5, 'order_id': 'order-1', 'status': 'accepted', 'filled_quantity': 1.0, 'filled_avg_price': None, 'pending': False, 'next_open': '2026-11-16T09:30:00-05:00'}
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_flags_pending_when_market_is_closed(monkeypatch):
def post(url, **kwargs):
return httpx.Response(200, json={'id': 'order-2', 'status': 'accepted', 'filled_qty': '0', 'filled_avg_price': None}, request=httpx.Request('POST', url))
def get(url, **kwargs):
assert url.endswith('/v2/clock')
return httpx.Response(200, json={'is_open': False, 'next_open': '2026-11-16T09:30:00-05:00'}, request=httpx.Request('GET', url))
monkeypatch.setattr(paper, 'pooled_post', post)
monkeypatch.setattr(paper, 'pooled_get', get)
monkeypatch.setenv('ALPACA_API_KEY', 'key')
monkeypatch.setenv('ALPACA_SECRET_KEY', 'secret')
result = paper.submit_order('AAPL', 'BUY', 1)
assert result['pending'] is True and result['next_open'] == '2026-11-16T09:30:00-05:00'
monkeypatch.setattr(paper, 'pooled_get', lambda url, **kwargs: (_ for _ in ()).throw(httpx.ConnectError('clock unavailable')))
degraded = paper.submit_order('AAPL', 'BUY', 1)
assert degraded['pending'] is False and degraded['next_open'] is None


def test_submit_order_reports_rejection_reason(monkeypatch):
monkeypatch.setenv('ALPACA_API_KEY', 'key')
monkeypatch.setenv('ALPACA_SECRET_KEY', 'secret')
Expand Down
16 changes: 11 additions & 5 deletions tests/ui.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -972,7 +972,7 @@ 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 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, pending: true, next_open: '2026-11-16T09:30:00-05:00'}}); });
await openView('portfolio-panel');
await page.waitForFunction(() => !document.getElementById('account-content').hidden);
await page.fill('#trade-symbol', 'aapl');
Expand All @@ -981,9 +981,12 @@ test('manual trade submits an alpaca market order with the fetched price', async
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'));
await page.waitForFunction(() => document.getElementById('portfolio-status').textContent.includes('market opens'));
assert.deepEqual(order, {symbol: 'AAPL', side: 'BUY', quantity: 2});
assert.match(await page.locator('#portfolio-status').innerText(), /submitted · status accepted/);
assert.match(await page.locator('#portfolio-status').innerText(), /accepted · it will perform when the market opens/);
const badge = page.locator('#portfolio-status .pending-badge');
assert.equal(await badge.innerText(), 'PENDING');
assert.match(await badge.getAttribute('title'), /will perform when the market opens \(16 Nov 2026, 14:30 UTC\)/);
});

test('manual sell is limited to held shares and buy to buying power', async () => {
Expand All @@ -1007,7 +1010,7 @@ test('auto-trade run now decides on the qualifying $1B+ gainer and places the or
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 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, pending: true, next_open: '2026-11-16T09:30:00-05:00'}}); });
await openView('portfolio-panel');
await page.waitForFunction(() => !document.getElementById('account-content').hidden);
await page.locator('#auto-toggle').check();
Expand All @@ -1016,7 +1019,10 @@ test('auto-trade run now decides on the qualifying $1B+ gainer and places the or
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.match(entry, /decision: buy 17\.00 shares · order accepted · will perform when the market opens/);
const pending = page.locator('#auto-log li').first().locator('.pending-badge');
assert.equal(await pending.innerText(), 'PENDING');
assert.match(await pending.getAttribute('title'), /will perform when the market opens \(16 Nov 2026, 14:30 UTC\)/);
assert.equal(await page.evaluate(() => localStorage.getItem('fasttrade-auto')), 'on');
});

Expand Down
Loading