paint-brush
Using Mobula to Fetch and Display Market Data For Assetsby@wise4rmgod
292 reads

Using Mobula to Fetch and Display Market Data For Assets

by Wisdom NwokochaJanuary 30th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Mobula API is a powerful tool that allows developers to access curated datasets for various crypto assets.
featured image - Using Mobula to Fetch and Display Market Data For Assets
Wisdom Nwokocha HackerNoon profile picture

Mobula API is a powerful tool that allows developers to access curated datasets for various crypto assets, such as market data, wallet transactions, historical balances, and swap quotes.


Mobula API provides a unified and aggregated interface to query data from multiple blockchains and sources.


In this article, you will learn how to use Mobula API to fetch and display market data for any assets using React, a popular front-end library for building user interfaces.


Mobula API Overview

Mobula API is a blockchain data provider that offers developers a wide range of features and functionalities.


It provides curated datasets, market data with Octopus, wallet data, metadata with Metacore, and REST, GraphSQL & SQL interfaces to query them.


Mobula API supports several chains, including:

  • Ethereum,
  • Avalanche,
  • Polygon,
  • Fantom,
  • Harmony,
  • xDai,
  • Cronos,
  • DFK Subnet,
  • SmartBCH,
  • Celo,
  • Klaytn,
  • Aurora,
  • HECO,
  • Arbitrum,
  • And more.


Developers can access vital data and perform key operations using Mobula API’s endpoints, designed to provide seamless integration and efficient access to blockchain features.


Mobula API also offers easy-to-integrate tools to fetch market data, wallet transactions, holdings, etc.

Retrieving Bitcoin Market Data

Key Requirements for API Calls:

  • API Key:

    • Mandatory for production environments.
    • Obtainable from your Mobula Dashboard.
    • Not required for development mode.
  • Method:

    • Use GET to retrieve data.
  • Base URL:

  • Endpoint:

    • /market/query (for market data queries)


Query parameters:

Parameter

Type

Description

Available Values

filters

string

A comma-separated list of filters to apply to the data.

liquidity, market_cap, volume, price, price_change_24h, price_change_1h, price_change_7d

sortBy

string

A comma-separated list of fields to sort the data by.

liquidity, market_cap, volume, price, price_change_24h, price_change_1h, price_change_7d

sortOrder

string

The order in which to sort the data.

asc (ascending), desc (descending)


Example Usage:

This example demonstrates how to retrieve market data for mid-cap cryptocurrencies with strong liquidity and promising potential.


Parameter Breakdown:

  • filters:

    • liquidity:100:1000: Selects assets with liquidity between 100 and 1000 (inclusive). This ensures sufficient trading volume for easy entry and exit.
    • market_cap:10000:100000: Chooses assets with market capitalization between 10,000 and 100,000 (inclusive). This range targets mid-cap projects with established value and room for growth.
  • sortBy=market_cap: Sorts the retrieved data by market capitalization in descending order. This prioritizes larger and potentially more stable assets.

  • sortOrder=desc: Specifies descending order for sorting. This displays the largest cap currencies first, making it easier to identify prominent mid-cap contenders.


filters=liquidity:100:1000,market_cap:10000:100000
sortBy=market_cap
sortOrder=desc


Response:

{
    "name": "NFTDAO",
    "logo": "https://metacore.mobula.io/d0acfb425c161c8e3e5426c77ec36128ecfd688c2367a411cab9c440acb8b7a3.png",
    "symbol": "NAO",
    "liquidity": 769,
    "market_cap": 97230,
    "volume": 0,
    "price": 9.723276418969192e-10,
    "price_change_1h": 0,
    "price_change_24h": 0,
    "price_change_7d": 0,
    "contracts": [
      {
        "address": "0xd049206fb408a611e543791f2d8f102a8bc253dc",
        "blockchain": "Ethereum",
        "blockchainId": "1",
        "decimals": 18
      }
    ],
    "id": 4696,
    "rank": 4673
  }


Explanation of the response:

Field

Description

Value

name

Name of the cryptocurrency

NFTDAO

logo

URL of the cryptocurrency’s logo

1

symbol

Symbol of the cryptocurrency

NAO

liquidity

Liquidity of the cryptocurrency

769

market_cap

Market capitalization of the cryptocurrency

97230

volume

Volume of the cryptocurrency

0

price

Price of the cryptocurrency

9.723276418969192e-10

price_change_1h

Percentage change in price over the last hour

0

price_change_24h

Percentage change in price over the last 24 hours

0

price_change_7d

Percentage change in price over the last 7 days

0

contracts

List of contracts associated with the cryptocurrency

[{“address”: “0xd049206fb408a611e543791f2d8f102a8bc253dc”, “blockchain”: “Ethereum”, “blockchainId”: “1”, “decimals”: 18}]

id

Unique identifier for the cryptocurrency

4696

rank

Rank of the cryptocurrency based on market capitalization


Exploring Block Data with Mobula Queries

To build a React project that interacts with the Mobula API and fetches data, follow these steps:

