Skip to main content

How to Track DEX Wallet Trading Performance using Syve's APIs

Updated on
Aug 15, 2024

8 min read

Overview

In this guide, we'll walk you through building an Ethereum wallet performance analyzer app using Syve's DEX Price Data & Wallet Tracking APIs. This application allows users to enter a wallet address and analyze trading performance metrics, such as profit and loss, for each token traded. The app provides insights into both realized and unrealized performance metrics, leveraging data from the blockchain.

What You Will Do

  • Clone a ready-to-use React app from our GitHub repository that utilizes the DEX Price Data & Wallet Tracking APIs
  • Understand how the app uses Syve's DEX Price Data & Wallet Tracking APIs to fetch wallet trading performance metrics

What You Will Need

  • A QuickNode account with access to the DEX Price Data & Wallet Tracking APIs
  • Node.js installed (v20 or higher)
  • A code editor (e.g., VS Code)
  • TypeScript and ts-node - installation instructions are indicated in the guide
  • Familiarity with JavaScript or TypeScript, and basic knowledge of React

How the DEX Price Data & Wallet Tracking APIs Work

Syve's DEX Price Data & Wallet Tracking APIs provide comprehensive tools for analyzing wallet performance and token price data across decentralized exchanges. These APIs enable developers to fetch detailed metrics for wallet trading activities and historical price data easily.

API Methods

The following methods are available in the DEX Price Data & Wallet Tracking APIs:

  • v1/getWalletLatestTotalPerformance: Provides overall trading performance metrics of a wallet, such as total profit and loss.
  • v1/getWalletLatestPerformancePerToken: Retrieves key trading performance metrics for each token traded by a specific wallet.
  • v1/getPriceHistoricalOHLC: Fetches historical DEX price data in OHLCV (Open-High-Low-Close-Volume) format.

In this guide, we will primarily use the v1/getWalletLatestTotalPerformance and v1/getWalletLatestPerformancePerToken methods to build our wallet performance analyzer app.

Total Performance Metrics

The v1/getWalletLatestTotalPerformance method returns an object with the following metrics:

MetricDescription
first_trade_timestampTimestamp of the first trade made by the wallet.
last_trade_timestampTimestamp of the most recent trade made by the wallet.
pnlTotal profit and loss for the wallet.
realized_investmentAmount invested in trades that have been closed.
realized_profitProfit from trades that have been closed.
realized_returnReturn on investment from closed trades.
realized_valueValue of the portfolio based on closed trades.
total_buy_volumeTotal volume of tokens purchased.
total_buysTotal number of buy transactions.
total_investmentTotal amount invested across all trades.
total_profitTotal profit from all trades.
total_returnTotal return on investment.
total_sell_volumeTotal volume of tokens sold.
total_sellsTotal number of sell transactions.
total_tokens_tradedNumber of unique tokens traded.
total_tradesTotal number of trades (buys + sells).
total_valueCurrent value of the portfolio.
unrealized_investmentAmount invested in trades that are still open.
unrealized_profitProfit from trades that are still open.
unrealized_returnReturn on investment from open trades.
unrealized_valueValue of the portfolio based on open trades.
wallet_addressAddress of the wallet being analyzed.
win_ratePercentage of trades that resulted in a profit.

Token-Specific Performance Metrics

The v1/getWalletLatestPerformancePerToken method returns an array of objects, each containing metrics for a specific token:

MetricDescription
avg_buy_priceAverage price at which the token was purchased.
avg_sell_priceAverage price at which the token was sold (if applicable).
current_priceCurrent market price of the token.
first_trade_timestampTimestamp of the first trade involving the token.
last_trade_timestampTimestamp of the most recent trade involving the token.
pnlProfit and loss for the token.
realized_investmentAmount invested in closed trades involving the token.
realized_profitProfit from closed trades involving the token.
realized_returnReturn on investment from closed trades involving the token (if applicable).
realized_valueValue of closed trades involving the token.
token_addressAddress of the token being analyzed.
token_nameName of the token.
token_symbolSymbol of the token.
total_buy_amountTotal amount of the token purchased.
total_buy_volumeTotal volume of the token purchased.
total_buysTotal number of buy transactions for the token.
total_investmentTotal amount invested in the token.
total_profitTotal profit from trades involving the token.
total_returnTotal return on investment for the token (if applicable).
total_sell_amountTotal amount of the token sold.
total_sell_volumeTotal volume of the token sold.
total_sellsTotal number of sell transactions for the token.
total_tradesTotal number of trades involving the token.
total_valueCurrent value of the token holdings.
trading_balanceCurrent balance of the token held.
unrealized_investmentAmount invested in open trades involving the token.
unrealized_profitProfit from open trades involving the token.
unrealized_returnReturn on investment from open trades involving the token (if applicable).
unrealized_valueValue of open trades involving the token.

