diff --git a/backend/src/services/apiServer.ts b/backend/src/services/apiServer.ts index 41b9ed6..e7fb248 100644 --- a/backend/src/services/apiServer.ts +++ b/backend/src/services/apiServer.ts @@ -151,7 +151,7 @@ interface AlpacaCredentials { secret: string; } -async function getUserAlpacaCredentials(userId: string): Promise { +async function getUserExecutionAlpacaCredentials(userId: string): Promise { const profile = await getCurrentUserProfile(userId); const key = String(config.PAPER_TRADING ? profile.ALPACA_API_KEY || '' : profile.REAL_ALPACA_API_KEY || '').trim(); const secret = String(config.PAPER_TRADING ? profile.ALPACA_SECRET_KEY || '' : profile.REAL_ALPACA_SECRET_KEY || '').trim(); @@ -167,6 +167,24 @@ async function getUserAlpacaCredentials(userId: string): Promise { + const profile = await getCurrentUserProfile(userId); + + const paperKey = String(profile.ALPACA_API_KEY || '').trim(); + const paperSecret = String(profile.ALPACA_SECRET_KEY || '').trim(); + if (paperKey && paperSecret) { + return { key: paperKey, secret: paperSecret }; + } + + const liveKey = String(profile.REAL_ALPACA_API_KEY || '').trim(); + const liveSecret = String(profile.REAL_ALPACA_SECRET_KEY || '').trim(); + if (liveKey && liveSecret) { + return { key: liveKey, secret: liveSecret }; + } + + throw new MissingServiceConfigError('User Alpaca credentials are not configured'); +} + interface TradeAuditEvent { event: string; userId?: string; @@ -2709,7 +2727,7 @@ RULES: const period = String(req.query.period || '1Y').trim(); if (!authUserId) return res.status(401).json({ error: 'Unauthorized' }); if (!symbol) return res.status(400).json({ error: 'symbol required' }); - const alpaca = await getUserAlpacaCredentials(authUserId); + const alpaca = await getUserMarketDataAlpacaCredentials(authUserId); const now = new Date(); let start = new Date(now); @@ -2796,7 +2814,7 @@ RULES: return res.status(401).json({ error: 'Unauthorized' }); } const limit = Math.max(1, Math.min(50, Number(req.query.limit) || 10)); - const alpaca = await getUserAlpacaCredentials(authUserId); + const alpaca = await getUserMarketDataAlpacaCredentials(authUserId); const qs = new URLSearchParams({ ...(symbols ? { symbols } : {}), limit: String(limit), @@ -2827,7 +2845,7 @@ RULES: if (!authUserId) { return res.status(401).json({ error: 'Unauthorized' }); } - const alpaca = await getUserAlpacaCredentials(authUserId); + const alpaca = await getUserMarketDataAlpacaCredentials(authUserId); const url = 'https://data.alpaca.markets/v2/stocks/snapshots?symbols=SPY,DIA,QQQ&feed=iex'; const r = await fetch(url, { headers: {