# Create order

To use this feature, you must have the API key. Read [here](/developer/get-api-key.md) to view how to get our API key

## [**Buy with API Key (Postman)**](https://www.postman.com/tronsave/tronsave/folder/y222ywm/buy-with-apikey)

## Create a new order by API key

<mark style="color:orange;">`POST`</mark> `https://api.tronsave.io/v2/buy-resource`

Create a new buy energy order by [API key](/developer/get-api-key.md)

Rate limi&#x74;***: 15** requests per **1** second*

#### Headers

<table><thead><tr><th width="156">Name</th><th width="94">Type</th><th>Description</th></tr></thead><tbody><tr><td>apikey<mark style="color:red;">*</mark></td><td>String</td><td>Tronsave api key that present for internal account</td></tr></tbody></table>

#### Request Body

<table><thead><tr><th width="206">Field</th><th width="130">Type</th><th width="398">Description</th></tr></thead><tbody><tr><td>resourceType</td><td>String</td><td>"ENERGY" or "BANDWIDTH", default: ENERGY</td></tr><tr><td>unitPrice</td><td>Number, String</td><td><p>"FAST", "MEDIUM", "SLOW", or a number. <strong>Default: "MEDIUM"</strong></p><p><br>-"FAST": If the market is ready to fill = 100%,  FAST = MEDIUM. If the market is ready to fill &#x3C; 100%,  FAST = MEDIUM + 10. If market ready to fill = 0%,  FAST = SLOW + 20.</p><p></p><p>-"MEDIUM":  The lowest price for the maximum market fill for this order. If market is ready to fill = 0%,  MEDIUM = SLOW + 10.</p><p></p><p>-"SLOW": The lowest price that can be set for this order.</p><p></p><p>-If the price is a number, the price unit is equal to SUN</p></td></tr><tr><td>resourceAmount<mark style="color:red;">*</mark></td><td>Number</td><td>The number of resources.</td></tr><tr><td>receiver<mark style="color:red;">*</mark></td><td>String</td><td>Resource receiving address</td></tr><tr><td>durationSec</td><td>Number</td><td>The duration of the bought resource, time unit, is in seconds. <strong>Default:</strong> 259200 (3 days).</td></tr><tr><td>sponsor</td><td>String</td><td>sponsor code</td></tr><tr><td>options</td><td>Object</td><td>optional</td></tr><tr><td>options.allowPartialFill</td><td>Boolean</td><td>Allow the order to be filled partially or not</td></tr><tr><td>options.onlyCreateWhenFulfilled</td><td>Boolean</td><td><p>[true]=> order only creates when it can be fulfilled</p><p>[false]=> order will create even if it can not be fulfilled</p><p>Default value: false</p></td></tr><tr><td>options.maxPriceAccepted</td><td>Number</td><td>Only create order when the estimate price less than this value.</td></tr><tr><td>options.preventDuplicateIncompleteOrders</td><td>Boolean</td><td><p>[true]=> Only create if no <strong>uncompleted order</strong> with the same parameters exists.</p><p>[false]=> Always create a new order, regardless of existing unfinished ones.</p><p>Default value: <strong>false</strong></p></td></tr><tr><td>options.minResourceDelegateRequiredAmount</td><td>Number</td><td>The minimum resource amount delegated by a single provider.</td></tr></tbody></table>

{% tabs %}
{% tab title="201: OK Success" %}
Return the order ID if successful

```json
{
    "error": false,
    "message": "Success",
    "data": {
        "orderId": "6818426a65fa8ea36d119d2c"
    }
}
```

{% endtab %}

{% tab title="400: Bad Request Invalid params" %}

```json
{
    "MISSING_PARAMS": "Missing some params in body",
    "INVALID_PARAMS": "Some params are invalid",
    "MIN_PRICE_INVALID": "minPrice is less than the system's minimum price or not in the correct format."
    "INTERNAL_ACCOUNT_NOT_FOUND": "internal account does not exist",
    "INTERNAL_BALANCE_ACCOUNT_TOO_LOW": "Balance is not enough",
    "CANNOT_FULFILLED": "The order requires an immediate full match, but the system cannot fulfill 100% of it.",
    "MUST_BE_WAIT_PREVIOUS_ORDER_FILLED": "A pending order with the same parameters already exists in the system.",
    "PRICE_EXCEED_MAX_PRICE_REQUIRED": "The price of the order exceeds the maximum price accepted."
}
```

