---
title: "How to Buy TRON Energy with Code: The TronSave SDK (Node.js, Python & More)"
description: Buy TRON energy programmatically with the TronSave SDK — Node.js, Python, Rust, Java and PHP. Estimate, buy and track energy orders from your backend.
url: https://blog.tronsave.io/buy-tron-energy-with-code-tronsave-sdk/
canonical: https://blog.tronsave.io/buy-tron-energy-with-code-tronsave-sdk/
lang: en-US
datePublished: 2026-07-12T05:20:31+00:00
dateModified: 2026-11-07T00:00:00+00:00
author: TronSave
publisher: TronSave (https://tronsave.io/)
categories:
  - Tron Guidelines
keywords: tron energy sdk
translations:
  ru: https://blog.tronsave.io/ru/kupit-energiyu-tron-cherez-kod-tronsave-sdk/
  es: https://blog.tronsave.io/es/comprar-energia-tron-con-codigo-sdk-tronsave/
  pt: https://blog.tronsave.io/pt/comprar-energia-tron-com-codigo-sdk-tronsave/
  zh: https://blog.tronsave.io/zh/tronsave-sdk-daima-goumai-bochang-nengliang/
  de: https://blog.tronsave.io/de/tron-energie-per-code-kaufen-tronsave-sdk/
---

# How to Buy TRON Energy with Code: The TronSave SDK (Node.js, Python & More)

If your app, exchange, or bot sends USDT (TRC-20) at scale, you don’t want to buy **energy** by hand. The official **TronSave SDK** lets you estimate, buy, extend and track energy orders straight from your backend — in **Node.js, Python, Rust, Java or PHP**. This guide gets you from install to your first on-chain energy order.

## The SDKs

All SDKs target the **v2 API** and wrap the same endpoints, so you get the same operations in every language:

| Language | Package | Install | Requires |
| --- | --- | --- | --- |
| TypeScript / JS | `tronsave-sdk` | `npm install tronsave-sdk` | Node.js 18+ |
| Python | `tronsave` | `pip install tronsave` | Python 3.9+ |
| Rust | `tronsave` | `cargo add tronsave` | — |
| Java | `io.tronsave:sdk` | Maven / Gradle | — |
| PHP | `tronsave/sdk` | `composer require tronsave/sdk` | PHP 8.1+ |

The Rust, Python, Java and PHP packages are all at **2.0.0**. For Java, the coordinates are `io.tronsave:sdk:2.0.0` — add it to `pom.xml` as a dependency or to `build.gradle` as `implementation 'io.tronsave:sdk:2.0.0'`.

## What every SDK covers

The surface is deliberately small. Whichever language you pick, you get the same seven operations:

-   **Estimate Buy Resource** — price a purchase before you commit to it.
-   **Buy Resource** — place the order for Energy or Bandwidth; returns an order ID.
-   **Get Order / Get Orders** — fetch one order’s status, or your order history.
-   **Get Order Book** — read live supply as price levels, cheapest first.
-   **Get User Info** — internal account balance and deposit address.
-   **Get Extendable Delegates** — list delegations that are eligible to be renewed.
-   **Extend Request** — renew an existing delegation instead of buying a fresh order.

That last pair matters more than it looks. If a receiver already has energy delegated and you just need it to last longer, extending is the correct call — see the [Extend feature guide](https://blog.tronsave.io/extend-feature-extend-top-up-energy-without-ever-worrying-about-reclaim/).

## Quickstart (Node.js)

The fastest route is the API-key flow: create an SDK instance, estimate the cost, then place the order. Grab an API key from the [TronSave dashboard](https://tronsave.io/market) (see [Authentication](https://docs.tronsave.io/developers/authentication)).

```
import { TronsaveSDK } from "tronsave-sdk";

const main = async () => {
  const sdk = new TronsaveSDK({ network: "mainnet", apiKey: "your_api_key" });

  const userInfo = await sdk.getUserInfo();

  // Estimate cost for 65,000 ENERGY for 1 hour (one USDT transfer)
  const estimate = await sdk.estimateBuyResource({
    receiver: "TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    resourceType: "ENERGY",
    durationSec: 3600,
    resourceAmount: 65000,
  });
  if (estimate.estimateTrx > Number(userInfo.balance)) throw new Error("Insufficient balance");

  const { orderId } = await sdk.buyResource({
    receiver: "TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    resourceType: "ENERGY",
    durationSec: 3600,
    resourceAmount: 65000,
  });

  await new Promise((r) => setTimeout(r, 5000)); // wait ~5s to fill
  const order = await sdk.getOrder(orderId);
  console.log(order.fulfilledPercent < 100 ? "Not filled" : "Filled");
};

main();
```

*Tip: use `network: "testnet"` (Nile) to develop with no real TRX, then switch to `"mainnet"` for production.*

Two details worth knowing before you run it. `userInfo.balance` comes back in **SUN** as a string — 1 TRX is 1,000,000 SUN — which is why the comparison casts it. And `durationSec` is optional: leave it out and the order defaults to 259,200 seconds, or 3 days.

## The same task in Python

The Python package installs with `pip install tronsave` and exposes the same estimate → buy → track flow; per-language method signatures live in the [SDK reference](https://docs.tronsave.io/developers/sdk). If you'd rather see exactly which HTTP calls are being made underneath, here is the identical job — estimate, buy, then poll — written against the raw v2 endpoints:

```
import time, requests

API = "https://api.tronsave.io"          # testnet: https://api-dev.tronsave.io
HEADERS = {"apikey": "your_api_key", "Content-Type": "application/json"}
ORDER = {
    "receiver": "TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "resourceType": "ENERGY",
    "resourceAmount": 65000,
    "durationSec": 3600,
    "unitPrice": "MEDIUM",
}

estimate = requests.post(f"{API}/v2/estimate-buy-resource", json=ORDER).json()["data"]
print(estimate["estimateTrx"] / 1e6, "TRX", estimate["availableResource"], "available")

order = requests.post(f"{API}/v2/buy-resource", headers=HEADERS,
                      json={**ORDER, "options": {"allowPartialFill": True,
                                                 "maxPriceAccepted": 100}}).json()
order_id = order["data"]["orderId"]

time.sleep(5)
detail = requests.get(f"{API}/v2/order/{order_id}", headers=HEADERS).json()["data"]
print("Filled" if detail["fulfilledPercent"] == 100 else "Not filled")
```

Same three steps, same field names, same response envelope. The SDK's value is typing and retries, not a different API — so pick whichever your stack prefers. For a fuller Python script with order-book sizing and error branches, see [how to buy TRON energy in Python](https://blog.tronsave.io/how-to-buy-tron-energy-in-python/).

## Estimate before you buy

The estimate call is worth a paragraph of its own because its response tells you two separate things. `estimateTrx` is the cost in SUN. `availableResource` is how much the market can actually supply right now. If `availableResource` comes back lower than the `resourceAmount` you asked for, the order cannot fill completely at that moment — and you decide what to do about it through `options`: `allowPartialFill: true` to take what's there, or `onlyCreateWhenFulfilled: true` to refuse anything less than a full match. For retry-heavy bots, `preventDuplicateIncompleteOrders: true` stops a repeated call from stacking identical open orders.

## Errors and limits

Endpoints allow **15 requests per second**; exceeding that returns HTTP 429 with `"Rate limit reached"`, and a simple 1s/2s/4s backoff is enough. Application errors arrive as `error: true` with a machine-readable code inside `message` — `INVALID_API_KEY`, `INTERNAL_BALANCE_ACCOUNT_TOO_LOW`, `PRICE_EXCEED_MAX_PRICE_REQUIRED`, `CANNOT_FULFILLED`. Branch on the code; the wording can change.

## Driving TronSave from an AI agent

If your integration is an agent rather than a service, TronSave also publishes an MCP server, hosted at `https://mcp.tronsave.io/mcp` over Streamable HTTP (with `https://mcp.tronsave.io/testnet/mcp` for the testnet). It exposes 53 MCP tools (server version 1.3.0, November 2026) — `tronsave_estimate_buy_resource`, `tronsave_list_order_books`, `tronsave_internal_order_create` and the rest — with API-key or wallet-signature sessions. Point any MCP-compatible client at the endpoint; our [guide to the TronSave MCP server](https://blog.tronsave.io/tronsave-mcp-server-ai-agent-tron-energy/) walks through login, the two tool families, and the safety model.

Prefer raw HTTP? The SDKs wrap the same endpoints in the [API](https://api.tronsave.io) — see our [API automation guide](https://blog.tronsave.io/automate-buy-tron-energy-with-api-guide/), the breakdown of [TronSave order types](https://blog.tronsave.io/tronsave-order-types-explained/), and, for high volume, [buying energy in bulk](https://blog.tronsave.io/buy-tron-energy-in-bulk-for-high-volume-usdt/).

## FAQ

**Do I need an API key?**  
The API-key flow is the simplest; you can also sign with a private key. Get a key from the [dashboard](https://tronsave.io/market). The difference is custody: an API key spends from a prefunded TronSave internal account, while the signed-transaction flow pays from your own wallet on every purchase and needs TronWeb.

**Which languages are supported?**  
Node.js/TypeScript, Python, Rust, Java and PHP — all on the v2 API. Language-specific walkthroughs are available for [Python](https://blog.tronsave.io/how-to-buy-tron-energy-in-python/), [Java](https://blog.tronsave.io/how-to-buy-tron-energy-in-java-sdk-guide/), [PHP](https://blog.tronsave.io/how-to-buy-tron-energy-in-php-sdk-guide/), and [Rust](https://blog.tronsave.io/how-to-buy-tron-energy-in-rust-sdk-guide/).

**How much energy per USDT transfer?**  
About 65,000 (≈130,000 if the recipient has never held USDT). More detail in [how much energy a USDT transfer needs](https://blog.tronsave.io/how-much-trx-is-needed-to-send-usdt/).

**Can I test without spending real TRX?**  
Yes. Set `network: "testnet"` (or point the base URL at `https://api-dev.tronsave.io`) to run against Nile. Keys, balances and orders are separate per environment, so issue a Nile key at `testnet.tronsave.io` — a mainnet key will be rejected. Shasta is not supported.

**Start building:** read the [TronSave docs](https://docs.tronsave.io) and grab an API key on the [market dashboard](https://tronsave.io/market).

**Python dev?** See the language-specific walkthrough: [how to buy TRON energy in Python](https://blog.tronsave.io/how-to-buy-tron-energy-in-python/) (full runnable script).
