# How AutoHedge Integrates with Jupiter APIs for Solana Trading

> Learn how AutoHedge integrates with Jupiter APIs to find optimal Solana trading routes and execute transactions efficiently. Discover the Python tools powering this integration.

- Repository: [Swarms/AutoHedge](https://github.com/The-Swarm-Corporation/AutoHedge)
- Tags: how-to-guide
- Published: 2026-09-09

---

**AutoHedge integrates with Jupiter's Ultra API through specialized Python modules—[`ultra_tools.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/ultra_tools.py), [`jupiter_search.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/jupiter_search.py), and [`jupiter_price.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/jupiter_price.py)—to discover optimal swap routes, validate real-time pricing, and execute Solana transactions via the orchestration layer in [`workers.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/workers.py).**

The AutoHedge repository by The-Swarm-Corporation implements an automated hedging engine that leverages the Jupiter Ultra API for high-frequency Solana trading. By modularizing route discovery, price validation, and swap execution into distinct components, the codebase provides a robust pipeline for programmatic token exchanges. This architecture ensures that hedging strategies operate with minimal latency while maintaining strict controls over slippage and transaction costs.

## Core Architecture of the Jupiter API Integration

### Low-Level API Wrappers in [`ultra_tools.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/ultra_tools.py)

The foundation of the integration resides in [`autohedge/tools/ultra_tools.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/tools/ultra_tools.py). This module contains the primary HTTP interface to Jupiter's Ultra endpoints, exposing three critical functions: `get_routes`, `get_price`, and `execute_swap`. 

The module uses **async `httpx`** for non-blocking requests, falling back to synchronous `requests` when necessary. It implements exponential backoff retry logic to handle Solana network congestion and parses JSON responses into native Python dictionaries. When the `JUPITER_API_KEY` environment variable is present (loaded via [`autohedge/env_loader.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/env_loader.py)), the wrapper injects it into the `x-api-key` header for authenticated access to higher rate limits.

### Route Discovery via [`jupiter_search.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/jupiter_search.py)

The [`autohedge/tools/jupiter_search.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/tools/jupiter_search.py) module implements high-level route discovery by wrapping `ultra_tools.get_routes`. It accepts token mint addresses and amounts denominated in lamports, returning an ordered list of viable swap paths. 

Each route object contains metadata about intermediate liquidity pools (`marketInfos`), enabling the engine to evaluate multi-hop trades across Solana decentralized exchanges. This module abstracts the complexity of Jupiter's route optimization algorithm, providing the hedging engine with a simple interface for sourcing liquidity.

### Price Validation in [`jupiter_price.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/jupiter_price.py)

Before executing any trade, [`autohedge/tools/jupiter_price.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/tools/jupiter_price.py) validates the economic viability of the proposed swap. By calling `ultra_tools.get_price`, this module retrieves real-time quote data including the expected output amount and `priceImpactPct`. 

The hedging strategy uses these values to enforce slippage tolerance limits. If the calculated price impact exceeds predefined thresholds, the worker aborts the transaction before reaching the execution phase, protecting the portfolio from adverse market movements.

### Execution Orchestration in [`workers.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/workers.py)

The [`autohedge/workers.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/workers.py) module serves as the orchestration layer that sequences the entire trading workflow. When the hedging engine triggers a signal, the worker:

1. Invokes `jupiter_search.get_routes()` to identify the optimal path
2. Passes the route to `jupiter_price.get_price()` for validation
3. Constructs a swap payload containing `userPublicKey`, `slippageBps`, `feeBps`, and `computeUnitPriceMicroLamports`
4. Calls `ultra_tools.execute_swap()` to submit a POST request to Jupiter's `/v4/swap` endpoint

The Jupiter API returns a base64-encoded Solana transaction, which the worker broadcasts to the network via the RPC endpoint configured in [`env_loader.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/env_loader.py).

## Step-by-Step Trading Flow

1. **Signal Detection**: The core engine in [`autohedge/main.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/main.py) monitors market conditions and emits trade signals when hedging criteria are satisfied.

2. **Route Discovery**: [`workers.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/workers.py) queries `jupiter_search.get_routes()` with the source token, destination token, and amount to retrieve candidate paths from Jupiter Ultra.

3. **Price Validation**: The optimal route undergoes scrutiny by `jupiter_price.get_price()`, which checks the `outAmount` and `priceImpactPct` against strategy constraints.

4. **Swap Execution**: Upon validation, `ultra_tools.execute_swap()` transmits the payload to Jupiter's API, receiving a signed transaction ready for on-chain submission.

5. **On-Chain Settlement**: The worker broadcasts the transaction to Solana validators via the configured RPC connection, completing the hedge.

## Code Examples for Jupiter API Integration

### Fetching Optimal Swap Routes

Use the `jupiter_search` module to discover the most efficient path between two tokens.

