Spaces:
Running
Running
Optimize Yahoo Finance requests: Reduced BATCH_SIZE to 5 and added 429 retry logic
Browse files- lib/munger-engine.ts +20 -4
lib/munger-engine.ts
CHANGED
|
@@ -11,7 +11,7 @@ const yahooFinance = new (YahooFinance as any)({
|
|
| 11 |
});
|
| 12 |
|
| 13 |
// Constants
|
| 14 |
-
const BATCH_SIZE =
|
| 15 |
|
| 16 |
// Config for Advanced Engine
|
| 17 |
const RISK_CONFIG = {
|
|
@@ -23,6 +23,20 @@ const RISK_CONFIG = {
|
|
| 23 |
entryLimitBufferBps: 75.0
|
| 24 |
};
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
export class MungerEngine {
|
| 27 |
|
| 28 |
/**
|
|
@@ -47,9 +61,9 @@ export class MungerEngine {
|
|
| 47 |
// Fetch chart data
|
| 48 |
let history;
|
| 49 |
try {
|
| 50 |
-
history = await yahooFinance.chart(symbol, queryOptions);
|
| 51 |
} catch (e) {
|
| 52 |
-
console.warn(`Failed to fetch chart for ${symbol}`);
|
| 53 |
return null;
|
| 54 |
}
|
| 55 |
|
|
@@ -72,7 +86,9 @@ export class MungerEngine {
|
|
| 72 |
// Fetch fundamental data
|
| 73 |
let summary;
|
| 74 |
try {
|
| 75 |
-
summary = await yahooFinance.quoteSummary(symbol, {
|
|
|
|
|
|
|
| 76 |
} catch (e) {
|
| 77 |
console.warn(`Failed to fetch summary for ${symbol}: ${(e as Error).message}`);
|
| 78 |
return null;
|
|
|
|
| 11 |
});
|
| 12 |
|
| 13 |
// Constants
|
| 14 |
+
const BATCH_SIZE = 5; // Reduced from 50 to avoid 429 errors
|
| 15 |
|
| 16 |
// Config for Advanced Engine
|
| 17 |
const RISK_CONFIG = {
|
|
|
|
| 23 |
entryLimitBufferBps: 75.0
|
| 24 |
};
|
| 25 |
|
| 26 |
+
// Retry helper
|
| 27 |
+
async function withRetry<T>(fn: () => Promise<T>, retries = 3, delay = 2000): Promise<T> {
|
| 28 |
+
try {
|
| 29 |
+
return await fn();
|
| 30 |
+
} catch (e: any) {
|
| 31 |
+
if (retries > 0 && (e.message?.includes('429') || e.message?.includes('Too Many Requests'))) {
|
| 32 |
+
console.warn(`Hit 429, retrying in ${delay}ms... (${retries} left)`);
|
| 33 |
+
await new Promise(r => setTimeout(r, delay));
|
| 34 |
+
return withRetry(fn, retries - 1, delay * 2);
|
| 35 |
+
}
|
| 36 |
+
throw e;
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
export class MungerEngine {
|
| 41 |
|
| 42 |
/**
|
|
|
|
| 61 |
// Fetch chart data
|
| 62 |
let history;
|
| 63 |
try {
|
| 64 |
+
history = await withRetry(() => yahooFinance.chart(symbol, queryOptions));
|
| 65 |
} catch (e) {
|
| 66 |
+
console.warn(`Failed to fetch chart for ${symbol}: ${(e as Error).message}`);
|
| 67 |
return null;
|
| 68 |
}
|
| 69 |
|
|
|
|
| 86 |
// Fetch fundamental data
|
| 87 |
let summary;
|
| 88 |
try {
|
| 89 |
+
summary = await withRetry(() => yahooFinance.quoteSummary(symbol, {
|
| 90 |
+
modules: ['financialData', 'summaryDetail', 'price']
|
| 91 |
+
}));
|
| 92 |
} catch (e) {
|
| 93 |
console.warn(`Failed to fetch summary for ${symbol}: ${(e as Error).message}`);
|
| 94 |
return null;
|