Code Examples

Ready-to-use code examples for common use cases

Portfolio Tracker

Track the real-time value of your cryptocurrency holdings

React Component
import { useState, useEffect } from 'react';
import axios from 'axios';

export function PortfolioTracker({ tokens }) {
  const [portfolio, setPortfolio] = useState([]);
  const [totalValue, setTotalValue] = useState(0);

  useEffect(() => {
    const fetchPrices = async () => {
      const prices = await Promise.all(
        tokens.map(token =>
          axios.get(`/api/coingecko/token?tokenId=${token.id}`)
        )
      );

      const portfolioData = prices.map((res, i) => ({
        name: tokens[i].name,
        amount: tokens[i].amount,
        price: res.data.data.current_price,
        value: tokens[i].amount * res.data.data.current_price
      }));

      setPortfolio(portfolioData);
      setTotalValue(portfolioData.reduce((sum, t) => sum + t.value, 0));
    };

    fetchPrices();
  }, [tokens]);

  return (
    <div>
      <h2>Portfolio Value: ${totalValue.toFixed(2)}</h2>
      {portfolio.map(token => (
        <div key={token.name}>
          <p>{token.name}: {token.amount} @ ${token.price}</p>
        </div>
      ))}
    </div>
  );
}

Market Sentiment Display

Display real-time market sentiment and analysis

React Component
import { useState, useEffect } from 'react';
import axios from 'axios';

export function MarketSentiment({ tokenQuery }) {
  const [sentiment, setSentiment] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchSentiment = async () => {
      setLoading(true);
      try {
        const response = await axios.get(
          `/api/gemini/overview?query=${encodeURIComponent(tokenQuery)}`
        );
        setSentiment(response.data.data);
      } catch (error) {
        console.error('Error fetching sentiment:', error);
      }
      setLoading(false);
    };

    fetchSentiment();
  }, [tokenQuery]);

  if (loading) return <div>Loading...</div>;
  if (!sentiment) return null;

  return (
    <div>
      <h2>Market Sentiment</h2>
      <p>Sentiment: {sentiment.sentiment}</p>
      <p>Confidence: {(sentiment.confidence * 100).toFixed(1)}%</p>
      <h3>Analysis</h3>
      <p>{sentiment.analysis}</p>
      <h3>Key Factors</h3>
      <ul>
        {sentiment.key_factors.map(factor => (
          <li key={factor}>{factor}</li>
        ))}
      </ul>
    </div>
  );
}

Token Comparison

Compare multiple tokens side-by-side

React Component
import { useState, useEffect } from 'react';
import axios from 'axios';

export function TokenComparison({ tokenIds }) {
  const [tokens, setTokens] = useState([]);

  useEffect(() => {
    const fetchTokens = async () => {
      const data = await Promise.all(
        tokenIds.map(id =>
          axios.get(`/api/coingecko/token?tokenId=${id}`)
            .then(res => ({ id, data: res.data.data }))
        )
      );
      setTokens(data);
    };

    fetchTokens();
  }, [tokenIds]);

  return (
    <table>
      <thead>
        <tr>
          <th>Token</th>
          <th>Price</th>
          <th>Market Cap</th>
          <th>24h Change</th>
        </tr>
      </thead>
      <tbody>
        {tokens.map(token => (
          <tr key={token.id}>
            <td>{token.data.name}</td>
            <td>${token.data.current_price}</td>
            <td>${(token.data.market_cap / 1e9).toFixed(2)}B</td>
            <td>{token.data.price_change_percentage_24h?.toFixed(2)}%</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}