> For the complete documentation index, see [llms.txt](https://www.aevo.xyz/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.aevo.xyz/docs/api-reference/subaccounts/trading-with-subaccounts.md).

# Trading with a subaccount

This guide shows how to trade a subaccount through the API, end to end: place an order, read it back, cancel it, and do the same over the websocket.

## What you need

Subaccounts don't have API keys or signing keys of their own. You use the **main account's** credentials for everything, and name the subaccount on each request:

| You need                        | From                                                                                                                       | Used for                                              |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| Main account API key and secret | [API key setup](https://www.aevo.xyz/docs/api-reference/api-key-setup.md)                                                  | Authenticating every request                          |
| Main account signing key        | Enable Trading in the app, or [`POST /register`](https://www.aevo.xyz/docs/api-reference/urls/private-api/postregister.md) | Signing orders (the main wallet also works)           |
| The subaccount's address        | [`GET /subaccounts`](https://www.aevo.xyz/docs/api-reference/urls/private-api/getsubaccounts.md)                           | The `AEVO-SUBACCOUNT` header, and the order's `maker` |

Two rules make an order act on a subaccount:

1. **Select the subaccount** on the request: the `AEVO-SUBACCOUNT` header on REST, or `subaccount` when you authenticate on the websocket.
2. **Set `maker` to the subaccount's address** in the signed order, and sign with the main account's signing key.

If either is missing, the request acts on the main account instead, or is rejected.

## Step 1. Find your subaccount's address

Call [`GET /subaccounts`](https://www.aevo.xyz/docs/api-reference/urls/private-api/getsubaccounts.md) with the main account's key and **no** `AEVO-SUBACCOUNT` header:

```json
{
  "account": "0xYourMainAccountAddress",
  "max_subaccounts": 10,
  "subaccounts": [
    { "subaccount": "0xYourSubaccountAddress", "name": "Market Making", "archived": false, "balances": [], "positions": [] }
  ]
}
```

Use the `subaccount` value exactly as returned. It is checksummed (mixed case), and the header must match it exactly.

## Step 2. Sign requests for the subaccount

With signature (HMAC) authentication, the subaccount is part of what you sign. Append it as a **sixth** field:

```
message = apiKey,timestamp,httpMethod,path,body,subaccount
```

* `path` is the URL path **without** the query string. For `GET /orders?instrument_id=1` you sign `/orders`.
* `body` is the exact JSON string you send, or empty for a `GET`.
* Without a subaccount, it is the usual five-field message, so the same helper works for the main account.

If you authenticate with `AEVO-KEY` and `AEVO-SECRET` instead of a signature, just add the `AEVO-SUBACCOUNT` header. Nothing else changes.

## Step 3. Sign an order for the subaccount

Use the normal `Order` type (see [Signing Orders](https://www.aevo.xyz/docs/api-reference/signing-orders.md)) with **`maker` set to the subaccount's address**, and sign it with the **main account's signing key**. The subaccount's address is inside the signed order, so the signature can't be reused for any other account.

## Full example (REST)

```python
import json
import os
import random
import time
import hmac
import hashlib

import requests
from eth_account import Account
from eth_account.messages import encode_typed_data

BASE_URL = "https://api-testnet.aevo.xyz"
API_KEY = os.environ["AEVO_API_KEY"]          # main account
API_SECRET = os.environ["AEVO_API_SECRET"]    # main account
SIGNING_KEY = os.environ["AEVO_SIGNING_KEY"]  # main account signing key
SUBACCOUNT = "0xYourSubaccountAddress"        # from GET /subaccounts

# Testnet. Mainnet: {"name": "Aevo Mainnet", "version": "1", "chainId": 1}
DOMAIN = {"name": "Aevo Testnet", "version": "1", "chainId": 11155111}


def auth_headers(method, path, body="", subaccount=None):
    """HMAC headers. The subaccount, when given, is the sixth signed field."""
    timestamp = str(time.time_ns())
    fields = [API_KEY, timestamp, method.upper(), path.split("?")[0], body]
    if subaccount:
        fields.append(subaccount)
    signature = hmac.new(
        API_SECRET.encode(), ",".join(fields).encode(), hashlib.sha256
    ).hexdigest()
    headers = {
        "AEVO-KEY": API_KEY,
        "AEVO-TIMESTAMP": timestamp,
        "AEVO-SIGNATURE": signature,
        "Content-Type": "application/json",
    }
    if subaccount:
        headers["AEVO-SUBACCOUNT"] = subaccount
    return headers


def sign_order(maker, is_buy, limit_price, amount, instrument, salt, timestamp):
    """EIP-712 Order signed by the main signing key. limit_price and amount are 6-decimal integers."""
    typed = encode_typed_data(full_message={
        "types": {
            "EIP712Domain": [
                {"name": "name", "type": "string"},
                {"name": "version", "type": "string"},
                {"name": "chainId", "type": "uint256"},
            ],
            "Order": [
                {"name": "maker", "type": "address"},
                {"name": "isBuy", "type": "bool"},
                {"name": "limitPrice", "type": "uint256"},
                {"name": "amount", "type": "uint256"},
                {"name": "salt", "type": "uint256"},
                {"name": "instrument", "type": "uint256"},
                {"name": "timestamp", "type": "uint256"},
            ],
        },
        "primaryType": "Order",
        "domain": DOMAIN,
        "message": {
            "maker": maker, "isBuy": is_buy, "limitPrice": limit_price, "amount": amount,
            "salt": salt, "instrument": instrument, "timestamp": timestamp,
        },
    })
    return "0x" + Account.sign_message(typed, SIGNING_KEY).signature.hex()


# Place a limit buy of 1 contract at $2,000 on instrument 1, for the subaccount.
order = {
    "instrument": 1,
    "maker": SUBACCOUNT,             # the subaccount, not the main account
    "is_buy": True,
    "amount": str(1 * 10**6),        # 6 decimals
    "limit_price": str(2000 * 10**6),
    "salt": str(random.randint(0, 10**9)),
    "timestamp": str(int(time.time())),
}
order["signature"] = sign_order(
    order["maker"], order["is_buy"], int(order["limit_price"]), int(order["amount"]),
    order["instrument"], int(order["salt"]), int(order["timestamp"]),
)
body = json.dumps(order, separators=(",", ":"))
placed = requests.post(
    f"{BASE_URL}/orders", data=body,
    headers=auth_headers("POST", "/orders", body, SUBACCOUNT),
).json()
print("placed", placed)

# The subaccount's open orders and positions: same calls, same header.
print(requests.get(f"{BASE_URL}/orders", headers=auth_headers("GET", "/orders", "", SUBACCOUNT)).json())
print(requests.get(f"{BASE_URL}/positions", headers=auth_headers("GET", "/positions", "", SUBACCOUNT)).json())

# Cancel it.
path = f"/orders/{placed['order_id']}"
print(requests.delete(f"{BASE_URL}{path}", headers=auth_headers("DELETE", path, "", SUBACCOUNT)).json())

# Without the header, the same key acts on the main account.
print(requests.get(f"{BASE_URL}/account", headers=auth_headers("GET", "/account")).json())
```

Every private endpoint works the same way with the header, including `GET /account`, `GET /trade-history`, `POST /batch-orders`, `DELETE /orders-all`, RFQ quotes and the account settings endpoints (leverage, margin mode, portfolio margin).

## Full example (websocket)

A websocket connection acts as **one** account. Add `subaccount` when you authenticate, and every order, cancel and private channel on that connection is for the subaccount. Open one connection per account you trade.

```python
import asyncio
import json
import random
import time

import websockets

WS_URL = "wss://ws-testnet.aevo.xyz"


async def trade_subaccount():
    async with websockets.connect(WS_URL) as ws:
        # Bind this connection to the subaccount.
        await ws.send(json.dumps({
            "op": "auth",
            "data": {"key": API_KEY, "secret": API_SECRET, "subaccount": SUBACCOUNT},
        }))
        print(await ws.recv())

        # Private channels now stream the subaccount's data.
        await ws.send(json.dumps({"op": "subscribe", "data": ["orders", "fills"]}))
        print(await ws.recv())

        salt, timestamp = random.randint(0, 10**9), int(time.time())
        signature = sign_order(SUBACCOUNT, True, 2000 * 10**6, 1 * 10**6, 1, salt, timestamp)
        await ws.send(json.dumps({
            "op": "create_order",
            "id": 1,
            "data": {
                "instrument": "1",
                "maker": SUBACCOUNT,
                "is_buy": True,
                "amount": str(1 * 10**6),
                "limit_price": str(2000 * 10**6),
                "salt": str(salt),
                "timestamp": str(timestamp),
                "signature": signature,
            },
        }))
        print(await ws.recv())


asyncio.run(trade_subaccount())
```

To authenticate with a signature instead of the secret, add `subaccount` to the auth `data` and sign `apiKey,timestamp,ws,auth,,subaccount`. For per-message authentication, add `subaccount` to the message's `auth` object and sign `apiKey,timestamp,ws,op,data,subaccount`. See [Subaccounts](https://www.aevo.xyz/docs/api-reference/subaccounts.md#acting-as-a-subaccount-over-the-websocket).

## Trading several subaccounts at once

* **REST:** one set of credentials covers every subaccount. Change the `AEVO-SUBACCOUNT` header per request.
* **Websocket:** one connection per subaccount (and one for the main account if you trade it too), each authenticated with its own `subaccount` value.
* **Rate limits** are shared by the main account and all its subaccounts, so adding subaccounts doesn't add capacity. See [Rate Limits](https://www.aevo.xyz/docs/api-reference/rate-limits.md).
* **Your own accounts never trade against each other.** If an order would fill against the main account or another of its subaccounts, the incoming order is cancelled. See [Shared rules](https://www.aevo.xyz/docs/api-reference/subaccounts.md#shared-rules).

## Moving funds with the API

Trading uses the main account's keys, but a transfer **out of** a subaccount must be signed by the **subaccount's own key** (`Transfer` type, `account` = the subaccount). Re-derive it from the main wallet as described in [Creating subaccounts](https://www.aevo.xyz/docs/api-reference/subaccounts/creating-subaccounts.md), then call [`POST /transfer`](https://www.aevo.xyz/docs/api-reference/urls/private-api/posttransfer.md) with the `AEVO-SUBACCOUNT` header. A subaccount can only transfer to its main account or another of its subaccounts, and can never withdraw.

## Common errors

| Error                                | Cause                                                                                               | Fix                                                                    |
| ------------------------------------ | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| `SUBACCOUNT_NOT_FOUND`               | The header isn't one of this main account's active subaccounts, or its casing doesn't match         | Copy the address exactly from `GET /subaccounts`                       |
| `SUBACCOUNT_ARCHIVED`                | The subaccount is archived                                                                          | Use an active subaccount                                               |
| `INVALID_SIGNATURE` (on auth)        | The HMAC didn't include the subaccount as the sixth field, or signed the path with its query string | Sign `apiKey,timestamp,method,path,body,subaccount` with the bare path |
| `UNAUTHORIZED` (on `POST /orders`)   | The order's `maker` isn't the account the request acts on                                           | Set `maker` to the same subaccount as the `AEVO-SUBACCOUNT` header     |
| `ORDER_INVALID_SIGNATURE`            | The order wasn't signed by the main account's signing key or wallet                                 | Sign the order with the main signing key                               |
| `SUBACCOUNT_TRANSFER_OUTSIDE_FAMILY` | A transfer from or to a subaccount crossed families                                                 | Transfer only between the main account and its subaccounts             |
| `SUBACCOUNT_WITHDRAW_NOT_ALLOWED`    | Withdrawal from a subaccount                                                                        | Transfer to the main account, then withdraw                            |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://www.aevo.xyz/docs/api-reference/subaccounts/trading-with-subaccounts.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