{% endtab %}

{% tab title="401: Unauthorized Invalid api key" %}

```json
{
    "API_KEY_REQUIRED": "Missing api key in headers",
    "INVALID_API_KEY": "api key not correct"
}
```

{% endtab %}

{% tab title="429: Too Many Requests Rate limit reached" %}

```json
{
    "RATE_LIMIT": "Rate limit reached",
}
```

{% endtab %}
{% endtabs %}

*Example*&#x20;

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

```json
{
    "resourceType": "ENERGY",
    "receiver": "TFFbwz3UpmgaPT4UudwsxbiJf63t777777",
    "durationSec": 3600,
    "resourceAmount": 32000,
    "unitPrice": "MEDIUM",
    "options": {
        "allowPartialFill": true,
        "onlyCreateWhenFulfilled": true,
        "preventDuplicateIncompleteOrders": false,
        "maxPriceAccepted": 100,
        "minResourceDelegateRequiredAmount": 100000
    }
}
```

{% endtab %}

{% tab title="Headers" %}

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

{% endtab %}

{% tab title="Success Response" %}

```json
{
    "error": false,
    "message": "Success",
    "data": {
        "orderId": "6818426a65fa8ea36d119d2c"
    }
}
```

{% endtab %}
{% endtabs %}

*Example Code*

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

```javascript
const BuyResource = async (apiKey, receiverAddress, resourceAmount, durationSec, maxPriceAccepted) => {
    const url = `${TRONSAVE_API_URL}/v2/buy-resource`
    const body = {
        resourceType: RESOURCE_TYPE,
        unitPrice: "MEDIUM", //price in sun or "SLOW"|"MEDIUM"|"FAST"
        resourceAmount, //Amount of resource wanted to buy
        receiver: receiverAddress,
        durationSec, //order duration in sec. Default: 259200 (3 days)
        options: {
            allowPartialFill: true,
            onlyCreateWhenFulfilled: false,
            maxPriceAccepted,
        }
    }
    const data = await fetch(url, {
        method: "POST",
        headers: {
            'apikey': apiKey,
            "content-type": "application/json",
        },
        body: JSON.stringify(body)
    })
    const response = await data.json()
    /**
     * Example response
     * {
     *     "error": false,
     *     "message": "Success",
     *     "data": {
     *         "orderId": "6809fdb7b9...a41d726fd"
     *     }
     * }
     */
    return response
}
```

{% endtab %}

{% tab title="PHP" %}

```php
function buyResource($apiKey, $receiverAddress, $resourceAmount, $durationSec, $maxPriceAccepted) {
    $url = TRONSAVE_API_URL . "/v2/buy-resource";
    $body = [
        'resourceType' => RESOURCE_TYPE,
        'unitPrice' => "MEDIUM",
        'resourceAmount' => $resourceAmount,
        'receiver' => $receiverAddress,
        'durationSec' => $durationSec,
        'options' => [
            'allowPartialFill' => true,
            'onlyCreateWhenFulfilled' => false,
            'maxPriceAccepted' => $maxPriceAccepted,
        ]
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($body),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'apikey: ' . $apiKey,
            'Content-Type: application/json'
        ]
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}
```

{% endtab %}

{% tab title="Python" %}

```python
def buy_resource(amount: int, duration_sec: int, max_price_accepted: int) -> Dict[str, Any]:
    """Buy resource"""
    url = f"{TRONSAVE_API_URL}/v2/buy-resource"
    headers = {
        'apikey': API_KEY,
        'Content-Type': 'application/json'
    }
    
    body = {
        'resourceType': RESOURCE_TYPE,
        'unitPrice': "MEDIUM",
        'amount': amount,
        'receiver': RECEIVER_ADDRESS,
        'durationSec': duration_sec,
        'options': {
            'allowPartialFill': True,
            'onlyCreateWhenFulfilled': False,
            'maxPriceAccepted': max_price_accepted,
        }
    }
    
    response = requests.post(url, headers=headers, json=body)
    return response.json()
```

{% endtab %}
{% endtabs %}

Get detailed orders [here](/developer/buy-resources-v2/use-api-key/get-one-order-details.md)


---

# 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/developer/buy-resources-v2/use-api-key/create-order.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.
