Editando Plataforma -2

<!DOCTYPE html>

<html lang="pt-BR">


<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Dados da Uniswap</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            margin: 20px;

        }


        table {

            width: 100%;

            border-collapse: collapse;

            margin-top: 20px;

        }


        th,

        td {

            border: 1px solid #ddd;

            padding: 8px;

            text-align: center;

        }


        th {

            background-color: #f2f2f2;

        }


        .loading {

            font-style: italic;

            color: gray;

        }


        .error {

            color: red;

        }

    </style>

</head>


<body>

    <h1>Dados da Uniswap</h1>

    <table id="uniswap-table">

        <thead>

            <tr>

                <th>Preço (USD)</th>

                <th>Preço (BRL)</th>

                <th>Capitalização de Mercado (USD)</th>

                <th>Volume em 24h (USD)</th>

                <th>Última Atualização</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td colspan="5" class="loading">Carregando dados da Uniswap...</td>

            </tr>

        </tbody>

    </table>


    <h2>Correlação entre UNI e Outras Moedas</h2>

    <table id="correlation-table">

        <thead>

            <tr>

                <th>Moeda</th>

                <th>Correlação com UNI</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td colspan="2" class="loading">Carregando dados de correlação...</td>

            </tr>

        </tbody>

    </table>


    <script>

        let uniswapDataCache = null;

        let lastFetchTime = 0;

        const CACHE_DURATION = 10 * 60 * 1000; // 10 minutos em milissegundos


        async function fetchUniswapData() {

            const currentTime = Date.now();

            

            if (uniswapDataCache && (currentTime - lastFetchTime < CACHE_DURATION)) {

                console.log("Usando dados do cache:", uniswapDataCache);

                return uniswapDataCache;

            }


            try {

                const url = "https://api.coingecko.com/api/v3/simple/price?ids=uniswap&vs_currencies=usd,brl&include_market_cap=true&include_24hr_vol=true&include_last_updated_at=true";

                console.log("Fetching Uniswap data from:", url);

                const response = await fetch(url);

                console.log("Response status:", response.status);


                if (!response.ok) throw new Error('Erro ao carregar dados da Uniswap: ' + response.status + ' ' + response.statusText);


                const data = await response.json();

                console.log("Uniswap data received:", data);

                

                if (data.uniswap) {

                    console.log("Detalhes dos dados da Uniswap:", data.uniswap); // Adicionando log detalhado

                    uniswapDataCache = data.uniswap;

                    lastFetchTime = currentTime;

                    return uniswapDataCache;

                } else {

                    throw new Error('Dados não encontrados na resposta da API.');

                }

                

            } catch (error) {

                console.error("Error fetching Uniswap data:", error);

                return null;

            }

        }


        async function updateUniswapTable() {

            const uniswapData = await fetchUniswapData();


            if (uniswapData) {

                const tableBody = document.querySelector('#uniswap-table tbody');

                tableBody.innerHTML = `

                    <tr>

                        <td>${uniswapData.usd}</td>

                        <td>${uniswapData.brl}</td>

                        <td>${uniswapData.usd_market_cap}</td>

                        <td>${uniswapData.usd_24h_vol}</td>

                        <td>${new Date(uniswapData.last_updated_at * 1000).toLocaleString('pt-BR')}</td>

                    </tr>

                `;

            } else {

                const tableBody = document.querySelector('#uniswap-table tbody');

                tableBody.innerHTML = `

                    <tr>

                        <td colspan="5" class="error">Erro ao carregar dados da Uniswap.</td>

                    </tr>

                `;

            }

        }


        async function fetchHistoricalData() {

            const coins = ['bitcoin', 'ethereum', 'tether', 'binancecoin', 'cardano', 'uniswap'];

            const historicalPrices = {};


            for (const coin of coins) {

                try {

                    const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart?vs_currency=usd&days=30`;

                    console.log(`Fetching historical data for ${coin} from:`, url);

                    const response = await fetch(url);

                    console.log("Response status for", coin, ":", response.status);


                    if (!response.ok) throw new Error(`Erro ao carregar dados de ${coin}: ${response.status} ${response.statusText}`);


                    const data = await response.json();

                    historicalPrices[coin] = data.prices.map(price => price[1]); // Preço em USD

                    console.log(`${coin} historical prices:`, historicalPrices[coin]);

                } catch (error) {

                    console.error(`Error fetching historical data for ${coin}:`, error);

                    historicalPrices[coin] = []; // Armazenar array vazio se houver erro

                }

            }


            return historicalPrices;

        }


        function calculateCorrelation(prices1, prices2) {

            const n = Math.min(prices1.length, prices2.length);

            if (n < 2) return 0; // Garantir que haja dados suficientes


            const mean1 = prices1.reduce((a, b) => a + b) / n;

            const mean2 = prices2.reduce((a, b) => a + b) / n;


            let numerator = 0;

            let denominator1 = 0;

            let denominator2 = 0;


            for (let i = 0; i < n; i++) {

                const diff1 = prices1[i] - mean1;

                const diff2 = prices2[i] - mean2;

                numerator += diff1 * diff2;

                denominator1 += diff1 ** 2;

                denominator2 += diff2 ** 2;

            }


            return denominator1 && denominator2 ? (numerator / Math.sqrt(denominator1 * denominator2)) : 0;

        }


        async function updateCorrelationTable() {

            const historicalPrices = await fetchHistoricalData();

            const correlationTableBody = document.querySelector('#correlation-table tbody');

            correlationTableBody.innerHTML = '';


            const uniPrices = historicalPrices['uniswap'];


            for (const coin of ['bitcoin', 'ethereum', 'tether', 'binancecoin', 'cardano']) {

                const prices = historicalPrices[coin];

                const correlation = calculateCorrelation(uniPrices, prices);

                correlationTableBody.innerHTML += `

                    <tr>

                        <td>${coin.charAt(0).toUpperCase() + coin.slice(1)}</td>

                        <td>${prices.length > 0 ? correlation.toFixed(2) : 'Dados insuficientes'}</td>

                    </tr>

                `;

            }

        }


        // Chamar as funções para buscar os dados

        updateUniswapTable().then(updateCorrelationTable);

    </script>

</body>


</html>


{"status":{"error_code":429,"error_message":"Você excedeu o Limite de Taxa. Acesse https://www.coingecko.com/en/api/pricing para assinar nossos planos de API para limites de taxa mais altos."}}

Parece que você excedeu o limite de taxa da API do CoinGecko. Isso significa que muitas requisições foram feitas em um curto período de tempo e a API bloqueou novas requisições temporariamente.

Aqui estão algumas opções para resolver esse problema:

Aqui está um exemplo de como você poderia implementar um sistema de cache para reduzir a quantidade de requisições:

javascript

let uniswapDataCache = null;

let lastFetchTime = 0;

const CACHE_DURATION = 10 * 60 * 1000; // 10 minutos em milissegundos


async function fetchUniswapData() {

    const currentTime = Date.now();

    

    if (uniswapDataCache && (currentTime - lastFetchTime < CACHE_DURATION)) {

        console.log("Usando dados do cache:", uniswapDataCache);

        return uniswapDataCache;

    }


    try {

        const url = "https://api.coingecko.com/api/v3/simple/price?ids=uniswap&vs_currencies=usd,brl&include_market_cap=true&include_24hr_vol=true&include_last_updated_at=true";

        console.log("Fetching Uniswap data from:", url);

        const response = await fetch(url);

        console.log("Response status:", response.status);


        if (!response.ok) throw new Error('Erro ao carregar dados da Uniswap: ' + response.status + ' ' + response.statusText);


        const data = await response.json();

        console.log("Uniswap data received:", data);

        

        if (data.uniswap) {

            uniswapDataCache = data.uniswap;

            lastFetchTime = currentTime;

            return uniswapDataCache;

        } else {

            throw new Error('Dados não encontrados na resposta da API.');

        }

        

    } catch (error) {

        console.error("Error fetching Uniswap data:", error);

        return null;

    }

}


async function updateUniswapTable() {

    const uniswapData = await fetchUniswapData();


    if (uniswapData) {

        const tableBody = document.querySelector('#uniswap-table tbody');

        tableBody.innerHTML = `

            <tr>

                <td>${uniswapData.usd}</td>

                <td>${uniswapData.brl}</td>

                <td>${uniswapData.usd_market_cap}</td>

                <td>${uniswapData.usd_24h_vol}</td>

                <td>${new Date(uniswapData.last_updated_at * 1000).toLocaleString('pt-BR')}</td>

            </tr>

        `;

    }

}


// Chamar as funções para buscar os dados

updateUniswapTable().then(updateCorrelationTable);


Com isso, os dados da Uniswap serão armazenados em cache por 10 minutos, reduzindo significativamente o número de requisições à API. Se precisar de mais ajuda, estou aqui para isso!


<!DOCTYPE html>

<html lang="pt-BR">


<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Dados da Uniswap</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            margin: 20px;

        }


        table {

            width: 100%;

            border-collapse: collapse;

            margin-top: 20px;

        }


        th,

        td {

            border: 1px solid #ddd;

            padding: 8px;

            text-align: center;

        }


        th {

            background-color: #f2f2f2;

        }


        .loading {

            font-style: italic;

            color: gray;

        }


        .error {

            color: red;

        }

    </style>

</head>


<body>

    <h1>Dados da Uniswap</h1>

    <table id="uniswap-table">

        <thead>

            <tr>

                <th>Preço (USD)</th>

                <th>Preço (BRL)</th>

                <th>Capitalização de Mercado (USD)</th>

                <th>Volume em 24h (USD)</th>

                <th>Última Atualização</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td colspan="5" class="loading">Carregando dados da Uniswap...</td>

            </tr>

        </tbody>

    </table>


    <h2>Correlação entre UNI e Outras Moedas</h2>

    <table id="correlation-table">

        <thead>

            <tr>

                <th>Moeda</th>

                <th>Correlação com UNI</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td colspan="2" class="loading">Carregando dados de correlação...</td>

            </tr>

        </tbody>

    </table>


    <script>

        async function fetchUniswapData() {

            try {

                const url = "https://api.coingecko.com/api/v3/simple/price?ids=uniswap&vs_currencies=usd,brl&include_market_cap=true&include_24hr_vol=true&include_last_updated_at=true";

                console.log("Fetching Uniswap data from:", url);

                const response = await fetch(url);

                console.log("Response status:", response.status);


                if (!response.ok) throw new Error('Erro ao carregar dados da Uniswap: ' + response.status + ' ' + response.statusText);


                const data = await response.json();

                console.log("Uniswap data received:", data);

                

                if (data.uniswap) {

                    console.log("Detalhes dos dados da Uniswap:", data.uniswap); // Adicionando log detalhado

                    const uniswapData = data.uniswap;

                    const tableBody = document.querySelector('#uniswap-table tbody');

                    tableBody.innerHTML = `

                        <tr>

                            <td>${uniswapData.usd}</td>

                            <td>${uniswapData.brl}</td>

                            <td>${uniswapData.usd_market_cap}</td>

                            <td>${uniswapData.usd_24h_vol}</td>

                            <td>${new Date(uniswapData.last_updated_at * 1000).toLocaleString('pt-BR')}</td>

                        </tr>

                    `;

                } else {

                    throw new Error('Dados não encontrados na resposta da API.');

                }

                

            } catch (error) {

                console.error("Error fetching Uniswap data:", error);

                const tableBody = document.querySelector('#uniswap-table tbody');

                tableBody.innerHTML = `

                    <tr>

                        <td colspan="5" class="error">${error.message}</td>

                    </tr>

                `;

            }

        }


        async function fetchHistoricalData() {

            const coins = ['bitcoin', 'ethereum', 'tether', 'binancecoin', 'cardano', 'uniswap'];

            const historicalPrices = {};


            for (const coin of coins) {

                try {

                    const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart?vs_currency=usd&days=30`;

                    console.log(`Fetching historical data for ${coin} from:`, url);

                    const response = await fetch(url);

                    console.log("Response status for", coin, ":", response.status);


                    if (!response.ok) throw new Error(`Erro ao carregar dados de ${coin}: ${response.status} ${response.statusText}`);


                    const data = await response.json();

                    historicalPrices[coin] = data.prices.map(price => price[1]); // Preço em USD

                    console.log(`${coin} historical prices:`, historicalPrices[coin]);

                } catch (error) {

                    console.error(`Error fetching historical data for ${coin}:`, error);

                    historicalPrices[coin] = []; // Armazenar array vazio se houver erro

                }

            }


            return historicalPrices;

        }


        function calculateCorrelation(prices1, prices2) {

            const n = Math.min(prices1.length, prices2.length);

            if (n < 2) return 0; // Garantir que haja dados suficientes


            const mean1 = prices1.reduce((a, b) => a + b) / n;

            const mean2 = prices2.reduce((a, b) => a + b) / n;


            let numerator = 0;

            let denominator1 = 0;

            let denominator2 = 0;


            for (let i = 0; i < n; i++) {

                const diff1 = prices1[i] - mean1;

                const diff2 = prices2[i] - mean2;

                numerator += diff1 * diff2;

                denominator1 += diff1 ** 2;

                denominator2 += diff2 ** 2;

            }


            return denominator1 && denominator2 ? (numerator / Math.sqrt(denominator1 * denominator2)) : 0;

        }


        async function updateCorrelationTable() {

            const historicalPrices = await fetchHistoricalData();

            const correlationTableBody = document.querySelector('#correlation-table tbody');

            correlationTableBody.innerHTML = '';


            const uniPrices = historicalPrices['uniswap'];


            for (const coin of ['bitcoin', 'ethereum', 'tether', 'binancecoin', 'cardano']) {

                const prices = historicalPrices[coin];

                const correlation = calculateCorrelation(uniPrices, prices);

                correlationTableBody.innerHTML += `

                    <tr>

                        <td>${coin.charAt(0).toUpperCase() + coin.slice(1)}</td>

                        <td>${prices.length > 0 ? correlation.toFixed(2) : 'Dados insuficientes'}</td>

                    </tr>

                `;

            }

        }


        // Chamar as funções para buscar os dados

        fetchUniswapData().then(updateCorrelationTable);

    </script>

</body>


</html>