# How to Generate a Swap Quote and Execute a Trade Using AutoHedge's UltraTools

> Learn to generate swap quotes and execute trades with AutoHedge's UltraTools. This guide covers using get_order() for quotes and execute_trade() for signed transactions via the Jupiter Ultra API.

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

---

**AutoHedge's UltraTools module wraps the Jupiter Ultra API to provide a stateless Python interface where `get_order()` generates unsigned swap quotes and `execute_trade()` cryptographically signs and submits transactions using your Solana private key.**

The **UltraTools** module in the AutoHedge repository eliminates boilerplate when interacting with Jupiter's Ultra swap infrastructure. Located at [`autohedge/tools/ultra_tools.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/tools/ultra_tools.py), this toolkit enables programmatic token swaps on Solana by handling transaction construction, signing, and execution against Jupiter's specialized endpoints. The implementation relies on environment-based configuration and supports concurrent workflows without maintaining mutable state.

## Understanding the UltraTools Architecture

The module follows a stateless design pattern that makes it safe for use within AutoHedge's worker pools. Each function call constructs independent HTTP requests using **httpx**, with specific timeouts: 15 seconds for quotes, 30 seconds for execution, and 10 seconds for balance queries. Error handling utilizes **loguru** for logging before re-raising exceptions to callers.

### Core API Functions

UltraTools exposes three primary functions for swap operations:

- **`get_order()`** - Requests an unsigned swap transaction from `https://api.jup.ag/ultra/v1/order`, returning a base64-encoded transaction and `requestId`
- **`execute_trade()`** - Decodes the unsigned transaction, signs it with your Solana Keypair, and POSTs to `https://api.jup.ag/ultra/v1/execute`
- **`get_holdings()`** - Retrieves current token balances via `https://api.jup.ag/ultra/v1/holdings/<address>`

### Environment Configuration

Two critical environment variables configure the module:

1. **`SOLANA_PRIVATE_KEY`** (required) - A base58-encoded private key parsed by `_get_keypair()` into a `solders.keypair.Keypair`, providing both the wallet's public key (via `_get_wallet_pubkey()`) and transaction signing capability
2. **`JUPITER_API_KEY`** (optional) - Loaded by `_headers()` and attached as the `x-api-key` header for authenticated requests

## Generating a Swap Quote with get_order

To request a quote, call `get_order()` with the input mint, output mint, and amount in the token's smallest denomination. The function sends a GET request to Jupiter's order endpoint and returns JSON containing the unsigned transaction and metadata.

```python
from autohedge.tools.ultra_tools import get_order
import json

# Request quote: 0.01 SOL (10000000 lamports) to USDC

order_json = get_order(
    input_mint="So11111111111111111111111111111111111111112",   # SOL

    output_mint="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",  # USDC

    amount="10000000"
)

order = json.loads(order_json)
unsigned_tx = order["transaction"]      # Base64-encoded VersionedTransaction

request_id = order["requestId"]         # Unique identifier for this quote

wallet_pubkey = order["taker"]          # Your wallet address

```

The response includes the `taker` field, which represents the public key derived from your `SOLANA_PRIVATE_KEY`.

## Executing the Trade with execute_trade

The `execute_trade()` function handles cryptographic signing and submission. It decodes the base64 transaction into a **VersionedTransaction** (supporting V0 or V1 formats), extracts message bytes using `to_bytes_versioned()`, signs them with your loaded Keypair, and submits the signed payload to Jupiter's execute endpoint.

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

# Sign and submit the unsigned transaction

execution_json = execute_trade(unsigned_tx, request_id)
execution = json.loads(execution_json)

print("Status:", execution["status"])           # "success" or "error"

print("Signatures:", execution["signatures"])   # On-chain transaction signatures

print("Slot:", execution["slot"])               # Confirmation slot

print("Swap details:", execution.get("swap"))

```

The function returns execution status, confirmation details, and error information if the transaction fails.

## Verifying Token Balances with get_holdings

After execution, verify your updated balances by calling `get_holdings()` with your wallet address:

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

holdings_json = get_holdings(wallet_pubkey)
holdings = json.loads(holdings_json)

sol_balance = holdings["uiAmount"]
usdc_balance = holdings["tokens"]["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]["uiAmount"]

print(f"SOL: {sol_balance}, USDC: {usdc_balance}")

```

## Complete Implementation Workflow

Combine all functions to execute a complete swap pipeline:

```python
import json
from autohedge.tools.ultra_tools import get_order, execute_trade, get_holdings

def perform_swap(input_mint: str, output_mint: str, amount: str):
    """
    Execute a complete swap: quote -> execute -> verify.
    Returns execution result and updated balances.
    """
    # Step 1: Generate quote

    order_data = json.loads(get_order(input_mint, output_mint, amount))
    
    # Step 2: Sign and execute

    execution_data = json.loads(
        execute_trade(order_data["transaction"], order_data["requestId"])
    )
    
    if execution_data["status"] != "success":
        raise RuntimeError(f"Swap failed: {execution_data}")
    
    # Step 3: Check final balances

    balances = json.loads(get_holdings(order_data["taker"]))
    
    return execution_data, balances

# Example usage

execution, balances = perform_swap(
    "So11111111111111111111111111111111111111112",
    "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    "10000000"  # 0.01 SOL

)

```

## Summary

- **UltraTools** provides a stateless Python wrapper around Jupiter's Ultra API in [`autohedge/tools/ultra_tools.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/tools/ultra_tools.py)
- **`get_order()`** requests unsigned transactions from `https://api.jup.ag/ultra/v1/order` using your wallet's public key derived from `SOLANA_PRIVATE_KEY`
- **`execute_trade()`** handles **VersionedTransaction** decoding, message signing via `solders.keypair.Keypair`, and submission to the execute endpoint
- **`get_holdings()`** queries token balances with a 10-second timeout for post-trade verification
- The module requires `httpx` for HTTP transport, `loguru` for logging, and `solders` for Solana cryptographic operations

## Frequently Asked Questions

### What environment variables does UltraTools require?

You must set `SOLANA_PRIVATE_KEY` containing a base58-encoded Solana private key. Optionally, configure `JUPITER_API_KEY` to bypass API rate limits via authenticated requests. The `_get_keypair()` function parses the private key into a `solders.keypair.Keypair` for signing.

### How does execute_trade handle transaction signing?

The function decodes the base64 unsigned transaction, instantiates a **VersionedTransaction** object, extracts the message bytes using `to_bytes_versioned()`, signs the message with your Solana Keypair, reconstructs the signed transaction, and submits it to `https://api.jup.ag/ultra/v1/execute`.

### Can UltraTools handle concurrent swap requests?

Yes. The module implements a stateless design where each call builds fresh requests from environment variables and arguments, making it thread-safe for concurrent execution within AutoHedge's worker pools or async applications.

### What token amount format should I use with get_order?

Pass amounts as strings representing the smallest token denomination: lamports for SOL (1 SOL = 1,000,000,000 lamports) or raw units for SPL tokens. For example, use `"10000000"` to swap 0.01 SOL.