```python
from autohedge.tools.jupiter_search import get_routes

# Find routes to swap 10 USDC for SOL

routes = get_routes(
    input_mint="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",  # USDC

    output_mint="So11111111111111111111111111111111111111112",  # Wrapped SOL

    amount=10_000_000  # Amount in lamports (10 USDC with 6 decimals)

)

best_route = routes[0]
print(f"Best route traverses {len(best_route['marketInfos'])} pools")

```

This function internally calls `ultra_tools.get_routes` and returns routes ordered by price efficiency.

### Validating Prices Before Execution

Verify slippage and expected output before committing capital.

```python
from autohedge.tools.jupiter_price import get_price

price_info = get_price(best_route)
expected_output = price_info['outAmount']
slippage = price_info['priceImpactPct'] * 100

print(f"Expected output: {expected_output} lamports")
print(f"Slippage: {slippage:.2f}%")

```

### Executing Swaps via the Ultra API

Submit the finalized transaction payload to Jupiter for on-chain execution.

```python
from autohedge.tools.ultra_tools import execute_swap

swap_payload = {
    "route": best_route,
    "userPublicKey": "YOUR_WALLET_PUBLIC_KEY",
    "slippageBps": 50,  # 0.5% slippage tolerance

    "feeBps": 5,        # Optional protocol fee

    "computeUnitPriceMicroLamports": 0,
}

signed_tx = execute_swap(swap_payload)

# Returns base64-encoded transaction for RPC submission

```

### Complete Hedge Workflow

The worker-level abstraction handles the entire pipeline in a single call.

```python
from autohedge.workers import hedge_sol_usdc

# Execute full hedge: route discovery, validation, and swap execution

hedge_sol_usdc(amount_usdc=10_000_000)  # 10 USDC

```

## Configuration and Environment Security

The integration relies on [`autohedge/env_loader.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/env_loader.py) to manage sensitive configuration. Required environment variables include:

- `JUPITER_API_KEY`: Authenticates requests to Jupiter Ultra (optional but recommended for production)
- `SOLANA_RPC_URL`: Specifies the RPC node for transaction submission
- Wallet credentials: Managed securely via environment variables, never hardcoded in source files

All HTTP interactions include timeout handling (typically 30 seconds) and retry logic with exponential backoff to accommodate Solana network variability. The modular architecture allows developers to swap the Jupiter Ultra client for alternative implementations by modifying only [`ultra_tools.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/ultra_tools.py) without affecting the higher-level hedging logic.

## Summary

- **AutoHedge** integrates with Jupiter Ultra through [`autohedge/tools/ultra_tools.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/tools/ultra_tools.py), which provides authenticated HTTP access to route, price, and swap endpoints.
- **Route discovery** is handled by [`jupiter_search.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/jupiter_search.py), optimizing multi-hop paths across Solana DEXs.
- **Price validation** occurs in [`jupiter_price.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/jupiter_price.py), filtering trades based on real-time slippage metrics.
- **Execution orchestration** in [`workers.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/workers.py) sequences these operations and manages on-chain transaction submission.
- The architecture uses async HTTP clients with robust error handling and environment-based API key management for secure, high-frequency trading.

## Frequently Asked Questions

### What specific Jupiter API endpoint does AutoHedge use for swap execution?

AutoHedge targets the Jupiter Ultra API v4, specifically the `/v4/swap` endpoint. The `execute_swap` function in [`autohedge/tools/ultra_tools.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/tools/ultra_tools.py) constructs a POST request to this endpoint, passing route data and user parameters, and receives a base64-encoded Solana transaction in response.

### How does AutoHedge handle authentication with Jupiter's API?

The system loads a `JUPITER_API_KEY` from environment variables via [`autohedge/env_loader.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/env_loader.py). When present, [`ultra_tools.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/ultra_tools.py) injects this key into the `x-api-key` header of all HTTP requests. While the Jupiter Ultra API permits unauthenticated requests, the API key is required for higher rate limits and guaranteed service availability.

### Can the AutoHedge Jupiter integration handle arbitrary Solana tokens?

Yes. The `get_routes` function in [`autohedge/tools/jupiter_search.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/tools/jupiter_search.py) accepts any valid Solana mint addresses as `input_mint` and `output_mint` parameters. As long as Jupiter supports the token pair, the integration will discover routes and execute swaps accordingly, making it suitable for hedging strategies involving SPL tokens beyond SOL and USDC.

### What safeguards prevent AutoHedge from executing trades with excessive slippage?

The [`jupiter_price.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/jupiter_price.py) module analyzes the `priceImpactPct` field returned by Jupiter's price endpoint. If the calculated slippage exceeds the `slippageBps` threshold defined in the swap payload (defaulting to 50 basis points or 0.5%), the worker in [`workers.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/workers.py) aborts the transaction before calling `execute_swap`, ensuring unfavorable market conditions do not trigger capital loss.