# 购买能源

要使用此功能，您必须拥有API密钥。请[在此处](/chinese/developer/get-api-key.md)了解如何获取我们的API密钥

[**TronSave 使用API密钥购买**](https://www.postman.com/tronsave/workspace/tronsave/request/29749953-add62099-655d-4f62-88f7-33423b4d70e8)

## 通过API密钥创建新的购买能源订单

<mark style="color:green;">`POST`</mark> `https://api.tronsave.io/v0/internal-buy-energy`

通过[API](/chinese/developer/get-api-key.md)密钥创建新的购买能源订单

速率限制 (Rate limit): 每1秒15个请求。

#### Headers

| Name                                     | Type   | Description            |
| ---------------------------------------- | ------ | ---------------------- |
| apikey<mark style="color:red;">\*</mark> | String | Tronsave API密钥，用于内部帐户。 |

#### Request Body

| Name                                                   | Type    | Description                                                                                                                                                                                                                                                    |
| ------------------------------------------------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| resource\_type<mark style="color:red;">\*</mark>       | String  | "ENERGY"                                                                                                                                                                                                                                                       |
| buy\_energy\_type<mark style="color:red;">\*</mark>    | String  | <p>"FAST"：如果市场准备填满 = 100%，则 "FAST" = "MEDIUM"。如果市场准备填满 < 100%，则 "FAST" = "MEDIUM" + 10。如果市场准备填满 = 0%，则 "FAST" = "SLOW" + 20。<br><br>"MEDIUM"：这个订单的最大市场填充的最低价格。如果市场准备填满 = 0%，"MEDIUM" = "SLOW" + 10。<br><br>"SLOW"：此订单可以设置的最低价格。<br><br>如果价格是数字，则价格单位等于SUN。</p> |
| amount<mark style="color:red;">\*</mark>               | Number  | 想要购买的资源量                                                                                                                                                                                                                                                       |
| allow\_partial\_fill<mark style="color:red;">\*</mark> | Boolean | 如果这个值为真，则订单可以从多个委托者那里填充。如果这个值为假，订单将填充困难一些。能源数量大于200,000的订单可以设置这个参数。                                                                                                                                                                                            |
| target\_address<mark style="color:red;">\*</mark>      | String  | 接收资源的地址                                                                                                                                                                                                                                                        |
| duration\_millisec                                     | Number  | 订单持续时间（毫秒）。默认值：259200000（3天）。                                                                                                                                                                                                                                  |
| sponsor                                                | String  | 赞助商代码                                                                                                                                                                                                                                                          |
| only\_create\_when\_fulfilled                          | Boolean | <p>\[true] => 订单只有在能够完成时才会创建 <br>\[false] => 即使订单无法完成也会创建<br>默认值: false</p>                                                                                                                                                                                    |
| max\_price\_accepted                                   | Number  | 只有当预估价格低于此值时才会创建订单。                                                                                                                                                                                                                                            |
| add\_order\_incomplete                                 | Boolean | <p>\[true] => 订单只有在订单列表中没有相同参数的未完成订单时才会创建 <br>\[false] => 即使订单列表中有相同参数的未完成订单，订单也会创建<br>默认值: false</p>                                                                                                                                                          |

{% tabs %}
{% tab title="200: OK 成功 (Success)" %}
如果成功，返回订单ID。

```javascript
{ 
    "order_id": string,
    "requester": string, // 表示订单拥有者的地址 
    "target": string, // 接收资源的地址 
    "resource_amount": number, // 资源数量 
    "resource_type": string, // 资源类型是 "ENERGY" 
    "remain_amount": number, // 系统可匹配的剩余数量 
    "price": number, // 价格单位为 sun 
    "duration": number, // 租赁时长，时长单位为秒 
    "allow_partial_fill": boolean, // 是否允许部分完成订单 
    "payout_amount": number, // 该订单的总支付金额 
    "fulfilled_percent": number, // 显示订单完成进度的百分比，0-100 
}
```

{% endtab %}

{% tab title="400: Bad Request 无效的参数 (Invalid params)" %}

```javascript
{
"MISSING_PARAMS": "在请求体中缺少一些参数",
"INVALID_PARAMS": "一些参数无效",
"ORDER_BUY_ENERGY_AMOUNT_TOO_SMALL": "订单金额太小，不得少于40000",
"CANNOT_SET_PARTIAL_FULFILLED": "订单金额小于100000时无法设置部分完成",
"INTERNAL_ACCOUNT_NOT_FOUND": "内部帐户不存在",
"ORDER_BUY_ENERGY_CAN_NOT_CREATE": "创建订单时出现错误，无法创建，请稍后再试",
"INTERNAL_BALANCE_ACCOUNT_TOO_LOW": "余额不足"
}

```

{% endtab %}

{% tab title="401: Unauthorized 无效的API密钥 (Invalid API key)" %}

```javascript
{
"API_KEY_REQUIRED": "请求头中缺少API密钥",
"INVALID_API_KEY": "API密钥不正确"
}
```

{% endtab %}

{% tab title="429: Too Many Requests 已达到速率限制 (Rate limit reached)" %}

```javascript
{
"RATE_LIMIT": "已达到速率限制"
}
```

{% endtab %}
{% endtabs %}

**例子&#x20;*****(Example)***

{% tabs %}
{% tab title="Body" %}

```javascript
{
    "resource_type": "ENERGY",
    "buy_energy_type": "FAST",
    "amount": 100000,
    "allow_partial_fill": true,
    "target_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
    "duration_millisec":86400000, //Optional
    "sponsor": <YOUR SPONSOR REF CODE> //Optional
    "only_create_when_fulfilled": false,
    "max_price_accepted": 100,
    "add_order_incomplete": false
}
```

{% endtab %}

{% tab title="Headers" %}

```javascript
{
  "apikey": <YOUR_API_KEY>
}
```

{% endtab %}

{% tab title="Success Response" %}

```javascript
{
      "order_id": "651d2306e55c073f6ca0992e",
      "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
      "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
      "resource_amount": 100000,
      "resource_type": "ENERGY",
      "remain_amount": 0,
      "price": 67.5,
      "duration": 3600,
      "allow_partial_fill": true,
      "payout_amount": 6750000,
      "fulfilled_percent": 100
}
```

{% endtab %}
{% endtabs %}

*Example Code*

{% tabs %}
{% tab title="Javascript" %}

```javascript
const BuyEnergy = async (api_key, target_address, amount, duration_ms) => {
    const url = `https://api.tronsave.io/v0/internal-buy-energy`
    //see more at https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/buy-energy
    const body = {
        "resource_type": "ENERGY",
        "buy_energy_type": "MEDIUM", //price in sun or "SLOW"|"MEDIUM"|"FAST"
        "amount": amount, //Amount of resource want to buy
        "allow_partial_fill": true,
        "target_address": target_address,
        "duration_millisec": duration_ms, //order duration in milli sec. Default: 259200000 (3 days)
        "only_create_when_fulfilled": false,
        "max_price_accepted": 100,
        "add_order_incomplete": false
    }
    const data = await fetch(url, {
        method: "POST",
        headers: {
            'apikey': api_key,
            "content-type": "application/json",
        },
        body: JSON.stringify(body)
    })
    const response = await data.json()
    /**
     * Example response 
     * @link  https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/buy-energy
   {
      "order_id": "651d2306e55c073f6ca0992e",
      "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
      "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
      "resource_amount": 100000,
      "resource_type": "ENERGY",
      "remain_amount": 0,
      "price": 67.5,
      "duration": 3600,
      "allow_partial_fill": true,
      "payout_amount": 6750000,
      "fulfilled_percent": 100
}
     */
    return response
}
```

{% endtab %}

{% tab title="cURL" %}

```
curl --location 'https://api.tronsave.io/v0/internal-buy-energy' \
--header 'apikey: {{apikey}}' \
--data '{
    "resource_type": "ENERGY",
    "amount": 40000,
    "buy_energy_type": "MEDIUM", 
    "duration_millisec": 3600000, 
    "target_address": "{{yourAddress}}", 
    "allow_partial_fill": false, 
    "only_create_when_fulfilled": false,
    "max_price_accepted": 100,
    "add_order_incomplete": false
}
'
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.tronsave.io/chinese/developer/rest-api-v0/buy-on-rest-api/use-api-key/buy-energy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
