API inserindo

<!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>

        const apiKey = 'CG-tKGVZRyT23GMxMHrGvk5RyBX ';  // Substitua 'SUA_API_KEY' pela sua chave da API CoinMarketCap


        async function fetchUniswapData() {

            try {

                const url = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=UNI&convert=USD,BRL`;

                const response = await fetch(url, {

                    headers: {

                        'X-CMC_PRO_API_KEY': apiKey

                    }

                });

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

                

                const data = await response.json();

                const uniswapData = data.data.UNI;


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

                tableBody.innerHTML = `

                    <tr>

                        <td>${uniswapData.quote.USD.price}</td>

                        <td>${uniswapData.quote.BRL.price}</td>

                        <td>${uniswapData.quote.USD.market_cap}</td>

                        <td>${uniswapData.quote.USD.volume_24h}</td>

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

                    </tr>

                `;

            } catch (error) {

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

                tableBody.innerHTML = `

                    <tr>

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

                    </tr>

                `;

            }

        }


        async function fetchHistoricalData() {

            // Implementação similar à anterior, usando outra API ou dados mockados

        }


        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() {

            // Implementação similar à anterior, usando outra API ou dados mockados

        }


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

        fetchUniswapData().then(updateCorrelationTable);

    </script>

</body>


</html>


<!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>

        const apiKey = 'CG-tKGVZRyT23GMxMHrGvk5RyBX ';  // Substitua 'SUA_API_KEY' pela sua chave da API CoinGecko


        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&x_cg_pro_api_key=${apiKey}`;

                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) {

                    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&x_cg_pro_api_key=${apiKey}`;

                    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>


Fiz um API teste no coingecko. Onde coloco no html. Indique no html para inserir o API chave.

Ótimo! Vou te mostrar como incluir a chave da API no HTML. Vamos adicionar a chave da API ao URL de solicitação na função fetch.

Aqui está um exemplo de como fazer isso:

html

<!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>

        const apiKey = 'CG-tKGVZRyT23GMxMHrGvk5RyBX ';  // Substitua 'SUA_API_KEY' pela sua chave da API CoinGecko


        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&x_cg_pro_api_key=${apiKey}`;

                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) {

                    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&x_cg_pro_api_key=${apiKey}`;

                    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>


Substitua 'SUA_API_KEY' pela chave da API que você obteve no CoinGecko. Isso deve garantir que a chave da API seja usada nas solicitações para evitar o erro de limite de taxa.

Experimente e veja se isso resolve o problema. Se precisar de mais alguma coisa, estarei por aqui