Step 1: Set Up Your React Project

First, ensure you have Node.js and npm installed on your machine. Then, create a new React project using Create React App:

npm create vite@latest mobula-market-app -- --template react
cd mobula-market-app


Step 2: Install Dependencies

Install Axios, a popular HTTP client for making API requests, to handle HTTP requests in your React project:

npm install axios


Step 3: Create a Component for API Interaction

Create a new file named MarketData.js inside the src directory to contain the logic for fetching market data:

// src/MarketData.js
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Line } from "react-chartjs-2";

const MarketData = () => {
  const [marketData, setMarketData] = useState(null);
  const [selectedCrypto, setSelectedCrypto] = useState(null);
  const [filters, setFilters] = useState("");
  const [sortBy, setSortBy] = useState("");
  const [sortOrder, setSortOrder] = useState("");
  const [showModal, setShowModal] = useState(false);

  const fetchData = async () => {
    try {
      const response = await axios.get(
        `https://api.mobula.io/api/1/market/query?filters=${filters}&sortBy=${sortBy}&sortOrder=${sortOrder}`
      );
      setMarketData(response.data);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  useEffect(() => {
    fetchData();
  }, [filters, sortBy, sortOrder]);

  const handleCardClick = (item) => {
    setSelectedCrypto(item);
    setShowModal(true); // Ensure showModal is set to true when a card is clicked
  };

  const handleCloseModal = () => {
    setShowModal(false);
  };

  const renderChart = () => {
    if (!selectedCrypto) return null;

    const data = {
      labels: ["1h", "24h", "7d"],
      datasets: [
        {
          label: "Price Change",
          data: [
            selectedCrypto.price_change_1h,
            selectedCrypto.price_change_24h,
            selectedCrypto.price_change_7d,
          ],
          fill: false,
          borderColor: "rgb(75, 192, 192)",
          tension: 0.1,
        },
      ],
    };

    return (
      <div
        style={{
          position: "fixed",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          backgroundColor: "#fff",
          padding: "20px",
          zIndex: 9999,
        }}
      >
        <button
          onClick={handleCloseModal}
          style={{ position: "absolute", top: "10px", right: "10px" }}
        >
          Close
        </button>
        <h3>Price Change Chart for {selectedCrypto.name}</h3>
        <Line data={data} />
      </div>
    );
  };

  const renderCryptoCards = (cryptoData) => {
    return cryptoData.map((item, index) => (
      <div
        key={item.id}
        style={{
          border: "1px solid #ccc",
          borderRadius: "5px",
          padding: "10px",
          marginBottom: "20px",
          width: "calc(33.33% - 20px)",
          marginRight: "20px",
          display: "inline-block",
        }}
      >
        <img
          src={item.logo}
          alt={`${item.name} logo`}
          style={{ width: "50px", height: "50px", marginRight: "10px" }}
        />
        <div>
          <h3>{item.name}</h3>
          <p>
            <strong>Symbol:</strong> {item.symbol}
          </p>
          <p>
            <strong>Liquidity:</strong> {item.liquidity}
          </p>
          <p>
            <strong>Market Cap:</strong> {item.market_cap}
          </p>
          <button onClick={() => handleCardClick(item)}>View Graph</button>
        </div>
      </div>
    ));
  };

  const renderBlockchainTabs = () => {
    if (!marketData) return null;

    const categorizedData = {};

    marketData.forEach((item) => {
      const blockchain = item.contracts[0].blockchain;
      if (!categorizedData[blockchain]) {
        categorizedData[blockchain] = [];
      }
      categorizedData[blockchain].push(item);
    });

    return Object.entries(categorizedData).map(([blockchain, data]) => (
      <div key={blockchain}>
        <h2>{blockchain}</h2>
        <div style={{ display: "flex", flexWrap: "wrap" }}>
          {renderCryptoCards(data)}
        </div>
      </div>
    ));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    fetchData();
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          Filters:
          <input
            type="text"
            value={filters}
            onChange={(e) => setFilters(e.target.value)}
          />
        </label>
        <label>
          Sort By:
          <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
            <option value="">Select</option>
            <option value="liquidity">Liquidity</option>
            <option value="market_cap">Market Cap</option>
          </select>
        </label>
        <label>
          Sort Order:
          <select
            value={sortOrder}
            onChange={(e) => setSortOrder(e.target.value)}
          >
            <option value="">Select</option>
            <option value="asc">Ascending</option>
            <option value="desc">Descending</option>
          </select>
        </label>
        <button type="submit">Fetch Data</button>
      </form>
      {renderBlockchainTabs()}
      {showModal && renderChart()}
    </div>
  );
};

export default MarketData;


Step 4: Integrate the Component in Your App

Modify the App.js file to include the MarketData component:

// src/App.js
import React from 'react';
import './App.css';
import MarketData from './MarketData';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Mobula Market Data</h1>
      </header>
      <main>
        <MarketData />
      </main>
    </div>
  );
}

export default App;


Folder structure:

Step 5: Run Your React App

Start your React development server to see the app in action:

npm start