Profit and Loss Calculations

Syve has a detailed methodology for calculating profit, loss, and other performance metrics. For more in-depth information on these calculations, refer to Syve's blog on profit and loss metrics.

Wallet Performance Analyzer App

This section will guide you through the components and logic used in the wallet performance analyzer app. We'll cover how the app interacts with Syve's API and processes the retrieved data.

This is how the app will look; now, let's learn the details.

Wallet Performance Analyzer App

The app is built using React, TypeScript, and Tailwind CSS. Below, we describe the logic behind the main components:

Main Logic and Workflow


  1. User Input: The app starts by allowing users to input an Ethereum wallet address.
  2. Address Validation: The input is validated to ensure it's a valid Ethereum address.
  3. API Calls: Upon submission, the app makes two simultaneous API calls to QuickNode's endpoints:
    • One to fetch overall wallet performance
    • Another to fetch token-specific performance data
  4. Data Processing: The retrieved data is then processed and stored in the app's state.
  5. Display: The processed data is displayed in two main sections:
    • Overall wallet performance statistics
    • Detailed token-by-token performance breakdown

File Structure and Descriptions

App.tsx

  • This is the main component that orchestrates the entire application.
  • It manages the app's state, including wallet address overall stats, and token performance data.
  • Handles the API calls and data fetching logic.
  • Renders the main layout and child components.

WalletSearch.tsx:

  • Renders the input form for the wallet address.
  • Performs client-side validation of the Ethereum address.
  • Triggers the search function in the parent component upon submission.

OverallStatsDisplay.tsx:

  • Displays the overall wallet performance statistics.
  • Formats and presents data such as total profit/loss, win rate, and trade volumes.
  • Uses color coding to highlight positive and negative values.

TokenPerformanceTable.tsx:

  • Renders a table showing detailed performance for each token.
  • Implements expandable rows for additional token-specific information.
  • Provides links to Etherscan for each token.

api.ts:

  • Contains the API calling functions using Axios.
  • Structures the API requests according to Syve's requirements.
  • Handles any necessary data transformation before returning results to the main app.

interfaces/OverallStats.ts and interfaces/TokenPerformance.ts:

  • Define TypeScript interfaces for the data structures used in the app.

Fetching Wallet Performance Data

To fetch wallet trading performance data, you'll need to make RPC calls to the QuickNode Ethereum endpoint.

The following code (api.ts) demonstrates how to set up a function to make RPC calls to the QuickNode endpoint and use the available methods to fetch wallet performance data:

We will build the project in the following section. For now, there is no need to take any action; this code snippet is just for explanation.

api.ts File
import axios from "axios";
import { OverallStats } from "../interfaces/OverallStats";
import { TokenPerformanceResult } from "../interfaces/TokenPerformance";

const QUICKNODE_ENDPOINT = import.meta.env.VITE_QUICKNODE_ENDPOINT as string;

const makeRpcCall = async (method: string, params: any) => {
const response = await axios.post(
QUICKNODE_ENDPOINT,
{
method,
params,
id: 1,
jsonrpc: "2.0",
},
{
headers: {
"Content-Type": "application/json",
},
}
);

if (response.data.error) {
throw new Error(response.data.error.message);
}

return response.data.result;
};

export const getWalletLatestTotalPerformance = async (
walletAddress: string
): Promise<OverallStats> => {
const result = await makeRpcCall("v1/getWalletLatestTotalPerformance", {
wallet_address: walletAddress,
max_size_ok: "true",
});
return result as OverallStats;
};

