> ## Documentation Index
> Fetch the complete documentation index at: https://orderly.network/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# AI Integration Cheat Sheet

> A structured quick reference guide optimizing Orderly Network API integration for AI agents and human developers.

This cheat sheet consolidates the critical paths, cryptographic signature logic, and core API mappings for integrating with the Orderly Network. It serves as a high-signal index designed for both AI agents and human developers.

***

## 1. Terminology & Core Architecture

* **Builder ID (`broker_id`)**: The identifier assigned to your platform/Broker during onboarding. Must be passed in registration and key generation APIs.
* **Orderly Key**: An on-chain registered Ed25519 keypair. The private key resides locally and is used to sign all subsequent private API/WS requests, bypassing wallet signatures.
* **Strategy Vault vs. OmniVault**:
  * **Strategy Vault**: The underlying technical smart contract and CeFi clearing infrastructure.
  * **OmniVault**: The official protocol-level vault implementation built on top of this Strategy Vault infrastructure.

***

## 2. API Authentication Flow

Orderly uses two main layers of authentication:

1. **EIP-712/Ethereum Signature**: Used only for registration and registering your Orderly Key.
2. **Orderly Key (Ed25519 Signature)**: Used to sign all private REST and WebSocket messages.

### Request Headers for Authenticated Endpoints

Every private request must contain the following HTTP headers:

```http theme={null}
orderly-timestamp: <current_epoch_ms>
orderly-signer-id: <account_id>
orderly-key: <public_orderly_key_hex>
orderly-signature: <computed_signature_base64>
```

### Signature Generation Rule

The signature string is generated by concatenating the timestamp, the HTTP method, the path (including query parameters if they exist), and the request body:

```
SignatureMessage = orderly-timestamp + METHOD + PATH + (BODY_STRING if exists else "")
```

> \[!IMPORTANT]
>
> * The path must contain query parameters if they exist (e.g., `/v1/order?symbol=PERP_ETH_USDC`).
> * The generated signature must be encoded in **base64url (URL-safe Base64)** format.

***

## 3. Cryptographic Signature Implementations

Here are minimal implementations for signing Orderly API requests using an Ed25519 private key.

### TypeScript / Node.js

```typescript theme={null}
import { ed25519 } from "@noble/curves/ed25519";
import { base58 } from "@scure/base";

interface SignParams {
  method: "GET" | "POST" | "PUT" | "DELETE";
  path: string; // e.g., "/v1/order" (include query parameters if exists)
  body?: Record<string, any>;
  timestamp: number; // e.g., Date.now()
  orderlySecret: string; // base58-encoded Orderly private key
}

export function generateOrderlySignature({
  method,
  path,
  body,
  timestamp,
  orderlySecret
}: SignParams): string {
  const bodyStr = body ? JSON.stringify(body) : "";
  const message = `${timestamp}${method}${path}${bodyStr}`;

  const privateKey = base58.decode(orderlySecret);
  const signatureBytes = ed25519.sign(new TextEncoder().encode(message), privateKey);

  return Buffer.from(signatureBytes).toString("base64url");
}
```

### Python

```python theme={null}
import json
from base58 import b58decode
from base64 import urlsafe_b64encode
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

def generate_orderly_signature(method: str, path: str, body: dict, timestamp: int, orderly_secret: str) -> str:
    body_str = json.dumps(body) if body else ""
    # Format: timestamp + method + path + body
    message = f"{timestamp}{method}{path}{body_str}"

    # Decode base58 encoded private key
    private_key_bytes = b58decode(orderly_secret)
    private_key = Ed25519PrivateKey.from_private_bytes(private_key_bytes)

    # Sign and encode base64url (url-safe base64)
    signature = private_key.sign(message.encode('utf-8'))
    return urlsafe_b64encode(signature).decode('utf-8')
```

***

## 4. Core REST API Endpoints Reference

All private endpoints require private headers signed by your Orderly Key.

| Endpoint                     | Method   | Auth Level            | Key Input Parameters                                            | Purpose                                                    |
| :--------------------------- | :------- | :-------------------- | :-------------------------------------------------------------- | :--------------------------------------------------------- |
| `/v1/register_account`       | `POST`   | Public (Wallet Sign)  | `broker_id`, `chain_id`, `user_address`                         | Registers user address to Orderly account ledger.          |
| `/v1/orderly_key`            | `POST`   | Public (Wallet Sign)  | `broker_id`, `orderly_key`, `key_expiration`                    | Authorizes an Ed25519 public key on-chain for the account. |
| `/v1/order`                  | `POST`   | Private (Orderly Key) | `symbol`, `side`, `order_type`, `order_price`, `order_quantity` | Creates limit/market order on the orderbook.               |
| `/v1/order`                  | `DELETE` | Private (Orderly Key) | `order_id` (Query), `symbol`                                    | Cancels a specific order.                                  |
| `/v1/order/cancel_all_after` | `POST`   | Private (Orderly Key) | `trigger_in` (ms)                                               | Dead man's switch. Auto-cancels orders after timeout.      |
| `/v1/positions`              | `GET`    | Private (Orderly Key) | -                                                               | Retrieves unrealized P\&L and sizes of active positions.   |
| `/v1/client/holding`         | `GET`    | Private (Orderly Key) | -                                                               | Retrieves collateral token balances (USDC, etc.).          |

***

## 5. WebSocket Authentication & Heartbeat

### Connection Endpoints

* **Testnet**: `wss://testnet-ws-private-evm.orderly.org/v2/ws/private/stream/<account_id>`
* **Mainnet**: `wss://ws-private-evm.orderly.org/v2/ws/private/stream/<account_id>`

### Private Authentication Message

Send an authentication frame immediately after connection opens:

```json theme={null}
{
  "id": "req-auth-1",
  "event": "auth",
  "params": {
    "orderly_key": "<public_key_hex>",
    "sign": "<computed_signature_base64>",
    "timestamp": "<current_epoch_ms>"
  }
}
```

*Note: The string to sign for WebSocket authentication is: `${timestamp}auth`.*

### Heartbeat Mechanism

To prevent connection timeout, send a ping frame every 10 seconds:

```json theme={null}
{
  "event": "ping"
}
```

Expected response from the server:

```json theme={null}
{
  "event": "pong",
  "ts": 123456789000
}
```
