How to Fetch Real-Time Token Prices Using AutoHedge's `get_token_price` Function

AutoHedge's get_token_price function wraps Jupiter's Price API V3 to retrieve live USD prices for Solana token mint addresses, returning structured JSON data via a simple Python interface.

AutoHedge is an open-source automation framework for Solana DeFi strategies. Fetching accurate pricing data is essential for any hedging or arbitrage logic, and the library provides a dedicated tool in autohedge/tools/jupiter_price.py to handle this via Jupiter's aggregated liquidity.

Architecture of the Price Fetching Tool

The implementation relies on a lightweight HTTP client wrapper around Jupiter's public Price API. According to the AutoHedge source code, the function performs a synchronous GET request and handles both single and batch token lookups.

Jupiter Price API V3 Integration

In [autohedge/tools/jupiter_price.py](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/tools/jupiter_price.py), the get_token_price function constructs the endpoint URL https://api.jup.ag/price/v3 and appends token mint addresses as query parameters. The code supports both individual strings and lists of strings for the ids parameter, allowing bulk price retrieval in a single network call.

Function Signature and Environment Configuration

The method signature accepts flexible input types:

def get_token_price(ids: Union[str, List[str]]) -> str:
    ...

Authentication is optional but recommended for production use. The function checks for a JUPITER_API_KEY environment variable and injects it as the x-api-key header in the HTTP request. Without this key, requests may face rate limits on Jupiter's public tier.

Implementation and Code Examples

The source uses httpx.Client with a 10-second timeout to ensure requests do not hang indefinitely. Below are practical patterns for integrating this into your trading logic.

Fetching a Single Token Price

To retrieve the current USD price for Wrapped SOL:

from autohedge.tools import get_token_price

# Wrapped SOL mint address

sol_price_json = get_token_price("So11111111111111111111111111111111111111112")
print(sol_price_json)

# Output: {"So11111111111111111111111111111111111111112": {"usdPrice": 19.73, ...}}

Batch Price Retrieval

For portfolio calculations, pass a list of mint addresses:

token_mints = [
    "So11111111111111111111111111111111111111112",   # Wrapped SOL

    "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",   # USDC

    "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"    # Bonk

]

prices = get_token_price(token_mints)

# Returns JSON string mapping each mint to its price, liquidity depth, and confidence levels

Environment Setup

Configure your API key before importing the function:

export JUPITER_API_KEY="your_jupiter_api_key_here"

Refer to the .env.example file in the repository for the required variable name format.

Error Handling and Edge Cases

The implementation includes defensive programming for edge cases encountered in production trading environments.

Empty Input Validation

If the ids parameter is empty or contains only whitespace, the function logs a warning via loguru and returns an empty JSON object string ("{}"). This prevents unnecessary network overhead and API errors.

Network Exception Management

All HTTP errors raise httpx.HTTPError, which bubbles up to the caller. The function does not swallow timeouts or 4xx/5xx responses, allowing your application to implement retry logic or circuit breakers as needed. As implemented in The-Swarm-Corporation/AutoHedge, the tool relies on the caller to handle httpx.ConnectTimeout or httpx.HTTPStatusError exceptions.

Integration with AutoHedge's Tool Registry

The function is exposed through the public API via two key files:

This dual-layer export ensures the function is accessible both as a standalone utility and as a component within larger AI-driven trading pipelines.

Summary

Frequently Asked Questions

What API does AutoHedge use to fetch token prices?

AutoHedge uses the Jupiter Price API V3, specifically the endpoint at https://api.jup.ag/price/v3. This aggregator pulls liquidity from Solana decentralized exchanges to provide accurate USD reference prices with confidence intervals.

Does get_token_price require an API key?

No, the function works without an API key for basic usage. However, for higher rate limits and production reliability, you should set the JUPITER_API_KEY environment variable. The code automatically detects this variable and adds it as the x-api-key header when present.

Can I fetch prices for multiple tokens in one call?

Yes. The function accepts a list[str] for the ids parameter, allowing you to query dozens of token prices simultaneously. This reduces network overhead compared to iterative single-token requests and is the recommended pattern for portfolio valuation logic.

What happens if the Jupiter API is unavailable?

The function raises httpx.HTTPError (or specific subclasses like httpx.ConnectTimeout) which must be caught by your application code. It does not implement internal retry logic, giving you full control over failure handling strategies such as exponential backoff or fallback to cached data.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →