Skip to content

Commit 649415a

Browse files
committed
Fix formatMarketCap and optimize historical data fetching
1 parent 3e6e8cf commit 649415a

1 file changed

Lines changed: 44 additions & 39 deletions

File tree

src/components/CustomPairsAnalysis.jsx

Lines changed: 44 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,15 @@ const COINGECKO_API_KEY = (() => {
8080
return key;
8181
})();
8282

83+
// Add formatMarketCap function at the top level
84+
const formatMarketCap = (value) => {
85+
if (!value && value !== 0) return 'N/A';
86+
if (value >= 1e12) return `$${(value / 1e12).toFixed(2)}T`;
87+
if (value >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;
88+
if (value >= 1e6) return `$${(value / 1e6).toFixed(2)}M`;
89+
return `$${value.toFixed(2)}`;
90+
};
91+
8392
export default function CustomPairsAnalysis({ open, onClose }) {
8493
const [token1, setToken1] = useState(null);
8594
const [token2, setToken2] = useState(null);
@@ -347,7 +356,7 @@ export default function CustomPairsAnalysis({ open, onClose }) {
347356
const previousData = { analysisData, tokenData };
348357

349358
try {
350-
// Fetch market data with all intervals
359+
// Fetch market data first
351360
const [info1, info2] = await Promise.all([
352361
fetchWithRetry(`${BASE_URL}/coins/${token1.id}`, {
353362
vs_currency: 'usd',
@@ -382,50 +391,27 @@ export default function CustomPairsAnalysis({ open, onClose }) {
382391
}
383392
});
384393

385-
// Validate and log market data
386-
const validateMarketData = (data, tokenSymbol) => {
387-
const marketData = data?.data?.market_data;
388-
if (!marketData) throw new Error('Market data not available.');
389-
390-
// Log raw market data for debugging
391-
console.log(`Raw market data for ${tokenSymbol}:`, marketData);
392-
393-
// Log price changes for debugging
394-
const priceChanges = {
395-
'24h': marketData.price_change_percentage_24h,
396-
'7d': marketData.price_change_percentage_7d,
397-
'30d': marketData.price_change_percentage_30d,
398-
'90d': marketData.price_change_percentage_90d,
399-
'1y': marketData.price_change_percentage_1y
400-
};
401-
402-
console.log(`Price changes for ${tokenSymbol}:`, priceChanges);
403-
404-
// Validate 90d data specifically
405-
if (priceChanges['90d'] === undefined || priceChanges['90d'] === null) {
406-
console.warn(`90d price change missing for ${tokenSymbol}, calculating from historical data...`);
407-
return marketData;
408-
}
409-
410-
return marketData;
411-
};
394+
const marketData1 = info1?.data?.market_data;
395+
const marketData2 = info2?.data?.market_data;
412396

413-
const marketData1 = validateMarketData(info1, token1.symbol);
414-
const marketData2 = validateMarketData(info2, token2.symbol);
397+
if (!marketData1 || !marketData2) {
398+
throw new Error('Market data not available.');
399+
}
415400

416401
// Add delay before fetching historical data
417402
await sleep(2000);
418403

419-
// Fetch historical data for 90d calculation if needed
404+
// Fetch historical data once with max days needed
405+
const daysNeeded = Math.max(selectedTimeframe, 90); // Use 90 days for both correlation and price change
420406
const [data1, data2] = await Promise.all([
421407
fetchWithRetry(`${BASE_URL}/coins/${token1.id}/market_chart`, {
422408
vs_currency: 'usd',
423-
days: Math.max(selectedTimeframe, marketData1.price_change_percentage_90d ? 0 : 90),
409+
days: daysNeeded,
424410
interval: 'daily'
425411
}, MAX_RETRIES, API_DELAY, true),
426412
fetchWithRetry(`${BASE_URL}/coins/${token2.id}/market_chart`, {
427413
vs_currency: 'usd',
428-
days: Math.max(selectedTimeframe, marketData2.price_change_percentage_90d ? 0 : 90),
414+
days: daysNeeded,
429415
interval: 'daily'
430416
}, MAX_RETRIES, API_DELAY, true)
431417
]).catch(error => {
@@ -439,15 +425,34 @@ export default function CustomPairsAnalysis({ open, onClose }) {
439425
}
440426
});
441427

442-
// Calculate 90d change if missing from market data
428+
// Calculate 90d change from historical data
443429
const calculate90dChange = (prices) => {
444-
if (prices.length < 90) return null;
430+
if (!Array.isArray(prices) || prices.length < 90) return null;
445431
const startPrice = prices[0][1];
446-
const endPrice = prices[prices.length - 1][1];
432+
const endPrice = prices[89][1]; // Use exactly 90 days
447433
return ((endPrice - startPrice) / startPrice) * 100;
448434
};
449435

450-
// Store token data with calculated 90d changes if needed
436+
// Extract prices and calculate daily changes for correlation
437+
const prices1 = data1.data.prices.slice(-selectedTimeframe);
438+
const prices2 = data2.data.prices.slice(-selectedTimeframe);
439+
440+
const changes1 = prices1.map((price, i) =>
441+
i === 0 ? 0 : ((price[1] - prices1[i-1][1]) / prices1[i-1][1]) * 100
442+
);
443+
const changes2 = prices2.map((price, i) =>
444+
i === 0 ? 0 : ((price[1] - prices2[i-1][1]) / prices2[i-1][1]) * 100
445+
);
446+
447+
// Calculate correlation
448+
const correlation = calculateCorrelation(changes1, changes2);
449+
if (isNaN(correlation)) {
450+
throw new Error('Unable to calculate correlation. Please try different tokens.');
451+
}
452+
453+
const dates = prices1.map(p => new Date(p[0]).toLocaleDateString());
454+
455+
// Store token data with calculated 90d changes
451456
const newTokenData = {
452457
token1: {
453458
price: marketData1.current_price?.usd ?? 0,
@@ -456,7 +461,7 @@ export default function CustomPairsAnalysis({ open, onClose }) {
456461
priceChange24h: marketData1.price_change_percentage_24h ?? null,
457462
priceChange7d: marketData1.price_change_percentage_7d ?? null,
458463
priceChange30d: marketData1.price_change_percentage_30d ?? null,
459-
priceChange90d: marketData1.price_change_percentage_90d ?? calculate90dChange(data1.data.prices),
464+
priceChange90d: calculate90dChange(data1.data.prices),
460465
priceChange1y: marketData1.price_change_percentage_1y ?? null,
461466
},
462467
token2: {
@@ -466,7 +471,7 @@ export default function CustomPairsAnalysis({ open, onClose }) {
466471
priceChange24h: marketData2.price_change_percentage_24h ?? null,
467472
priceChange7d: marketData2.price_change_percentage_7d ?? null,
468473
priceChange30d: marketData2.price_change_percentage_30d ?? null,
469-
priceChange90d: marketData2.price_change_percentage_90d ?? calculate90dChange(data2.data.prices),
474+
priceChange90d: calculate90dChange(data2.data.prices),
470475
priceChange1y: marketData2.price_change_percentage_1y ?? null,
471476
}
472477
};

0 commit comments

Comments
 (0)