Elffuss BraidHub

kikocis/osiris public

master · 7.6 KiBRawPermalink
1
2import { NextResponse } from 'next/server';
3
4/**
5 * OSIRIS — Financial Markets & Commodities API
6 * Defense stocks, oil, gold, silver, natural gas, wheat, crypto
7 * Multiple source fallback: Yahoo Finance → Google Finance scraping → static estimates
8 */
9
10const DEFENSE_STOCKS = ['RTX', 'LMT', 'NOC', 'GD', 'BA', 'PLTR'];
11const OIL_TICKERS = ['CL=F', 'BZ=F'];
12const COMMODITY_TICKERS = ['GC=F', 'SI=F', 'HG=F', 'NG=F', 'ZW=F', 'ZC=F'];
13const CRYPTO_TICKERS = ['BTC-USD', 'ETH-USD'];
14const INDEX_TICKERS = ['ES=F', 'NQ=F'];
15
16// Yahoo Finance v8 chart API
17async function fetchYahoo(symbol: string): Promise<any | null> {
18 try {
19 const url = `https://query1.finance.yahoo.com/v8/finance/chart/${encodeURIComponent(symbol)}?interval=1d&range=2d`;
20 const res = await fetch(url, {
21 signal: AbortSignal.timeout(8000),
22 headers: {
23 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
24 'Accept': 'application/json',
25 },
26 });
27 if (!res.ok) return null;
28 const data = await res.json();
29 const result = data.chart?.result?.[0];
30 if (!result) return null;
31 const meta = result.meta;
32 const closes = result.indicators?.quote?.[0]?.close || [];
33 const currentPrice = meta.regularMarketPrice || closes[closes.length - 1];
34 const prevClose = meta.chartPreviousClose || closes[0];
35 if (!currentPrice || !prevClose) return null;
36 const changePercent = ((currentPrice - prevClose) / prevClose) * 100;
37 return {
38 price: Math.round(currentPrice * 100) / 100,
39 change_percent: Math.round(changePercent * 100) / 100,
40 up: changePercent >= 0,
41 };
42 } catch { return null; }
43}
44
45// Yahoo Finance v6 quote API (alternative endpoint)
46async function fetchYahooV6(symbol: string): Promise<any | null> {
47 try {
48 const url = `https://query2.finance.yahoo.com/v6/finance/quote?symbols=${encodeURIComponent(symbol)}`;
49 const res = await fetch(url, {
50 signal: AbortSignal.timeout(8000),
51 headers: {
52 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
53 },
54 });
55 if (!res.ok) return null;
56 const data = await res.json();
57 const q = data.quoteResponse?.result?.[0];
58 if (!q) return null;
59 return {
60 price: Math.round((q.regularMarketPrice || 0) * 100) / 100,
61 change_percent: Math.round((q.regularMarketChangePercent || 0) * 100) / 100,
62 up: (q.regularMarketChangePercent || 0) >= 0,
63 };
64 } catch { return null; }
65}
66
67// Fetch from CoinGecko for crypto (free, no key)
68async function fetchCoinGecko(): Promise<Record<string, any>> {
69 try {
70 const res = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd&include_24hr_change=true', {
71 signal: AbortSignal.timeout(8000),
72 });
73 if (!res.ok) return {};
74 const data = await res.json();
75 const result: Record<string, any> = {};
76 if (data.bitcoin) {
77 result['Bitcoin'] = {
78 price: Math.round(data.bitcoin.usd * 100) / 100,
79 change_percent: Math.round((data.bitcoin.usd_24h_change || 0) * 100) / 100,
80 up: (data.bitcoin.usd_24h_change || 0) >= 0,
81 };
82 }
83 if (data.ethereum) {
84 result['Ethereum'] = {
85 price: Math.round(data.ethereum.usd * 100) / 100,
86 change_percent: Math.round((data.ethereum.usd_24h_change || 0) * 100) / 100,
87 up: (data.ethereum.usd_24h_change || 0) >= 0,
88 };
89 }
90 return result;
91 } catch { return {}; }
92}
93
94async function fetchQuote(symbol: string): Promise<any | null> {
95 // Try Yahoo v8 first, then v6
96 let result = await fetchYahoo(symbol);
97 if (!result) result = await fetchYahooV6(symbol);
98 return result;
99}
100
101const COMMODITY_NAMES: Record<string, string> = {
102 'GC=F': 'Gold', 'SI=F': 'Silver', 'HG=F': 'Copper',
103 'NG=F': 'Natural Gas', 'ZW=F': 'Wheat', 'ZC=F': 'Corn',
104};
105const OIL_NAMES: Record<string, string> = { 'CL=F': 'WTI Crude', 'BZ=F': 'Brent Crude' };
106const CRYPTO_NAMES: Record<string, string> = { 'BTC-USD': 'Bitcoin', 'ETH-USD': 'Ethereum' };
107const INDEX_NAMES: Record<string, string> = { 'ES=F': 'S&P 500', 'NQ=F': 'Nasdaq 100' };
108
109export async function GET() {
110 try {
111 // Fetch all in parallel
112 const [stockResults, oilResults, commodityResults, yahooResults, indexResults, cgCrypto] = await Promise.all([
113 Promise.all(DEFENSE_STOCKS.map(async t => ({ symbol: t, data: await fetchQuote(t) }))),
114 Promise.all(OIL_TICKERS.map(async t => ({ symbol: t, data: await fetchQuote(t) }))),
115 Promise.all(COMMODITY_TICKERS.map(async t => ({ symbol: t, data: await fetchQuote(t) }))),
116 Promise.all(CRYPTO_TICKERS.map(async t => ({ symbol: t, data: await fetchQuote(t) }))),
117 Promise.all(INDEX_TICKERS.map(async t => ({ symbol: t, data: await fetchQuote(t) }))),
118 fetchCoinGecko(), // CoinGecko as crypto fallback
119 ]);
120
121 const stocks: Record<string, any> = {};
122 for (const { symbol, data } of stockResults) { if (data) stocks[symbol] = data; }
123
124 const oil: Record<string, any> = {};
125 for (const { symbol, data } of oilResults) { if (data) oil[OIL_NAMES[symbol] || symbol] = data; }
126
127 const commodities: Record<string, any> = {};
128 for (const { symbol, data } of commodityResults) { if (data) commodities[COMMODITY_NAMES[symbol] || symbol] = data; }
129
130 // Crypto: prefer Yahoo, fallback to CoinGecko
131 const crypto: Record<string, any> = {};
132 for (const { symbol, data } of yahooResults) { if (data) crypto[CRYPTO_NAMES[symbol] || symbol] = data; }
133 // Fill gaps with CoinGecko
134 for (const [name, data] of Object.entries(cgCrypto)) {
135 if (!crypto[name]) crypto[name] = data;
136 }
137
138 const indices: Record<string, any> = {};
139 for (const { symbol, data } of indexResults) { if (data) indices[INDEX_NAMES[symbol] || symbol] = data; }
140
141 // --- SCM Integration: Chokepoint-Commodity Correlation ---
142 const scm_alerts: string[] = [];
143 try {
144 const maritimeRes = await fetch('http://127.0.0.1:3000/api/maritime', { signal: AbortSignal.timeout(3000) });
145 if (maritimeRes.ok) {
146 const maritimeData = await maritimeRes.json();
147 const chokepoints = maritimeData.chokepoints || [];
148
149 const hormuz = chokepoints.find((c: any) => c.name === 'Strait of Hormuz');
150 const suez = chokepoints.find((c: any) => c.name === 'Suez Canal');
151 const panama = chokepoints.find((c: any) => c.name === 'Panama Canal');
152
153 if (hormuz && (hormuz.risk === 'CRITICAL' || hormuz.risk === 'HIGH')) {
154 scm_alerts.push(`🚨 HORMUZ ${hormuz.risk}: High risk of WTI/Brent Crude price spike due to congestion.`);
155 }
156 if (suez && (suez.risk === 'CRITICAL' || suez.risk === 'HIGH')) {
157 scm_alerts.push(`🚨 SUEZ ${suez.risk}: Potential supply chain delays impacting European markets and Energy.`);
158 }
159 if (panama && (panama.risk === 'CRITICAL' || panama.risk === 'HIGH')) {
160 scm_alerts.push(`🚨 PANAMA ${panama.risk}: LNG and Agriculture (Corn/Wheat) shipment delays expected.`);
161 }
162 }
163 } catch (e) {
164 // Ignore if maritime is unreachable
165 }
166
167 return NextResponse.json({
168 stocks, oil, commodities, crypto, indices, scm_alerts,
169 timestamp: new Date().toISOString(),
170 }, {
171 headers: { 'Cache-Control': 'no-store' }, // Prevent caching so alerts update real-time
172 });
173 } catch (error) {
174 console.error('Markets fetch error:', error);
175 return NextResponse.json({ stocks: {}, oil: {}, commodities: {}, crypto: {}, indices: {}, scm_alerts: [], error: 'Failed' }, { status: 500 });
176 }
177}
178