-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
519 lines (466 loc) · 24.9 KB
/
server.js
File metadata and controls
519 lines (466 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json());
const WALLET_ADDRESS = process.env.WALLET_ADDRESS;
const PORT = process.env.PORT || 3000;
const BASE_URL = process.env.BASE_URL || 'https://hedgealphaoracle-production.up.railway.app';
const CRYPTO_ASSETS = [
'BTC','ETH','SOL','BNB','XRP','ADA','AVAX','DOGE','DOT','MATIC',
'LINK','UNI','LTC','ATOM','BCH','SHIB','TRX','XMR','USDT','USDC'
];
const STOCK_ASSETS = [
'AAPL','MSFT','GOOGL','AMZN','NVDA','META','TSLA','BRK-B','V','JNJ',
'WMT','JPM','PG','MA','HD','DIS','BAC','ADBE','NFLX','CRM'
];
function symbolToId(symbol) {
const map = {
'BTC': 'bitcoin', 'ETH': 'ethereum', 'SOL': 'solana',
'BNB': 'binancecoin', 'XRP': 'ripple', 'ADA': 'cardano',
'AVAX': 'avalanche-2', 'DOGE': 'dogecoin', 'DOT': 'polkadot',
'MATIC': 'matic-network', 'LINK': 'chainlink', 'UNI': 'uniswap',
'LTC': 'litecoin', 'ATOM': 'cosmos', 'BCH': 'bitcoin-cash',
'SHIB': 'shiba-inu', 'TRX': 'tron', 'XMR': 'monero',
'USDT': 'tether', 'USDC': 'usd-coin'
};
return map[symbol.toUpperCase()] || symbol.toLowerCase();
}
function detectAssetType(symbol) {
const upper = symbol.toUpperCase();
if (CRYPTO_ASSETS.includes(upper)) return 'crypto';
if (STOCK_ASSETS.includes(upper)) return 'stock';
return 'unknown';
}
async function getCryptoPrice(symbol) {
try {
const fetch = (await import('node-fetch')).default;
const id = symbolToId(symbol);
const url = 'https://api.coingecko.com/api/v3/simple/price?ids=' + id + '&vs_currencies=usd&include_24hr_change=true&include_market_cap=true';
const res = await fetch(url);
const data = await res.json();
return data[id] || null;
} catch (e) { return null; }
}
async function getStockPrice(symbol) {
try {
const fetch = (await import('node-fetch')).default;
const url = 'https://finnhub.io/api/v1/quote?symbol=' + symbol + '&token=demo';
const res = await fetch(url);
const data = await res.json();
if (!data.c || data.c === 0) return null;
const change24h = ((data.c - data.pc) / data.pc) * 100;
return { usd: data.c, usd_24h_change: change24h, usd_market_cap: 0 };
} catch (e) { return null; }
}
async function getFearGreedIndex() {
try {
const fetch = (await import('node-fetch')).default;
const res = await fetch('https://api.alternative.me/fng/?limit=1');
const data = await res.json();
if (data.data && data.data[0]) return data.data[0];
return null;
} catch (e) { return null; }
}
function generateSignal(change24h) {
if (change24h > 5) return { direction: 'STRONG LONG', sentiment: 85 };
if (change24h > 2) return { direction: 'LONG', sentiment: 72 };
if (change24h > 0) return { direction: 'NEUTRAL/LONG', sentiment: 58 };
if (change24h > -2) return { direction: 'NEUTRAL/SHORT', sentiment: 42 };
if (change24h > -5) return { direction: 'SHORT', sentiment: 28 };
return { direction: 'STRONG SHORT', sentiment: 15 };
}
// ─────────────────────────────────────────────
// PAYMENT MIDDLEWARE FACTORY
// NOW ACCEPTS: Base Mainnet + Monad Testnet + Hedera Mainnet + Algorand Mainnet
// $0.01 = 10000 | $0.02 = 20000 | $0.05 = 50000
// ─────────────────────────────────────────────
const HEDERA_WALLET = '0x00000000000000000000000000000000008cd721'; // Hedera 0.0.9230113 (Tallytrades1)
const ALGORAND_WALLET = '5DWBO7N5KU3PXQHXLKDCEALRI4TEOLJG3KTBADTQ734TKZRWMFOA25VLKQ';
function requirePayment(amountMicro, description, exampleInput, exampleOutput) {
return function(req, res, next) {
const paymentSig = req.headers['x-payment-signature'] || req.query.paymentSig;
if (paymentSig) return next();
return res.status(402).json({
x402Version: 2,
error: 'X-PAYMENT-REQUIRED',
accepts: [
{
scheme: 'exact',
network: 'eip155:8453',
asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
payTo: WALLET_ADDRESS,
amount: String(amountMicro),
maxTimeoutSeconds: 60
},
{
scheme: 'exact',
network: 'eip155:10143',
asset: '0x534b2f3A21130d7a60830c2Df862319e593943A3',
payTo: WALLET_ADDRESS,
amount: String(amountMicro),
maxTimeoutSeconds: 60,
extra: { name: 'USDC', version: '2', facilitator: 'https://x402-facilitator.molandak.org' }
},
{
scheme: 'exact',
network: 'eip155:295',
asset: '0x000000000000000000000000000000000006f89a',
payTo: HEDERA_WALLET,
amount: String(amountMicro),
maxTimeoutSeconds: 60,
extra: { name: 'USDC', version: '1', facilitator: 'https://x402.blockydevs.com' }
},
{
scheme: 'exact',
network: 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k',
asset: '31566704',
payTo: ALGORAND_WALLET,
amount: String(amountMicro),
maxTimeoutSeconds: 60,
extra: { name: 'USDC', version: '1', facilitator: 'https://facilitator.goplausible.xyz' }
}
],
resource: {
url: BASE_URL + req.path,
description: description,
mimeType: 'application/json'
},
extensions: {
bazaar: {
info: { input: exampleInput, output: exampleOutput }
}
}
});
};
}
const DISCLAIMER = '\n\nNOT FINANCIAL ADVICE. For informational purposes only.';
// ─────────────────────────────────────────────
// DISCOVERY ENDPOINTS
// ─────────────────────────────────────────────
app.get('/.well-known/x402', (req, res) => {
res.json({
version: 1,
resources: [
BASE_URL + '/sentiment/BTC',
BASE_URL + '/alpha/BTC',
BASE_URL + '/premium/BTC',
BASE_URL + '/market/fear-greed',
BASE_URL + '/market/whale-alert/BTC',
BASE_URL + '/portfolio/risk-score'
],
instructions: '# HedgeAlphaOracle v4.2\n\nReal-time crypto & stock trading signals + market intelligence for AI agents.\n\n## Endpoints\n- /sentiment/{asset} — Sentiment score $0.01\n- /alpha/{asset} — Entry/target/stop loss $0.02\n- /premium/{asset} — Full thesis + risk $0.05\n- /market/fear-greed — Fear & Greed index $0.01\n- /market/whale-alert/{asset} — Large move detection $0.02\n- /portfolio/risk-score — Multi-asset risk $0.02\n\n## Networks\nBase Mainnet (eip155:8453) | Monad Testnet (eip155:10143) | Hedera Mainnet (eip155:295) | Algorand Mainnet\n\n## Provider\nNurse2Web3 — https://nurse2web3.com'
});
});
app.get('/x402/discovery', (req, res) => {
res.json({
x402Version: 2,
name: 'HedgeAlphaOracle',
version: '4.2',
description: 'Real-time crypto & stock signals + market intelligence for AI agents. Accepts payments on Base, Monad, Hedera, and Algorand.',
provider: 'Nurse2Web3',
url: BASE_URL,
discoverable: true,
category: 'financial-data',
tags: ['crypto', 'stocks', 'trading-signals', 'sentiment', 'fear-greed', 'whale-alert', 'portfolio', 'defi', 'finance', 'monad', 'base', 'hedera', 'algorand', 'hbar'],
networks: ['base-mainnet', 'monad-testnet', 'hedera-mainnet', 'algorand-mainnet'],
endpoints: [
{ path: '/sentiment/{asset}', price: '$0.01', description: 'Sentiment score for any crypto or stock' },
{ path: '/alpha/{asset}', price: '$0.02', description: 'Entry zone, target, stop loss signals' },
{ path: '/premium/{asset}', price: '$0.05', description: 'Full thesis with risk assessment' },
{ path: '/market/fear-greed', price: '$0.01', description: 'Bitcoin Fear & Greed Index with market context' },
{ path: '/market/whale-alert/{asset}', price: '$0.02', description: 'Detect large price moves and unusual activity' },
{ path: '/portfolio/risk-score', price: '$0.02', description: 'Risk score for a portfolio of assets' }
],
supportedAssets: { crypto: CRYPTO_ASSETS, stocks: STOCK_ASSETS },
contact: { twitter: 'https://twitter.com/nurse2web3', website: 'https://nurse2web3.com' }
});
});
// ─────────────────────────────────────────────
// ROOT + HEALTH
// ─────────────────────────────────────────────
app.get('/', (req, res) => {
res.json({
api: 'HedgeAlphaOracle',
version: '4.2',
description: 'Real-time crypto & stock signals + market intelligence for AI agents',
endpoints: {
'/sentiment/:asset': 'Sentiment score — $0.01',
'/alpha/:asset': 'Entry, target, stop loss — $0.02',
'/premium/:asset': 'Full thesis + risk — $0.05',
'/market/fear-greed': 'Fear & Greed Index — $0.01',
'/market/whale-alert/:asset': 'Whale / large move alert — $0.02',
'/portfolio/risk-score': 'Portfolio risk score — $0.02',
'/health': 'Health check'
},
networks: { base: 'eip155:8453 (mainnet)', monad: 'eip155:10143 (testnet)', hedera: 'eip155:295 (mainnet)', algorand: 'algorand mainnet' },
wallet: WALLET_ADDRESS
});
});
app.get('/health', (req, res) => {
res.json({
status: 'OK', service: 'HedgeAlphaOracle', version: '4.2',
wallet: WALLET_ADDRESS, x402: 'enabled', bazaar: 'discoverable',
networks: {
base: 'eip155:8453 (mainnet) — active',
monad: 'eip155:10143 (testnet) — active',
hedera: 'eip155:295 (mainnet) — active',
algorand: 'algorand (mainnet) — active'
},
pricing: { sentiment: '$0.01', alpha: '$0.02', premium: '$0.05', fearGreed: '$0.01', whaleAlert: '$0.02', portfolioRisk: '$0.02' }
});
});
// ─────────────────────────────────────────────
// ENDPOINT 1: /sentiment/:asset — $0.01
// ─────────────────────────────────────────────
app.get('/sentiment/:asset',
requirePayment(10000,
'Sentiment score for any crypto or stock. Bullish/bearish direction with score out of 100.',
{ asset: 'BTC' },
{ success: true, asset: 'BTC', sentimentScore: 72, direction: 'LONG', price: 67432, change24h: 2.34 }
),
async (req, res) => {
const asset = req.params.asset.toUpperCase();
const assetType = detectAssetType(asset);
if (assetType === 'unknown') return res.status(404).json({ success: false, error: asset + ' not supported.' });
const priceData = assetType === 'crypto' ? await getCryptoPrice(asset) : await getStockPrice(asset);
if (!priceData) return res.status(404).json({ success: false, error: 'Could not fetch price for ' + asset });
const change24h = priceData.usd_24h_change || 0;
const signal = generateSignal(change24h);
res.json({
success: true, asset, assetType,
sentimentScore: signal.sentiment,
direction: signal.direction,
price: priceData.usd,
change24h: parseFloat(change24h.toFixed(2)),
summary: 'SENTIMENT [' + asset + '] Score: ' + signal.sentiment + '/100 | ' + signal.direction + ' | Price: $' + priceData.usd.toLocaleString() + ' (' + change24h.toFixed(2) + '% 24h)' + DISCLAIMER
});
}
);
// ─────────────────────────────────────────────
// ENDPOINT 2: /alpha/:asset — $0.02
// ─────────────────────────────────────────────
app.get('/alpha/:asset',
requirePayment(20000,
'Actionable alpha signal with entry zone, price target, and stop loss for any crypto or stock.',
{ asset: 'ETH' },
{ success: true, asset: 'ETH', direction: 'LONG', entryLow: 3200, entryHigh: 3280, target: 3520, stopLoss: 3040 }
),
async (req, res) => {
const asset = req.params.asset.toUpperCase();
const assetType = detectAssetType(asset);
if (assetType === 'unknown') return res.status(404).json({ success: false, error: asset + ' not supported.' });
const priceData = assetType === 'crypto' ? await getCryptoPrice(asset) : await getStockPrice(asset);
if (!priceData) return res.status(404).json({ success: false, error: 'Could not fetch price for ' + asset });
const price = priceData.usd;
const change24h = priceData.usd_24h_change || 0;
const signal = generateSignal(change24h);
const entryLow = parseFloat((price * 0.98).toFixed(2));
const entryHigh = parseFloat((price * 1.01).toFixed(2));
const target = parseFloat((price * 1.10).toFixed(2));
const stopLoss = parseFloat((price * 0.95).toFixed(2));
res.json({
success: true, asset, assetType,
direction: signal.direction,
sentimentScore: signal.sentiment,
price, change24h: parseFloat(change24h.toFixed(2)),
entryLow, entryHigh, target, stopLoss,
riskReward: '2:1',
summary: 'ALPHA [' + asset + '] ' + signal.direction + ' | Entry $' + entryLow + '-$' + entryHigh + ' | Target $' + target + ' | Stop $' + stopLoss + DISCLAIMER
});
}
);
// ─────────────────────────────────────────────
// ENDPOINT 3: /premium/:asset — $0.05
// ─────────────────────────────────────────────
app.get('/premium/:asset',
requirePayment(50000,
'Full hedge-fund style thesis with risk assessment, position sizing, and market context for any crypto or stock.',
{ asset: 'NVDA' },
{ success: true, asset: 'NVDA', direction: 'LONG', thesis: 'Bullish momentum...', riskLevel: 'MEDIUM', positionSize: '3%' }
),
async (req, res) => {
const asset = req.params.asset.toUpperCase();
const assetType = detectAssetType(asset);
if (assetType === 'unknown') return res.status(404).json({ success: false, error: asset + ' not supported.' });
const priceData = assetType === 'crypto' ? await getCryptoPrice(asset) : await getStockPrice(asset);
if (!priceData) return res.status(404).json({ success: false, error: 'Could not fetch price for ' + asset });
const price = priceData.usd;
const change24h = priceData.usd_24h_change || 0;
const marketCap = priceData.usd_market_cap || 0;
const signal = generateSignal(change24h);
const riskLevel = Math.abs(change24h) > 5 ? 'HIGH' : Math.abs(change24h) > 2 ? 'MEDIUM' : 'LOW';
res.json({
success: true, asset, assetType,
direction: signal.direction,
sentimentScore: signal.sentiment,
price, change24h: parseFloat(change24h.toFixed(2)),
marketCapB: marketCap > 0 ? parseFloat((marketCap / 1e9).toFixed(2)) : null,
entryLow: parseFloat((price * 0.98).toFixed(2)),
entryHigh: parseFloat((price * 1.01).toFixed(2)),
target: parseFloat((price * 1.10).toFixed(2)),
stopLoss: parseFloat((price * 0.95).toFixed(2)),
riskLevel,
positionSize: riskLevel === 'HIGH' ? '1-2%' : riskLevel === 'MEDIUM' ? '2-4%' : '3-5%',
riskReward: '2:1',
thesis: signal.direction.includes('LONG')
? asset + ' showing bullish momentum with ' + change24h.toFixed(2) + '% 24h move. Sentiment at ' + signal.sentiment + '/100. Key support holds above stop loss zone.'
: asset + ' showing bearish pressure with ' + change24h.toFixed(2) + '% 24h move. Sentiment at ' + signal.sentiment + '/100. Resistance likely to cap any bounces.',
summary: 'PREMIUM [' + asset + '] ' + signal.direction + ' | Risk: ' + riskLevel + ' | Score: ' + signal.sentiment + '/100' + DISCLAIMER
});
}
);
// ─────────────────────────────────────────────
// ENDPOINT 4: /market/fear-greed — $0.01
// ─────────────────────────────────────────────
app.get('/market/fear-greed',
requirePayment(10000,
'Bitcoin Fear & Greed Index with market sentiment context and trading implications.',
{},
{ success: true, value: 72, classification: 'Greed', signal: 'Market is greedy — consider taking profits or waiting for pullback' }
),
async (req, res) => {
const fng = await getFearGreedIndex();
const value = fng ? parseInt(fng.value) : 50;
const classification = fng ? fng.value_classification : 'Neutral';
let signal, color;
if (value >= 80) { signal = 'Extreme Greed — high risk, consider taking profits'; color = 'RED'; }
else if (value >= 60) { signal = 'Greed — market optimistic, watch for reversals'; color = 'ORANGE'; }
else if (value >= 40) { signal = 'Neutral — no strong directional bias'; color = 'YELLOW'; }
else if (value >= 20) { signal = 'Fear — potential buying opportunity forming'; color = 'LIGHTGREEN'; }
else { signal = 'Extreme Fear — historically strong buy zone'; color = 'GREEN'; }
res.json({
success: true,
fearGreedIndex: value,
classification,
signal,
color,
tradingImplication: value > 75
? 'Market extremely greedy. Historically a contrarian sell signal. Reduce position sizes.'
: value < 25
? 'Market in extreme fear. Historically a contrarian buy signal. Consider scaling in.'
: 'Market in neutral/moderate territory. Follow individual asset signals.',
lastUpdated: fng ? fng.timestamp : new Date().toISOString(),
summary: 'FEAR & GREED INDEX: ' + value + '/100 — ' + classification + ' | ' + signal + DISCLAIMER
});
}
);
// ─────────────────────────────────────────────
// ENDPOINT 5: /market/whale-alert/:asset — $0.02
// ─────────────────────────────────────────────
app.get('/market/whale-alert/:asset',
requirePayment(20000,
'Detect large price moves, unusual volume, and whale-level activity for any crypto or stock.',
{ asset: 'BTC' },
{ success: true, asset: 'BTC', whaleAlert: true, alertLevel: 'HIGH', unusualVolume: true, priceImpact: 'SIGNIFICANT' }
),
async (req, res) => {
const asset = req.params.asset.toUpperCase();
const assetType = detectAssetType(asset);
if (assetType === 'unknown') return res.status(404).json({ success: false, error: asset + ' not supported.' });
const priceData = assetType === 'crypto' ? await getCryptoPrice(asset) : await getStockPrice(asset);
if (!priceData) return res.status(404).json({ success: false, error: 'Could not fetch price for ' + asset });
const price = priceData.usd;
const change24h = priceData.usd_24h_change || 0;
const absChange = Math.abs(change24h);
const whaleAlert = absChange > 5;
const alertLevel = absChange > 10 ? 'CRITICAL' : absChange > 5 ? 'HIGH' : absChange > 3 ? 'MEDIUM' : 'LOW';
const priceImpact = absChange > 8 ? 'EXTREME' : absChange > 5 ? 'SIGNIFICANT' : absChange > 2 ? 'MODERATE' : 'NORMAL';
const direction = change24h > 0 ? 'UPWARD' : 'DOWNWARD';
res.json({
success: true, asset, assetType,
price, change24h: parseFloat(change24h.toFixed(2)),
whaleAlert, alertLevel, priceImpact,
moveDirection: direction,
unusualActivity: absChange > 3,
interpretation: whaleAlert
? 'WHALE ALERT: ' + asset + ' has moved ' + change24h.toFixed(2) + '% in 24h. Large ' + direction.toLowerCase() + ' pressure detected. Monitor closely for continuation or reversal.'
: asset + ' showing normal price activity. No unusual whale movement detected at this time.',
recommendation: alertLevel === 'CRITICAL' || alertLevel === 'HIGH'
? 'High volatility detected. Reduce position size. Set tight stop losses.'
: 'Normal market conditions. Standard position sizing applies.',
summary: 'WHALE ALERT [' + asset + '] Level: ' + alertLevel + ' | Move: ' + change24h.toFixed(2) + '% | Impact: ' + priceImpact + DISCLAIMER
});
}
);
// ─────────────────────────────────────────────
// ENDPOINT 6: /portfolio/risk-score — $0.02
// ─────────────────────────────────────────────
app.get('/portfolio/risk-score',
requirePayment(20000,
'Analyze portfolio risk across multiple crypto and stock assets. Pass assets as comma-separated query param.',
{ assets: 'BTC,ETH,AAPL' },
{ success: true, overallRisk: 'MEDIUM', riskScore: 58, assets: 3, recommendation: 'Diversified portfolio with moderate risk.' }
),
async (req, res) => {
const assetsParam = req.query.assets || 'BTC,ETH,SOL';
const assetList = assetsParam.split(',').map(a => a.trim().toUpperCase()).slice(0, 10);
const results = [];
let totalRisk = 0;
for (const asset of assetList) {
const assetType = detectAssetType(asset);
if (assetType === 'unknown') { results.push({ asset, error: 'not supported' }); continue; }
const priceData = assetType === 'crypto' ? await getCryptoPrice(asset) : await getStockPrice(asset);
if (!priceData) { results.push({ asset, error: 'price unavailable' }); continue; }
const change24h = priceData.usd_24h_change || 0;
const absChange = Math.abs(change24h);
const riskScore = Math.min(100, Math.round(absChange * 8 + 20));
totalRisk += riskScore;
results.push({
asset, assetType,
price: priceData.usd,
change24h: parseFloat(change24h.toFixed(2)),
riskScore,
riskLevel: riskScore > 70 ? 'HIGH' : riskScore > 40 ? 'MEDIUM' : 'LOW'
});
}
const validResults = results.filter(r => !r.error);
const avgRisk = validResults.length > 0 ? Math.round(totalRisk / validResults.length) : 50;
const overallRisk = avgRisk > 70 ? 'HIGH' : avgRisk > 40 ? 'MEDIUM' : 'LOW';
const highRiskAssets = validResults.filter(r => r.riskLevel === 'HIGH').map(r => r.asset);
res.json({
success: true,
overallRisk,
riskScore: avgRisk,
assetsAnalyzed: validResults.length,
assets: results,
highRiskAssets,
recommendation: overallRisk === 'HIGH'
? 'High portfolio risk detected. Consider reducing exposure to: ' + (highRiskAssets.join(', ') || 'volatile assets') + '. Use tighter stop losses.'
: overallRisk === 'MEDIUM'
? 'Moderate portfolio risk. Standard position sizing recommended. Monitor high-volatility assets closely.'
: 'Low portfolio risk. Good diversification detected. Standard risk management applies.',
summary: 'PORTFOLIO RISK: ' + overallRisk + ' (' + avgRisk + '/100) across ' + validResults.length + ' assets' + DISCLAIMER
});
}
);
// ─────────────────────────────────────────────
// LEGACY ROUTE
// ─────────────────────────────────────────────
app.get('/signal/:asset',
requirePayment(10000, 'Legacy signal endpoint — use /sentiment/:asset, /alpha/:asset, or /premium/:asset for best results.', { asset: 'BTC', tier: 'sentiment' }, {}),
async (req, res) => {
const asset = req.params.asset.toUpperCase();
const tier = req.query.tier || 'sentiment';
const assetType = detectAssetType(asset);
if (assetType === 'unknown') return res.status(404).json({ success: false, error: asset + ' not supported.' });
const priceData = assetType === 'crypto' ? await getCryptoPrice(asset) : await getStockPrice(asset);
if (!priceData) return res.status(404).json({ success: false, error: 'Could not fetch price for ' + asset });
const price = priceData.usd;
const change24h = priceData.usd_24h_change || 0;
const signal = generateSignal(change24h);
res.json({
success: true, asset, assetType, tier,
sentimentScore: signal.sentiment, direction: signal.direction,
price, change24h: parseFloat(change24h.toFixed(2)),
note: 'Use /sentiment/, /alpha/, or /premium/ endpoints for dedicated signals at lower prices.',
summary: signal.direction + ' | Score: ' + signal.sentiment + '/100 | $' + price.toLocaleString() + DISCLAIMER
});
}
);
app.listen(PORT, function() {
console.log('HedgeAlphaOracle v4.2 running on port ' + PORT);
console.log('Networks: Base (eip155:8453) + Monad (eip155:10143) + Hedera (eip155:295) + Algorand');
console.log('6 endpoints: sentiment $0.01 | alpha $0.02 | premium $0.05');
console.log('fear-greed $0.01 | whale-alert $0.02 | portfolio-risk $0.02');
console.log('x402 payments on Base + Monad + Hedera + Algorand | Bazaar discoverable');
});