export const getWalletLatestPerformancePerToken = async (
walletAddress: string
): Promise<TokenPerformanceResult> => {
const result = await makeRpcCall("v1/getWalletLatestPerformancePerToken", {
wallet_address: walletAddress,
max_size_ok: "true",
});
return result as TokenPerformanceResult;
};

  1. Axios Setup: The code uses the axios library to make HTTP POST requests to the QuickNode endpoint.

  2. Environment Variable: The QUICKNODE_ENDPOINT constant stores the URL of your QuickNode endpoint, which is fetched from the environment variables.

  3. RPC Call Function: The makeRpcCall function is a reusable function that performs the actual RPC call to the endpoint. It takes the method name and parameters as arguments and sends a POST request with these details.

  4. Exported Functions:

    • getWalletLatestTotalPerformance: This function calls the v1/getWalletLatestTotalPerformance method to fetch overall trading performance metrics for a given wallet address.
    • getWalletLatestPerformancePerToken: This function calls the v1/getWalletLatestPerformancePerToken method to retrieve performance metrics for each token traded by the wallet.

Now that we know the working logic of the application, let's move on to development!

Setting Up Your Development Environment

To build the wallet performance analyzer app, you need to set up your development environment. This involves installing the necessary tools and dependencies and configuring your QuickNode access.

Installing Necessary Tools and Dependencies

Before you begin, make sure you have Node.js installed on your system. If not, download and install it from the official website. Node.js comes with npm (Node Package Manager), which you will use to install other dependencies.

Next, install TypeScript and ts-node globally if you haven't already:

npm install -g typescript ts-node

Setting Up an Ethereum Endpoint

Before you begin, please note that the DEX Price Data & Wallet Tracking APIs are paid add-ons. Please check the details here and compare plans based on your needs.

Setting up your Ethereum endpoint with the DEX Price Data & Wallet Tracking APIs is straightforward. If you haven't signed up already, you can create an account here.

Once you have logged in, navigate to the Endpoints page and click Create an endpoint. Select Ethereum mainnet, then click Next. You'll be prompted to configure the add-on. Activate DEX Price Data & Wallet Tracking API. Afterward, simply click Create Endpoint.

If you already have an Ethereum endpoint without the add-on, go to the Add-ons page within your Ethereum endpoint, select the DEX Price Data & Wallet Tracking API, and activate it.

QuickNode - Ethereum Node Endpoint with Add-on

Once your endpoint is ready, copy the HTTP Provider link and keep it handy, as you'll need it in the next section.

Running the App

We have a ready-to-use solution available on our GitHub repository to get started quickly. Follow these steps to clone and set up the sample app:


  1. Clone the repository from GitHub
git clone https://github.com/quiknode-labs/qn-guide-examples.git

  1. Navigate to the project directory
cd sample-dapps/ethereum-dex-trade-performance-analyzer

  1. Install dependencies
npm install

  1. Rename .env.example to .env and replace the placeholder with your QuickNode Ethereum endpoint URL
VITE_QUICKNODE_ENDPOINT="YOUR_QUICKNODE_ENDPOINT_URL"

  1. Start the development server
npm run dev
  1. Open http://localhost:5173/ in your browser to see the application

  2. Enter the Ethereum address you want to analyze (i.e., Vitalik's address 0xd8da6bf26964af9d7eed9e03e53415d37aa96045) and explore the displayed overall stats and token-specific performance metrics

Afterward, you will see a screen similar to the one in the images below.

Overall PerformanceToken Specific Performance
App Overall PerformanceApp Token Specific Performance

Conclusion

Congratulations! You've successfully set up and explored the wallet performance analyzer app. Building a wallet performance analyzer app with Syve's DEX Price Data & Wallet Tracking APIs demonstrates how easily developers can create valuable tools. The flexibility and comprehensive data provided by these APIs enable developers to explore various applications that can provide users with actionable insights into their trading activities.

Possible Improvements to This Project

Here are some ideas to enhance the functionality and user experience of the wallet performance analyzer app:

  • Enhanced Visualization: Incorporate interactive charts and graphs to visualize wallet performance trends over time.
  • Multi-Wallet Support: Allow users to analyze and compare the performance of multiple wallets simultaneously.
  • Historical Data Analysis: Provide more detailed historical data analysis using the v1/getPriceHistoricalOHLC method to show price trends and volatility.

If you have any questions, feel free to use our dedicated channel on Discord or provide feedback using the form below. Stay up to date with the latest by following us on Twitter and our Telegram announcement channel.

We ❤️ Feedback!

Let us know if you have any feedback or requests for new topics. We'd love to hear from you.

Share this guide