---
openapi: 3.0.3
info:
  title: Trading API
  description: |
    # Overview: Trading API
    
    {% hint style="warning" %}
    **This API is currently in beta.** The API may experience breaking changes. Any breaking changes will be communicated via email.
    {% endhint %}

    The Trading API is a completely optional feature for advanced users of The Grid. For basic, pay as you go usage of AI Inference, simply enable "Auto-Top-Up" and send chat completions requests to the Consumption API.
    
    The Trading API provides a comprehensive interface for buying AI Inference via advanced order types, interacting with markets, and managing your accounts on The Grid.
    
    ## Base URLs
    
    | Type | Base URL |
    |------------|----------|
    | **Http** | `https://trading-api.cortex.thegrid.ai/api/v1` |
    | **WebSocket** | `wss://trading-api.cortex.thegrid.ai/ws` |
    
    ## Authentication
    
    ### Authentication Scheme
    
    Trading API uses Ed25519 signature authentication (signatureAuth).
    
    To authenticate with the Trading API, you'll need an Ed25519 keypair (private and public keys). See the **Generating Ed25519 Keypairs** section below for instructions on how to generate them.
    
    Each authenticated request must include three headers:
    
    | Header | Description |
    |--------|-------------|
    | `x-thegrid-signature` | Base64-encoded Ed25519 signature |
    | `x-thegrid-timestamp` | Unix timestamp (seconds since epoch) |
    | `x-thegrid-fingerprint` | SHA256 hash of your public key (Base64-encoded) |
    
    ### Signature Generation Process
    
    1. Construct the message: `timestamp + HTTP_METHOD + request_path + body`
    2. Sign the message with your Ed25519 private key
    3. Base64 encode the signature
    4. Include headers in your request
    
    {% hint style="info" %}
    **Important:** The `request_path` is the endpoint path **without** query parameters. Query parameters are sent with the HTTP request but are excluded from signature computation.
    {% endhint %}
    
    **Signature Examples:**
    
    For a simple POST request to `/api/v1/trading/orders`:
    ```
    Message to sign: {timestamp}POST/api/v1/trading/orders{"market_id":"market_b310e860-97cd-45eb-bdc3-5be0b79295d0","side":"buy",...}
    ```
    
    For a GET request with query parameters like `/api/v1/trading/orders?limit=10&next=eyJpZCI6Im9yZGVyX1pWRk9BR0c0SldSTlhNQ0sifQ`:
    ```
    Path for signature: /api/v1/trading/orders  (query string excluded)
    Message to sign: {timestamp}GET/api/v1/trading/orders
    ```
    
    **Common mistake** (will cause "Signature verification failed"):
    ```
    # WRONG - do not include query parameters in signature
    Message: 1739145600GET/api/v1/trading/orders?limit=10
    ```
    
    **Correct:**
    ```
    # RIGHT - only the path, no query string
    Message: 1739145600GET/api/v1/trading/orders
    ```
    
    {% tabs %}
    {% tab title="Python" %}
    ```python
    import base64
    import hashlib
    import time
    from nacl.signing import SigningKey
    
    class SignatureAuth:
        def __init__(self, private_key_base64, public_key_base64):
            self.private_key = SigningKey(base64.b64decode(private_key_base64))
            public_key_bytes = base64.b64decode(public_key_base64)
            hash_obj = hashlib.sha256(public_key_bytes)
            self.fingerprint = base64.b64encode(hash_obj.digest()).decode('utf-8').rstrip('=')
    
        def get_headers(self, method, path, body=''):
            timestamp = str(int(time.time()))
            message = f"{timestamp}{method.upper()}{path}{body}"
            message_bytes = message.encode('utf-8')
            signature_bytes = self.private_key.sign(message_bytes).signature
            signature = base64.b64encode(signature_bytes).decode('utf-8')
    
            return {
                'x-thegrid-signature': signature,
                'x-thegrid-timestamp': timestamp,
                'x-thegrid-fingerprint': self.fingerprint
            }
    ```
    {% endtab %}
    
    {% tab title="JavaScript" %}
    ```javascript
    import nacl from 'tweetnacl';
    import util from 'tweetnacl-util';
    import crypto from 'crypto';
    
    class SignatureAuth {
      constructor(privateKeyBase64, publicKeyBase64) {
        this.privateKey = util.decodeBase64(privateKeyBase64);
        const publicKeyBuffer = Buffer.from(publicKeyBase64, 'base64');
        const hash = crypto.createHash('sha256').update(publicKeyBuffer).digest('base64');
        this.fingerprint = hash.replace(/=+$/, '');
      }
    
      getHeaders(method, path, body = '') {
        const timestamp = Math.floor(Date.now() / 1000).toString();
        const message = `${timestamp}${method.toUpperCase()}${path}${body}`;
        const messageBytes = util.decodeUTF8(message);
        const signatureBytes = nacl.sign.detached(messageBytes, this.privateKey);
        const signature = util.encodeBase64(signatureBytes);
    
        return {
          'x-thegrid-signature': signature,
          'x-thegrid-timestamp': timestamp,
          'x-thegrid-fingerprint': this.fingerprint
        };
      }
    }
    ```
    {% endtab %}
    
    {% tab title="Go" %}
    ```go
    package main
    
    import (
        "crypto/ed25519"
        "crypto/sha256"
        "encoding/base64"
        "fmt"
        "strings"
        "time"
    )
    
    type SignatureAuth struct {
        privateKey  ed25519.PrivateKey
        fingerprint string
    }
    
    func NewSignatureAuth(privateKeyBase64, publicKeyBase64 string) (*SignatureAuth, error) {
        privateKey, err := base64.StdEncoding.DecodeString(privateKeyBase64)
        if err != nil {
            return nil, err
        }
    
        publicKey, err := base64.StdEncoding.DecodeString(publicKeyBase64)
        if err != nil {
            return nil, err
        }
    
        hash := sha256.Sum256(publicKey)
        fingerprint := base64.StdEncoding.EncodeToString(hash[:])
        fingerprint = strings.TrimRight(fingerprint, "=")
    
        return &SignatureAuth{
            privateKey:  ed25519.PrivateKey(privateKey),
            fingerprint: fingerprint,
        }, nil
    }
    
    func (a *SignatureAuth) GetHeaders(method, path, body string) map[string]string {
        timestamp := fmt.Sprintf("%d", time.Now().Unix())
        message := timestamp + strings.ToUpper(method) + path + body
    
        signature := ed25519.Sign(a.privateKey, []byte(message))
        signatureBase64 := base64.StdEncoding.EncodeToString(signature)
    
        return map[string]string{
            "x-thegrid-signature":  signatureBase64,
            "x-thegrid-timestamp":  timestamp,
            "x-thegrid-fingerprint": a.fingerprint,
        }
    }
    ```
    {% endtab %}
    {% endtabs %}
    
    ### Generating Ed25519 Keypairs
    
    To authenticate with the Trading API, you'll need an Ed25519 keypair (private and public keys). Here's how to generate them in different languages:
    
    {% tabs %}
    {% tab title="OpenSSL (Command Line)" %}
    
    Generate a private key (32-byte seed)
    ```bash
    openssl genpkey -algorithm Ed25519 -out private_key.pem
    ```
    
    Extract the public key **for adding in The Grid UI**
    ```bash
    openssl pkey -in private_key.pem -pubout -out public_key.pem
    ```
    
    Convert private key to Base64 format **for use with the API**
    ```bash
    openssl pkey -in private_key.pem -outform DER | tail -c +13 | base64
    ```
    
    Convert public key to Base64 format **for use with the API**
    ```bash
    openssl pkey -pubin -in public_key.pem -outform DER | base64
    ```
    
    {% endtab %}


    {% tab title="Python" %}
    
    ```python
    import base64
    from nacl.signing import SigningKey
    
    # Generate a new Ed25519 keypair
    signing_key = SigningKey.generate()
    
    # Get the private key (64 bytes: 32-byte seed + 32-byte public key)
    private_key_bytes = bytes(signing_key)
    private_key_base64 = base64.b64encode(private_key_bytes).decode('utf-8')
    
    # Get the public key (32 bytes)
    public_key_bytes = bytes(signing_key.verify_key)
    public_key_base64 = base64.b64encode(public_key_bytes).decode('utf-8')
    
    print(f"Private Key (Base64): {private_key_base64}")
    print(f"Public Key (Base64): {public_key_base64}")
    ```
    
    **Note:** The private key includes both the seed and public key. You can extract just the seed (first 32 bytes) if needed.
    
    {% endtab %}
    
    {% tab title="JavaScript" %}
    
    ```javascript
    import nacl from 'tweetnacl';
    import util from 'tweetnacl-util';
    
    // Generate a new Ed25519 keypair
    const keypair = nacl.sign.keyPair();
    
    // Get the private key (64 bytes: 32-byte seed + 32-byte public key)
    const privateKeyBase64 = util.encodeBase64(keypair.secretKey);
    
    // Get the public key (32 bytes)
    const publicKeyBase64 = util.encodeBase64(keypair.publicKey);
    
    console.log(`Private Key (Base64): ${privateKeyBase64}`);
    console.log(`Public Key (Base64): ${publicKeyBase64}`);
    ```
    
    **Note:** The `secretKey` includes both the seed and public key. You can extract just the seed (first 32 bytes) if needed.
    
    {% endtab %}
    
    {% tab title="Go" %}
    
    ```go
    package main
    
    import (
        "crypto/ed25519"
        "encoding/base64"
        "fmt"
    )
    
    func main() {
        // Generate a new Ed25519 keypair
        publicKey, privateKey, err := ed25519.GenerateKey(nil)
        if err != nil {
            panic(err)
        }
    
        // Get the private key (64 bytes: 32-byte seed + 32-byte public key)
        privateKeyBase64 := base64.StdEncoding.EncodeToString(privateKey)
    
        // Get the public key (32 bytes)
        publicKeyBase64 := base64.StdEncoding.EncodeToString(publicKey)
    
        fmt.Printf("Private Key (Base64): %s\n", privateKeyBase64)
        fmt.Printf("Public Key (Base64): %s\n", publicKeyBase64)
    }
    ```
    
    **Note:** The private key includes both the seed and public key. You can extract just the seed (first 32 bytes) if needed.
    
    {% endtab %}
    
    {% endtabs %}
    
    **Important Security Notes:**
    
    - **Never share your private key** - keep it secure and never commit it to version control
    - **Store keys securely** - use environment variables or secure key management systems
    - **Use different keypairs** for different environments (development, staging, production)
    - The private key format includes both the seed and public key (64 bytes total)
    - The public key is 32 bytes and is used to generate the fingerprint for the `x-thegrid-fingerprint` header
    
    ## Request & Response Conventions

    ### Request Headers
    
    | Header | Description |
    |--------|----------|
    | `Content-Type` | Must be `application/json` for POST/PUT/PATCH requests |
    | `x-thegrid-signature` | Base64-encoded Ed25519 signature |
    | `x-thegrid-timestamp` | Unix timestamp in seconds |
    | `x-thegrid-fingerprint` | SHA256 hash of your public key (Base64-encoded) |
    
    **Example Request Headers:**
    ```http
    Content-Type: application/json
    x-thegrid-signature: 7Rp4K9mXvQ2hLwYzN8bJcT1gFdAeS6uHxI0oP3nMkWqVrCtByD5aUfGjElZiOsXm+4K8R2vN1hLwYzMbJcT6gFdA==
    x-thegrid-timestamp: 1739145600
    x-thegrid-fingerprint: Yk3mN7pRtV2xLwQzH8bJcS1gFdAeU6uHxI0oP3nMkWq
    ```

    ### Request Format
    - **Body**: JSON-encoded request body for POST/PUT requests
    - **Query Parameters**: URL-encoded for GET requests
    
    ### Response Headers
    
    All API responses include the following headers:
    
    | Header | Description |
    |--------|-------------|
    | `x-request-id` | Unique request identifier for debugging and support inquiries |
    | `x-ratelimit-limit` | Maximum requests allowed in the current time window |
    | `x-ratelimit-remaining` | Requests remaining in the current time window |
    | `x-ratelimit-reset` | Unix timestamp when the rate limit window resets |
    | `x-ratelimit-retry-after` | Seconds to wait before retrying (only present on 429 responses) |
    
    **Example Response Headers:**
    ```http
    x-request-id: GIkgbPVEdBDYQbcAAChF
    x-ratelimit-limit: 100
    x-ratelimit-remaining: 95
    x-ratelimit-reset: 1640995200
    ```
    > **Tip:** Always include the `x-request-id` value when contacting support to help diagnose issues.
    
    ### Response Body Format
    
    **Success Response:**
    
    ```json
    {
      "data": [ ... ],
      "paging": {
        "has_more": false,
        "next_cursor": null,
        "prev_cursor": null
      }
    }
    ```
    
    **Error Response:**
    
    ```json
    {
      "data": null,
      "error": "Error message",
      "errors": {
        "detail": "Detailed error information"
      },
      "meta": {
        "request_id": "GIkgbPVEdBDYQbcAAChF",
        "timestamp": "2025-01-01T00:00:00Z"
      }
    }
    ```
    
    ### Filtering
    
    Many list endpoints support filtering to narrow down results. Filter parameters are passed as query parameters and vary by endpoint.
    
    **Common filter patterns:**
    
    | Filter Type | Example | Description |
    |-------------|---------|-------------|
    | Exact match | `status=active` | Returns items where field equals value |
    | Date range | `start_datetime=2024-01-01T00:00:00Z` | Returns items after the specified date |
    
    **Example filtered request:**
    ```
    GET /api/v1/trading/orders?status=active&market_id=market_b310e860-97cd-45eb-bdc3-5be0b79295d0
    ```
    
    See each endpoint's documentation for available filter parameters.
    
    ### Sorting
    
    List endpoints support sorting results using the `order_by` and `order_direction` parameters.
    
    | Parameter | Type | Description |
    |-----------|------|-------------|
    | `order_by` | string | Field to sort by. Must be one of the endpoint's sortable fields. |
    | `order_direction` | string | Sort direction: `asc` (ascending) or `desc` (descending). Default: `asc`. |
    
    **Example sorted request:**
    ```
    GET /api/v1/trading/orders?order_by=submitted_at&order_direction=desc
    ```
    
    See each endpoint's documentation for available sortable fields.
        
    ## Pagination
    
    All list endpoints use **cursor-based pagination** for efficient and consistent data retrieval. Unlike offset-based pagination, cursor pagination ensures you won't miss items or see duplicates when the underlying data changes during pagination.
    
    ### Request Parameters
    
    | Parameter | Type | Default | Max | Description |
    |-----------|------|---------|-----|-------------|
    | `limit` | integer | 50 | 100 | Number of items to return per page |
    | `next` | string | - | - | Cursor token from a previous response's `next_cursor` field. Use for forward pagination. |
    | `prev` | string | - | - | Cursor token from a previous response's `prev_cursor` field. Use for backward pagination. |
    
    {% hint style="warning" %}
    The `next` and `prev` parameters are **mutually exclusive**. Do not send both in the same request.
    {% endhint %}
    
    ### Response Structure
    
    All paginated endpoints return a `paging` object:
    
    | Field | Type | Description |
    |-------|------|-------------|
    | `has_more` | boolean | `true` if there are more items available beyond this page |
    | `next_cursor` | string \| null | Cursor token to fetch the next page. `null` if no more pages. |
    | `prev_cursor` | string \| null | Cursor token to fetch the previous page. `null` if on the first page. |
    
    ### Request Examples
    
    ```
    # First page (no cursor needed)
    GET /api/v1/trading/orders?limit=10
    
    # Next page (use next_cursor value from previous response)
    GET /api/v1/trading/orders?limit=10&next=eyJpZCI6Im9yZGVyXzEyMyJ9
    
    # Previous page (use prev_cursor value from previous response)
    GET /api/v1/trading/orders?limit=10&prev=eyJpZCI6Im9yZGVyXzQzRUtVWUwzNE5XQVNMSVIifQ
    ```
    
    ### Response Example
    
    ```json
    {
      "data": [
        { "order_id": "order_ZVFOAGG4JWRNXMCK", "status": "active" },
        { "order_id": "order_43EKUYL34NWASLIR", "status": "filled" }
      ],
      "paging": {
        "has_more": true,
        "next_cursor": "eyJpZCI6Im9yZGVyX1pWRk9BR0c0SldSTlhNQ0sifQ",
        "prev_cursor": null
      }
    }
    ```
    
    ### Cursor Encoding
    
    Cursor values are base64-encoded strings. When passing these as query parameters:
    - The cursor value can be passed **as-is** (without URL encoding)
    - The server accepts both URL-encoded and non-encoded forms
    - If your HTTP client automatically URL-encodes query parameters, this is also acceptable
    
    ### Best Practices
    
    - Always check `has_more` before requesting the next page
    - Cursors are opaque strings—do not parse or modify them
    - Cursors may expire—they are meant for immediate sequential pagination, not long-term storage
    - Results maintain consistent ordering across pages when using cursors from the same initial request
    - Use appropriate `limit` values: higher for bulk operations, lower for UI display
    
    ## Rate Limits
    
    | Endpoint Type | Rate Limit |
    |---------------|------------|
    | **General requests** | 100 requests/minute |
    | **Order placement** | 50 orders/minute |
    
    **Rate Limit Headers** (included in every response):
    ```http
    x-ratelimit-limit: 100
    x-ratelimit-remaining: 95
    x-ratelimit-reset: 1640995200
    ```
    
    ## Common Error Codes
    
    | Code | HTTP Status | Description |
    |------|-------------|-------------|
    | `INVALID_SIGNATURE` | 401 | Authentication signature is invalid |
    | `EXPIRED_TIMESTAMP` | 401 | Request timestamp is too old (>30s) |
    | `INSUFFICIENT_BALANCE` | 400 | Not enough funds for operation |
    | `INSUFFICIENT_CREDITS` | 400 | Not enough AI credits |
    | `INVALID_MARKET` | 404 | Market ID not found |
    | `INVALID_ORDER` | 400 | Order parameters are invalid |
    | `ORDER_NOT_FOUND` | 404 | Order ID not found |
    | `RATE_LIMIT_EXCEEDED` | 429 | Too many requests |
    | `INTERNAL_ERROR` | 500 | Server error |
    
    ## Versioning
    
    - **Current version**: v1
    - **Version in URL**: `/api/v1/...`
    - **Breaking changes**: Will result in new version (v2, v3, etc.)
    - **Deprecation notice**: At least 6 months before removal
  version: 1.0.0
  contact:
    name: Customer Support
    email: support@thegrid.ai
    url: "https://thegrid.ai/docs"
  license:
    name: Proprietary
  x-logo:
    url: "https://thegrid.ai/logo.png"
externalDocs:
  description: |
    Full Documentation.
  url: "https://thegrid.ai/docs"
servers:
  -
      url: "{BASE_URL}/api/v1"
      description: |
        GRID Trading API Base URL
      variables:
        BASE_URL:
          default: "https://trading.api.thegrid.ai"
          description: |
            The base URL for the API.
tags:
  -
      name: Accounts
      description: |
        Trading and consumption accounts, their balances and more.
  -
      name: Instruments
      description: |
        Trading instruments including AI commodities with specifications
  -
      name: Markets
      description: |
        Market information, statistics, and orderbook data
  -
      name: Orders
      description: |
        Order management including creation, cancellation, and updates
  -
      name: Trades
      description: |
        Trade history associated with the authenticated user. Trades are individual fills for a given order.
  -
      name: Transfers
      description: |
        Asset transfers from trading to consumption accounts. Transfers are one-way.
paths:
  /trading/consumption-accounts:
    get:
      tags:
        - Accounts
      summary: List consumption accounts
      description: |
        View your consumption accounts by instrument, including balances and tokens used.
      operationId: listConsumptionAccounts
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/consumption-accounts' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/consumption-accounts'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              accounts = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/consumption-accounts';
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const accounts = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/consumption-accounts"
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []struct {
              		AccountID        string `json:"account_id"`
              		UserID           string `json:"user_id"`
              		InstrumentID     string `json:"instrument_id"`
              		TotalBalance     int    `json:"total_balance"`
              		AvailableBalance int    `json:"available_balance"`
              		CommittedBalance int    `json:"committed_balance"`
              		Status           string `json:"status"`
              	} `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: account_id
            in: query
            schema:
              type: string
            description: Filter by account ID
        -
            name: instrument_id
            in: query
            schema:
              type: string
            description: Filter by instrument ID
        -
            name: status
            in: query
            schema:
              type: string
              enum: [active, inactive]
            description: Filter by account status
        -
            name: order_by
            in: query
            schema:
              type: string
              enum: [account_id, total_balance, available_balance, status, created_at, updated_at]
            description: Field to sort by
        -
            name: order_direction
            in: query
            schema:
              type: string
              enum: [asc, desc]
              default: asc
            description: Sort direction
        -
            $ref: '#/components/parameters/next'
        -
            $ref: '#/components/parameters/prev'
        -
            $ref: '#/components/parameters/limit'
      responses:
        "200":
          description: |
            Consumption accounts
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConsumptionAccountsResponse'
              example:
                data:
                  -
                      account_id: consumption_account_cbf73393ef9e2ed0
                      user_id: user_094a5dc4-a2a6-48de-b6e0-09e214c5ca0d
                      instrument_id: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                      total_balance: 1500
                      available_balance: 1000
                      committed_balance: 500
                      uncommitted_balance: 1000
                      status: active
                      total_commitments: 0
                      total_deposits: 2
                      total_transfers_in: 2
                      total_transfers_out: 0
                      total_withdrawals: 0
                      last_commitment_at: null
                      last_deposit_at: "2026-01-09T17:33:02Z"
                      last_transfer_at: "2026-01-09T17:33:02Z"
                      last_withdrawal_at: null
                      created_at: "2026-01-09T17:33:02Z"
                      updated_at: "2026-01-09T17:33:02Z"
                paging:
                  has_more: false
                  next_cursor: null
                  prev_cursor: null
  /trading/consumption-accounts/{account_id}:
    get:
      tags:
        - Accounts
      summary: Get consumption account details
      description: |
        Get detailed information about a specific consumption account.
      operationId: tradingGetConsumptionAccount
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/consumption-accounts/consumption_account_cbf73393ef9e2ed0' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              account_id = 'consumption_account_cbf73393ef9e2ed0'
              path = f'/api/v1/trading/consumption-accounts/{account_id}'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              account = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const accountId = 'consumption_account_cbf73393ef9e2ed0';
              const path = `/api/v1/trading/consumption-accounts/${accountId}`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const account = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              accountID := "consumption_account_cbf73393ef9e2ed0"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/consumption-accounts/%s", accountID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data ConsumptionAccount `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: account_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the consumption account (e.g., "consumption_account_cbf73393ef9e2ed0")
      responses:
        "200":
          description: |
            Consumption account details
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/ConsumptionAccount'
              example:
                data:
                  account_id: consumption_account_cbf73393ef9e2ed0
                  available_balance: 2000
                  committed_balance: 500
                  uncommitted_balance: 1500
                  created_at: "2026-01-09T17:33:02Z"
                  instrument_id: instrument_c18a986c-522b-475a-b319-f2d0ba04a64d
                  last_commitment_at: null
                  last_deposit_at: "2026-01-09T17:33:02Z"
                  last_transfer_at: "2026-01-09T17:33:02Z"
                  last_withdrawal_at: null
                  status: active
                  total_balance: 2500
                  total_commitments: 0
                  total_deposits: 2
                  total_transfers_in: 2
                  total_transfers_out: 0
                  total_withdrawals: 0
                  updated_at: "2026-01-09T17:33:02Z"
                  user_id: user_9294c85b-d84f-4a9b-9bc3-51be1005cead
        "404":
          $ref: '#/components/responses/NotFound'
  /trading/currency-trading-accounts:
    get:
      tags:
        - Accounts
      summary: List currency trading accounts
      description: |
        List all currency trading accounts (USD, etc.).
      operationId: tradingListCurrencyAccounts
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/currency-trading-accounts' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/currency-trading-accounts'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              currency_accounts = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/currency-trading-accounts';
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const currencyAccounts = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/currency-trading-accounts"
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []CurrencyAccount `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: user_id
            in: query
            schema:
              type: string
            description: Filter by user ID
        -
            name: account_id
            in: query
            schema:
              type: string
            description: Filter by account ID
        -
            name: currency
            in: query
            schema:
              type: string
            description: Filter by currency (e.g., "USD")
        -
            name: status
            in: query
            schema:
              type: string
              enum: [active, inactive]
            description: Filter by account status
        -
            name: order_by
            in: query
            schema:
              type: string
              enum: [account_id, currency, total_balance, available_balance, status, created_at, updated_at]
            description: Field to sort by
        -
            name: order_direction
            in: query
            schema:
              type: string
              enum: [asc, desc]
              default: asc
            description: Sort direction
        -
            $ref: '#/components/parameters/next'
        -
            $ref: '#/components/parameters/prev'
        -
            $ref: '#/components/parameters/limit'
      responses:
        "200":
          description: |
            List of currency trading accounts
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/CurrencyTradingAccount'
                  paging:
                    $ref: '#/components/schemas/CursorPaging'
              example:
                data:
                  -
                      account_id: currency_trading_account_e927ad93f9c4aaa8
                      user_id: user_2e605810-1e39-4d5a-a8e2-e46c89ac4b26
                      currency: USD
                      total_balance: "1200"
                      available_balance: "700"
                      locked_balance: "500"
                      status: active
                      last_deposit_at: null
                      last_trading_activity_at: null
                      last_withdrawal_at: null
                      created_at: "2025-12-10T18:19:01Z"
                      updated_at: "2025-12-10T18:19:01Z"
                paging:
                  has_more: false
                  next_cursor: null
                  prev_cursor: null
  /trading/currency-trading-accounts/{account_id}:
    get:
      tags:
        - Accounts
      summary: Get currency account details
      description: |
        Get specific currency trading account details.
      operationId: tradingGetCurrencyAccount
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/currency-trading-accounts/currency_trading_account_57252e83c212e7a9' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              account_id = 'currency_trading_account_57252e83c212e7a9'
              path = f'/api/v1/trading/currency-trading-accounts/{account_id}'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              account = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const accountId = 'currency_trading_account_57252e83c212e7a9';
              const path = `/api/v1/trading/currency-trading-accounts/${accountId}`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const account = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              accountID := "currency_trading_account_57252e83c212e7a9"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/currency-trading-accounts/%s", accountID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data CurrencyAccount `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: account_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the currency trading account (e.g., "currency_trading_account_57252e83c212e7a9")
      responses:
        "200":
          description: |
            Currency account details
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/CurrencyTradingAccount'
              example:
                data:
                  account_id: currency_trading_account_57252e83c212e7a9
                  user_id: user_2ce466b1-d257-4337-98e4-54b4fd254702
                  currency: USD
                  total_balance: "1200"
                  available_balance: "700"
                  locked_balance: "500"
                  status: active
                  last_deposit_at: null
                  last_trading_activity_at: null
                  last_withdrawal_at: null
                  created_at: "2025-12-10T18:19:01Z"
                  updated_at: "2025-12-10T18:19:01Z"
        "404":
          $ref: '#/components/responses/NotFound'
  /trading/instruments:
    get:
      tags:
        - Instruments
      summary: List instruments
      description: |
        Lists all available instruments with optional filtering and sorting.
      operationId: listInstruments
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/instruments' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/instruments'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              instruments = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/instruments';
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const instruments = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/instruments"
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []Instrument `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            $ref: '#/components/parameters/next'
        -
            $ref: '#/components/parameters/prev'
        -
            $ref: '#/components/parameters/limit'
        -
            name: order_by
            in: query
            schema:
              type: string
              enum:
                - symbol
                - created_at
                - updated_at
            description: |
              Field to sort by
        -
            name: order_direction
            in: query
            schema:
              type: string
              enum:
                - asc
                - desc
            description: |
              Sort direction
        -
            name: symbol
            in: query
            schema:
              type: string
            description: |
              Filter by exact symbol match (e.g., "CHAT-PRIME")
        -
            name: instrument_type
            in: query
            schema:
              type: string
              enum:
                - ai_commodity
                - currency
                - commodity
            description: |
              Filter by instrument type
        -
            name: status
            in: query
            schema:
              type: string
              enum:
                - draft
                - active
                - inactive
                - suspended
                - deleted
            description: |
              Filter by status
      responses:
        "200":
          description: |
            List of instruments
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InstrumentListResponse'
              example:
                data:
                  -
                      instrument_id: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                      symbol: CHAT-PRIME
                      name: Chat Prime Instrument
                      description: High-quality AI inference capacity
                      type: ai_commodity
                      status: active
                      basic_info:
                        service_type: text_generation
                        model_category: language_model
                      trading_params:
                        min_quantity: 1
                        max_quantity: 1000
                        quantity_increment: 1
                        fee: "0.025"
                      ai_specs:
                        context_window: "200000"
                        token_throughput: "50"
                        tokens_per_unit: 1000000
                        unit_definition: per_1000_input_tokens
                        qualifying_models:
                          - gpt-5
                          - gpt-5-mini
                        max_output_length: 4096
                        model_id: gpt-5
                        model_version: "1.0"
                paging:
                  has_more: false
                  next_cursor: null
                  prev_cursor: null
  /trading/instruments/{instrument_id}:
    get:
      tags:
        - Instruments
      summary: Get instrument details
      description: |
        Gets a specific instrument by its ID. Returns full instrument details including
        trading parameters and AI specifications.
      operationId: getInstrument
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/instruments/instrument_c18a986c-522b-475a-b319-f2d0ba04a64d' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              instrument_id = 'instrument_c18a986c-522b-475a-b319-f2d0ba04a64d'
              path = f'/api/v1/trading/instruments/{instrument_id}'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              instrument = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const instrumentId = 'instrument_c18a986c-522b-475a-b319-f2d0ba04a64d';
              const path = `/api/v1/trading/instruments/${instrumentId}`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const instrument = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              instrumentID := "instrument_c18a986c-522b-475a-b319-f2d0ba04a64d"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/instruments/%s", instrumentID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data InstrumentDetail `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: instrument_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the instrument (e.g., "instrument_c18a986c-522b-475a-b319-f2d0ba04a64d")
      responses:
        "200":
          description: |
            Instrument details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InstrumentDetailResponse'
              example:
                data:
                  instrument_id: instrument_c18a986c-522b-475a-b319-f2d0ba04a64d
                  symbol: CHAT-PRIME
                  name: Chat Prime Instrument
                  description: High-quality AI inference capacity
                  type: ai_commodity
                  status: active
                  basic_info:
                    service_type: text_generation
                    model_category: language_model
                  trading_params:
                    min_quantity: 1
                    max_quantity: 1000
                    quantity_increment: 1
                    fee: "0.025"
                  ai_specs:
                    context_window: "200000"
                    token_throughput: "50"
                    tokens_per_unit: 1000000
                    unit_definition: per_1000_input_tokens
                    qualifying_models:
                      - gpt-5
                      - gpt-5-mini
                    max_output_length: 4096
                    model_id: gpt-5
                    model_version: "1.0"
                  last_trade_price: null
                  last_trade_at: null
                  last_quote_at: null
                  total_volume: "0"
                  volume_24h: "0"
                  total_trades: 0
                  total_quotes: 0
                  price_range_24h_high: null
                  price_range_24h_low: null
        "404":
          $ref: '#/components/responses/NotFound'
  /trading/markets:
    get:
      tags:
        - Markets
      summary: List markets
      description: |
        Returns markets with instrument details.
      operationId: tradingListMarkets
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/markets' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/markets'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              markets = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/markets';
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const markets = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/markets"
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []MarketWithInstruments `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      responses:
        "200":
          description: |
            List of markets
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/MarketWithInstruments'
                  paging:
                    $ref: '#/components/schemas/CursorPaging'
              example:
                data:
                  -
                      market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                      name: Alpha Market
                      description: Primary market for AI inference trading
                      market_type: spot
                      status: active
                      allowed_instruments:
                        - instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                        - instrument_b237c3b4-e623-48ba-bddd-a8ee5230973e
                      instruments:
                        -
                            id: 6b3946b6-4697-4171-a922-7d445bca61f4
                            instrument_id: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                            symbol: GPT-TRADER
                            name: GPT Trader Token
                            description: Claude-3 Inference Token Trading
                            instrument_type: ai_commodity
                            status: active
                            basic_info:
                              service_type: text_generation
                              model_category: language_model
                            trading_params:
                              min_quantity: 1
                              max_quantity: 1000
                              quantity_increment: 1
                              fee: "0.025"
                            ai_specs:
                              context_window: "200000"
                              token_throughput: "50"
                              tokens_per_unit: 1000000
                              unit_definition: per_1000_input_tokens
                              qualifying_models:
                                - gpt-5
                                - gpt-5-mini
                              max_output_length: 4096
                              model_id: gpt-5
                              model_version: "1.0"
                            sla_requirements:
                              availability_target: 99.95
                              max_latency_ms: 300
                              quality_score_min: 90
                            last_trade_price: null
                            last_trade_at: null
                            last_quote_at: null
                            price_range_24h_high: null
                            price_range_24h_low: null
                            total_volume: 0
                            volume_24h: 0
                            total_trades: 0
                            total_quotes: 0
                            created_at: "2025-12-15T11:29:53"
                            updated_at: "2025-12-15T11:29:53"
                      created_at: "2025-12-15T11:29:53Z"
                      updated_at: "2025-12-15T11:29:53Z"
                paging:
                  has_more: false
                  next_cursor: null
                  prev_cursor: null
  /trading/markets/{market_id}/ticker:
    get:
      tags:
        - Markets
      summary: Get market ticker
      description: |
        Get current ticker data including best bid/ask, last price, and 24h volume.
      operationId: tradingGetTicker
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/markets/market_b310e860-97cd-45eb-bdc3-5be0b79295d0/ticker' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              market_id = 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0'
              path = f'/api/v1/trading/markets/{market_id}/ticker'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              ticker = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const marketId = 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0';
              const path = `/api/v1/trading/markets/${marketId}/ticker`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const ticker = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              marketID := "market_b310e860-97cd-45eb-bdc3-5be0b79295d0"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/markets/%s/ticker", marketID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data Ticker `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: market_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the market (e.g., "market_CHAT-PRIME_USD")
      responses:
        "200":
          description: |
            Ticker data including last trade, bid/ask, and 24h volume
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/Ticker'
              example:
                data:
                  last_price: "45.50"
                  last_trade_size: 100
                  last_trade_timestamp: "2026-02-12T07:42:45Z"
                  lowest_ask: "45.75"
                  highest_bid: "45.25"
                  volume_24h: 15000
        "401":
          $ref: '#/components/responses/Unauthorized'
        "404":
          $ref: '#/components/responses/NotFound'
  /trading/markets/{market_id}/orderbook:
    get:
      tags:
        - Markets
      summary: Get order book
      description: |
        Get the order book (depth of market) for a specific market.
      operationId: tradingGetOrderbook
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/markets/market_b310e860-97cd-45eb-bdc3-5be0b79295d0/orderbook' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              market_id = 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0'
              path = f'/api/v1/trading/markets/{market_id}/orderbook'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              book = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const marketId = 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0';
              const path = `/api/v1/trading/markets/${marketId}/orderbook`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const book = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              marketID := "market_b310e860-97cd-45eb-bdc3-5be0b79295d0"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/markets/%s/orderbook", marketID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data Orderbook `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: market_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the market (e.g., "market_CHAT-PRIME_USD")
        -
            name: depth
            in: query
            schema:
              type: integer
              default: 10
              minimum: 1
              maximum: 100
            description: |
              Maximum number of price levels to return per side (bids and asks). Default: 10. Use lower values for quick price checks, higher values for detailed market depth analysis.
      responses:
        "200":
          description: |
            Order book data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderbookResponse'
              example:
                data:
                  buy:
                    -
                        price: "144.50"
                        size: 100
                        total: 100
                        order_count: 1
                    -
                        price: "144.00"
                        size: 200
                        total: 300
                        order_count: 1
                  sell:
                    -
                        price: "145.50"
                        size: 150
                        total: 150
                        order_count: 1
                    -
                        price: "146.00"
                        size: 250
                        total: 400
                        order_count: 1
                  highest_bid: "144.50000000"
                  lowest_ask: "145.50000000"
                  updated_at: "2025-12-15T11:29:53.531908Z"
  /trading/markets/{market_id}/trades:
    get:
      tags:
        - Markets
      summary: Get market trades
      description: |
        Returns public trades for a specific market (not scoped to authenticated user).
      operationId: tradingGetMarketTrades
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/markets/market_b310e860-97cd-45eb-bdc3-5be0b79295d0/trades' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              market_id = 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0'
              path = f'/api/v1/trading/markets/{market_id}/trades'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              trades = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const marketId = 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0';
              const path = `/api/v1/trading/markets/${marketId}/trades`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const trades = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              marketID := "market_b310e860-97cd-45eb-bdc3-5be0b79295d0"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/markets/%s/trades", marketID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []PublicTrade `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: market_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the market (e.g., "market_CHAT-PRIME_USD")
        -
            name: status
            in: query
            schema:
              type: string
            description: Filter by trade status
        -
            name: side
            in: query
            schema:
              type: string
              enum: [buy, sell]
            description: Filter by taker side
        -
            name: min_quantity
            in: query
            schema:
              type: integer
            description: Filter trades with quantity >= this value
        -
            name: max_quantity
            in: query
            schema:
              type: integer
            description: Filter trades with quantity <= this value
        -
            name: min_price
            in: query
            schema:
              type: string
            description: Filter trades with price >= this value
        -
            name: max_price
            in: query
            schema:
              type: string
            description: Filter trades with price <= this value
        -
            name: start_date
            in: query
            schema:
              type: string
              format: date-time
            description: Filter trades executed at or after this time (ISO8601 or Unix timestamp)
        -
            name: end_date
            in: query
            schema:
              type: string
              format: date-time
            description: Filter trades executed at or before this time (ISO8601 or Unix timestamp)
        -
            name: order_by
            in: query
            schema:
              type: string
              enum: [execution_timestamp, quantity, price]
            description: Field to sort by
        -
            name: order_direction
            in: query
            schema:
              type: string
              enum: [asc, desc]
              default: asc
            description: Sort direction
        -
            $ref: '#/components/parameters/next'
        -
            $ref: '#/components/parameters/prev'
        -
            name: limit
            in: query
            schema:
              type: integer
              default: 50
              maximum: 100
            description: |
              Number of trades to return (max: 100)
      responses:
        "200":
          description: |
            Recent trades
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/PublicTrade'
                  paging:
                    $ref: '#/components/schemas/CursorPaging'
              example:
                data:
                  -
                      id: be130f02-a0d1-43f7-9781-dab66ea3f627
                      trade_id: trade-1
                      market_id: test-market-trades
                      market_name: null
                      instrument_id: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                      instrument_symbol: GPT-TEST
                      instrument_name: Test Instrument
                      price: "45.50000000"
                      quantity: 3
                      side: buy
                      total_value: "45500.00000000"
                      status: executed
                      execution_timestamp: "2025-12-05T17:29:29.944711Z"
                      settlement_timestamp: "2025-12-05T17:29:29.944712Z"
                  -
                      id: 48540c98-bbee-441c-a984-b2aa56cd613a
                      trade_id: trade-2
                      market_id: test-market-trades
                      market_name: null
                      instrument_id: instrument_b237c3b4-e623-48ba-bddd-a8ee5230973e
                      instrument_symbol: GPT-TEST
                      instrument_name: Test Instrument
                      price: "45.50000000"
                      quantity: 11
                      side: buy
                      total_value: "45500.00000000"
                      status: executed
                      execution_timestamp: "2025-12-05T17:29:29.944180Z"
                      settlement_timestamp: "2025-12-05T17:29:29.944181Z"
                  -
                      id: 6a9eab19-f78c-4ddd-9422-7d4a24c2a3d3
                      trade_id: trade-3
                      market_id: test-market-trades
                      market_name: null
                      instrument_id: instrument_c18a986c-522b-475a-b319-f2d0ba04a64d
                      instrument_symbol: GPT-TEST
                      instrument_name: Test Instrument
                      price: "45.50000000"
                      quantity: 1
                      side: buy
                      total_value: "45500.00000000"
                      status: executed
                      execution_timestamp: "2025-12-05T17:29:29.942332Z"
                      settlement_timestamp: "2025-12-05T17:29:29.942334Z"
                paging:
                  has_more: false
                  next_cursor: null
                  prev_cursor: null
  /trading/markets/{market_id}:
    get:
      tags:
        - Markets
      summary: Get market details
      description: |
        Returns market details with instruments.
      operationId: tradingGetMarket
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/markets/market_b310e860-97cd-45eb-bdc3-5be0b79295d0' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              market_id = 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0'
              path = f'/api/v1/trading/markets/{market_id}'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              market = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const marketId = 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0';
              const path = `/api/v1/trading/markets/${marketId}`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const market = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              marketID := "market_b310e860-97cd-45eb-bdc3-5be0b79295d0"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/markets/%s", marketID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data MarketWithInstruments `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: market_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the market (e.g., "market_CHAT-PRIME_USD")
      responses:
        "200":
          description: |
            Market details
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/MarketWithInstruments'
              example:
                data:
                  market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                  name: Detail Market
                  description: Primary market for AI inference trading
                  market_type: spot
                  status: active
                  allowed_instruments:
                    - instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                    - instrument_b237c3b4-e623-48ba-bddd-a8ee5230973e
                  instruments:
                    -
                        id: b89a5f06-5fa4-41d8-98e3-dc07ff12bc4f
                        instrument_id: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                        symbol: GPT-DETAIL
                        name: GPT Detail Token
                        description: Claude-3 Inference Token Trading
                        instrument_type: ai_commodity
                        status: active
                        basic_info:
                          service_type: text_generation
                          model_category: language_model
                        trading_params:
                          min_quantity: 1
                          max_quantity: 1000
                          quantity_increment: 1
                          fee: "0.025"
                        ai_specs:
                          context_window: "200000"
                          token_throughput: "50"
                          tokens_per_unit: 1000000
                          unit_definition: per_1000_input_tokens
                          qualifying_models:
                            - gpt-5
                            - gpt-5-mini
                          max_output_length: 4096
                          model_id: gpt-5
                          model_version: "1.0"
                        sla_requirements:
                          availability_target: 99.95
                          max_latency_ms: 300
                          quality_score_min: 90
                        last_trade_price: null
                        last_trade_at: null
                        last_quote_at: null
                        price_range_24h_high: null
                        price_range_24h_low: null
                        total_volume: 0
                        volume_24h: 0
                        total_trades: 0
                        total_quotes: 0
                        created_at: "2025-12-15T11:29:53"
                        updated_at: "2025-12-15T11:29:53"
                  created_at: "2025-12-15T11:29:53Z"
                  updated_at: "2025-12-15T11:29:53Z"
        "404":
          $ref: '#/components/responses/NotFound'
  /trading/orders:
    get:
      tags:
        - Orders
      summary: List trader's orders
      description: |
        Returns the authenticated trader's orders using Ed25519 signature authentication.
      operationId: tradingListOrders
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/orders' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/orders'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              orders = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/orders';
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const orders = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/orders"
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []Order `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: market_id
            in: query
            schema:
              type: string
            description: Filter by market ID
        -
            name: trader_id
            in: query
            schema:
              type: string
            description: Filter by trader ID
        -
            name: instrument_id
            in: query
            schema:
              type: string
            description: Filter by instrument ID
        -
            name: side
            in: query
            schema:
              type: string
              enum: [buy, sell]
            description: Filter by order side
        -
            name: status
            in: query
            schema:
              type: string
              enum: [active, closed, cancelled]
            description: Filter by order status
        -
            name: start_datetime
            in: query
            schema:
              type: string
              format: date-time
            description: Filter orders submitted at or after this time (ISO8601 or Unix timestamp)
        -
            name: end_datetime
            in: query
            schema:
              type: string
              format: date-time
            description: Filter orders submitted at or before this time (ISO8601 or Unix timestamp)
        -
            name: order_by
            in: query
            schema:
              type: string
              enum: [submitted_at, filled_at, price, original_quantity, order_id]
            description: Field to sort by
        -
            name: order_direction
            in: query
            schema:
              type: string
              enum: [asc, desc]
              default: asc
            description: Sort direction
        -
            $ref: '#/components/parameters/next'
        -
            $ref: '#/components/parameters/prev'
        -
            $ref: '#/components/parameters/limit'
      responses:
        "200":
          description: |
            List of orders
          headers:
            x-request-id:
              $ref: '#/components/headers/x-request-id'
            x-ratelimit-limit:
              $ref: '#/components/headers/x-ratelimit-limit'
            x-ratelimit-remaining:
              $ref: '#/components/headers/x-ratelimit-remaining'
            x-ratelimit-reset:
              $ref: '#/components/headers/x-ratelimit-reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradingOrderListResponse'
              example:
                data:
                  -
                      id: order_ZVFOAGG4JWRNXMCK
                      market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                      market_name: Market Alpha
                      instrument_id: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                      instrument_name: Test Instrument
                      instrument_symbol: GPT-ALPHA
                      trader_id: user_1b8dafe4-cea0-415a-8e4c-089c5af0168f
                      type: limit
                      side: buy
                      price: "45.50000000"
                      size: 100
                      filled_quantity: 0
                      average_price: "45.50000000"
                      fee: "1137.50000000000"
                      status: active
                      closure_reason: null
                      time_in_force: gtc
                      stop_price: null
                      client_order_id: "my-order-123"
                      triggered_by_auto_top_up: false
                      submitted_at: "2025-12-23T15:15:16Z"
                paging:
                  has_more: false
                  next_cursor: null
                  prev_cursor: null
        "429":
          $ref: '#/components/responses/RateLimitExceeded'
    post:
      tags:
        - Orders
      summary: Place order
      description: |
        Create a new order using Ed25519 signature authentication.
      operationId: tradingCreateOrder
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X POST 'https://trading-api.cortex.thegrid.ai/api/v1/trading/orders' \
                -H 'Content-Type: application/json' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT' \
                -d '{
                  "market_id": "market_b310e860-97cd-45eb-bdc3-5be0b79295d0",
                  "side": "buy",
                  "type": "limit",
                  "quantity": 1,
                  "price": "1.19"
                }'
        -
            lang: Python
            source: |
              import json
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/orders'
              order_params = {
                  'market_id': 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0',
                  'side': 'buy',
                  'type': 'limit',
                  'quantity': 1,
                  'price': '1.19'
              }
              body = json.dumps(order_params)
              headers = auth.get_headers('POST', path, body)
              response = requests.post(
                  f'https://trading.api.thegrid.ai{path}',
                  json=order_params,
                  headers={
                      'Content-Type': 'application/json',
                      **headers
                  }
              )
              data = response.json()['data']  # { order_id }
              order_id = data['order_id']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/orders';
              const orderParams = {
                market_id: 'market_b310e860-97cd-45eb-bdc3-5be0b79295d0',
                side: 'buy',
                type: 'limit',
                quantity: 1,
                price: '1.19'
              };
              const body = JSON.stringify(orderParams);
              const headers = auth.getHeaders('POST', path, body);
              const response = await axios.post(
                `https://trading.api.thegrid.ai${path}`,
                orderParams,
                {
                  headers: {
                    'Content-Type': 'application/json',
                    ...headers
                  }
                }
              );
              const data = response.data.data;  // { order_id }
              const orderId = data.order_id;
        -
            lang: Go
            source: |
              import (
              	"bytes"
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/orders"
              orderParams := map[string]interface{}{
              	"market_id": "market_b310e860-97cd-45eb-bdc3-5be0b79295d0",
              	"side":      "buy",
              	"type":      "limit",
              	"quantity":  1,
              	"price":     "1.19",
              }
              bodyBytes, _ := json.Marshal(orderParams)
              bodyStr := string(bodyBytes)
              headers, _ := auth.GetHeaders("POST", path, bodyStr)
              req, _ := http.NewRequest("POST", baseURL+path, bytes.NewBuffer(bodyBytes))
              req.Header.Set("Content-Type", "application/json")
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data struct {
              		OrderID       string `json:"order_id"`
              	} `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
                    $ref: '#/components/schemas/TradingCreateOrderRequest'
            example:
              market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
              side: buy
              type: limit
              quantity: 1
              price: "1.19"
      responses:
        "201":
          description: |
            Order created
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      order_id:
                        type: string
                        example: order_TT64AI5BZNLKUFTL
                      client_order_id:
                        type: string
                        example: my-order-123
                        nullable: true
        "400":
          description: |
            Invalid order parameters
        "401":
          $ref: '#/components/responses/Unauthorized'
        "422":
          $ref: '#/components/responses/ValidationError'
  /trading/orders/{order_id}:
    delete:
      tags:
        - Orders
      summary: Cancel order
      description: |
        Cancel an order using Ed25519 signature authentication.
      operationId: tradingCancelOrder
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X DELETE 'https://trading-api.cortex.thegrid.ai/api/v1/trading/orders/order_ZVFOAGG4JWRNXMCK' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              order_id = 'order_ZVFOAGG4JWRNXMCK'
              path = f'/api/v1/trading/orders/{order_id}'
              headers = auth.get_headers('DELETE', path, '')
              response = requests.delete(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const orderId = 'order_ZVFOAGG4JWRNXMCK';
              const path = `/api/v1/trading/orders/${orderId}`;
              const headers = auth.getHeaders('DELETE', path, '');
              const response = await axios.delete(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
        -
            lang: Go
            source: |
              import (
              	"fmt"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              orderID := "order_ZVFOAGG4JWRNXMCK"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/orders/%s", orderID)
              headers, _ := auth.GetHeaders("DELETE", path, "")
              req, _ := http.NewRequest("DELETE", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: order_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the order (e.g., "order_TT64AI5BZNLKUFTL")
      responses:
        "204":
          description: |
            Order cancelled successfully
        "404":
          $ref: '#/components/responses/NotFound'
        "409":
          description: |
            Order already cancelled
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                errors:
                  detail: "order_already_cancelled"
    get:
      tags:
        - Orders
      summary: Get order details
      description: |
        Returns details of a specific order.
      operationId: tradingGetOrder
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/orders/order_ZVFOAGG4JWRNXMCK' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              order_id = 'order_ZVFOAGG4JWRNXMCK'
              path = f'/api/v1/trading/orders/{order_id}'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              order = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const orderId = 'order_ZVFOAGG4JWRNXMCK';
              const path = `/api/v1/trading/orders/${orderId}`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const order = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              orderID := "order_ZVFOAGG4JWRNXMCK"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/orders/%s", orderID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data Order `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: order_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the order (e.g., "order_TT64AI5BZNLKUFTL")
      responses:
        "200":
          description: |
            Order details
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/Order'
              example:
                data:
                  id: order_show_1
                  market_id: test-market-27
                  market_name: Show Market
                  instrument_id: instrument_c18a986c-522b-475a-b319-f2d0ba04a64d
                  instrument_name: Test Instrument
                  instrument_symbol: GPT-SHOW
                  trader_id: user_0e393ba0-84a3-49e2-9795-59174ddb29a4
                  type: limit
                  side: buy
                  price: "45.50000000"
                  size: 1000
                  filled_quantity: 0
                  average_price: "45.50000000"
                  fee: "1137.50000000000"
                  status: active
                  closure_reason: null
                  time_in_force: gtc
                  stop_price: null
                  client_order_id: null
                  triggered_by_auto_top_up: false
                  submitted_at: "2025-12-23T15:15:16Z"
        "404":
          $ref: '#/components/responses/NotFound'
  /trading/trades:
    get:
      tags:
        - Trades
      summary: Get user's trade history
      description: |
        Get your trade history (fills). Results are always the authenticated user's trades.
        Use the `order_id` filter to limit results to trades for a specific order (the user's order
        associated with each trade, as returned in the response `order_id` field).
      operationId: tradingListTrades
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/trades' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/trades'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              trades = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/trades';
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const trades = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/trades"
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []Trade `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: market_id
            in: query
            schema:
              type: string
            description: Filter by market ID
        -
            name: instrument_id
            in: query
            schema:
              type: string
            description: Filter by instrument ID
        -
            name: trade_id
            in: query
            schema:
              type: string
            description: Filter by trade ID
        -
            name: order_id
            in: query
            schema:
              type: string
            description: |
              Filter by the user's order ID associated with the trade (canonical filter for "my" trades).
              Matches the `order_id` field returned on each trade.
        -
            name: status
            in: query
            schema:
              type: string
            description: Filter by trade status
        -
            name: buyer_order_id
            in: query
            schema:
              type: string
            description: Filter by buyer's order ID (legacy; prefer `order_id` for user's trades)
        -
            name: seller_order_id
            in: query
            schema:
              type: string
            description: Filter by seller's order ID (legacy; prefer `order_id` for user's trades)
        -
            name: triggering_order_id
            in: query
            schema:
              type: string
            description: Filter by the order that triggered the trade (legacy; prefer `order_id` for user's trades)
        -
            name: start_datetime
            in: query
            schema:
              type: string
              format: date-time
            description: Filter trades executed at or after this time (ISO8601 or Unix timestamp)
        -
            name: end_datetime
            in: query
            schema:
              type: string
              format: date-time
            description: Filter trades executed at or before this time (ISO8601 or Unix timestamp)
        -
            name: order_by
            in: query
            schema:
              type: string
              enum: [execution_timestamp, trade_id, price, quantity, total_value]
            description: Field to sort by
        -
            name: order_direction
            in: query
            schema:
              type: string
              enum: [asc, desc]
              default: asc
            description: Sort direction
        -
            $ref: '#/components/parameters/next'
        -
            $ref: '#/components/parameters/prev'
        -
            $ref: '#/components/parameters/limit'
      responses:
        "200":
          description: |
            List of trades
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradeListResponse'
              example:
                data:
                  -
                      id: d9dcb544-02a2-4637-880c-13d50d61fb42
                      trade_id: trade_d7b40819-0ea6-428b-b00c-deb559206cb7
                      market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                      market_name: Show Market
                      instrument_id: instrument_c18a986c-522b-475a-b319-f2d0ba04a64d
                      instrument_name: Test Instrument
                      instrument_symbol: GPT-SHOW
                      order_id: order_ZVFOAGG4JWRNXMCK
                      trading_account_id: trading_account_6e6ad9d28eaae559
                      price: "99.99000000"
                      quantity: 500
                      side: buy
                      total_value: "45500.00000000"
                      fee: "0.025"
                      status: executed
                      execution_timestamp: "2025-12-05T17:29:29.887434Z"
                      settlement_timestamp: "2025-12-05T17:29:29.887436Z"
                paging:
                  has_more: false
                  next_cursor: null
                  prev_cursor: null
  /trading/trades/{trade_id}:
    get:
      tags:
        - Trades
      summary: Get single trade
      description: |
        Returns a single trade with metadata.
      operationId: tradingGetTrade
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/trades/trade_d7b40819-0ea6-428b-b00c-deb559206cb7' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              trade_id = 'trade_d7b40819-0ea6-428b-b00c-deb559206cb7'
              path = f'/api/v1/trading/trades/{trade_id}'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              trade = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const tradeId = 'trade_d7b40819-0ea6-428b-b00c-deb559206cb7';
              const path = `/api/v1/trading/trades/${tradeId}`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const trade = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              tradeID := "trade_d7b40819-0ea6-428b-b00c-deb559206cb7"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/trades/%s", tradeID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data Trade `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: trade_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the trade (e.g., "trade_d7b40819-0ea6-428b-b00c-deb559206cb7")
      responses:
        "200":
          description: |
            Trade details
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/UserTrade'
              example:
                data:
                  id: d9dcb544-02a2-4637-880c-13d50d61fb42
                  trade_id: trade_d7b40819-0ea6-428b-b00c-deb559206cb7
                  market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                  market_name: Show Market
                  instrument_id: instrument_c18a986c-522b-475a-b319-f2d0ba04a64d
                  instrument_name: Test Instrument
                  instrument_symbol: GPT-SHOW
                  order_id: order_ZVFOAGG4JWRNXMCK
                  trading_account_id: trading_account_6e6ad9d28eaae559
                  price: "99.99000000"
                  quantity: 500
                  side: buy
                  total_value: "45500.00000000"
                  fee: "0.025"
                  status: executed
                  execution_timestamp: "2025-12-05T17:29:29.887434Z"
                  settlement_timestamp: "2025-12-05T17:29:29.887436Z"
        "404":
          $ref: '#/components/responses/NotFound'
  /trading/trading-accounts:
    get:
      tags:
        - Accounts
      summary: List trading account balances
      description: |
        List all trading account balances across instruments.
      operationId: tradingListTradingAccounts
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/trading-accounts' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/trading-accounts'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              balances = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/trading-accounts';
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const balances = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/trading-accounts"
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []TradingAccount `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: account_id
            in: query
            schema:
              type: string
            description: Filter by account ID
        -
            name: market_id
            in: query
            schema:
              type: string
            description: Filter by market ID
        -
            name: instrument_id
            in: query
            schema:
              type: string
            description: Filter by instrument ID
        -
            name: status
            in: query
            schema:
              type: string
              enum: [active, inactive]
            description: Filter by account status
        -
            name: order_by
            in: query
            schema:
              type: string
              enum: [account_id, total_balance, available_balance, status, created_at, updated_at]
            description: Field to sort by
        -
            name: order_direction
            in: query
            schema:
              type: string
              enum: [asc, desc]
              default: asc
            description: Sort direction
        -
            $ref: '#/components/parameters/next'
        -
            $ref: '#/components/parameters/prev'
        -
            $ref: '#/components/parameters/limit'
      responses:
        "200":
          description: |
            List of trading accounts
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/TradingAccount'
                  paging:
                    $ref: '#/components/schemas/CursorPaging'
              example:
                data:
                  -
                      account_id: trading_account_6e6ad9d28eaae559
                      user_id: user_7225b557-5e6d-4faa-a0d7-4ca6fe261165
                      instrument_id: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                      instrument_name: GPT Trader Token
                      instrument_symbol: GPT-TRADER
                      market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                      market_name: Alpha Market
                      total_balance: 150
                      available_balance: "100"
                      locked_balance: "50"
                      last_trade_price: "45.50"
                      status: active
                      last_deposit_at: null
                      last_trading_activity_at: null
                      last_withdrawal_at: null
                      created_at: "2025-12-02T11:51:37Z"
                      updated_at: "2025-12-02T11:51:37Z"
                paging:
                  has_more: false
                  next_cursor: null
                  prev_cursor: null
  /trading/trading-accounts/{account_id}:
    get:
      tags:
        - Accounts
      summary: Get trading account details
      description: |
        Get detailed information about a specific trading account.
      operationId: tradingGetTradingAccount
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/trading-accounts/trading_account_6e6ad9d28eaae559' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              account_id = 'trading_account_6e6ad9d28eaae559'
              path = f'/api/v1/trading/trading-accounts/{account_id}'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              account = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const accountId = 'trading_account_6e6ad9d28eaae559';
              const path = `/api/v1/trading/trading-accounts/${accountId}`;
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const account = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"fmt"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              accountID := "trading_account_6e6ad9d28eaae559"
              const baseURL = "https://trading.api.thegrid.ai"
              path := fmt.Sprintf("/api/v1/trading/trading-accounts/%s", accountID)
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data TradingAccount `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: account_id
            in: path
            required: true
            schema:
              type: string
            description: |
              Unique identifier for the trading account (e.g., "trading_account_6e6ad9d28eaae559")
      responses:
        "200":
          description: |
            Trading account details
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/TradingAccount'
              example:
                data:
                  account_id: trading_account_6e6ad9d28eaae559
                  user_id: user_2e73aeab-3f3e-401f-9976-c78b9d326961
                  instrument_id: instrument_c18a986c-522b-475a-b319-f2d0ba04a64d
                  instrument_name: GPT Detail Token
                  instrument_symbol: GPT-DETAIL
                  market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                  market_name: Detail Market
                  total_balance: 250
                  available_balance: "200"
                  locked_balance: "50"
                  last_trade_price: "45.50"
                  status: active
                  last_deposit_at: null
                  last_trading_activity_at: null
                  last_withdrawal_at: null
                  created_at: "2025-12-02T11:51:37Z"
                  updated_at: "2025-12-02T11:51:37Z"
        "404":
          $ref: '#/components/responses/NotFound'
  /trading/transfers/trading-to-consumption:
    post:
      tags:
        - Transfers
      summary: Transfer to consumption
      description: |
        Transfers a specified quantity of an instrument from trading account to consumption account.
      operationId: transferToConsumption
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X POST 'https://trading-api.cortex.thegrid.ai/api/v1/trading/transfers/trading-to-consumption' \
                -H 'Content-Type: application/json' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT' \
                -d '{
                  "instrument_id": "instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0",
                  "quantity": 100
                }'
        -
            lang: Python
            source: |
              import json
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/transfers/trading-to-consumption'
              payload = {'instrument_id': 'instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0', 'quantity': 100}
              body = json.dumps(payload)
              headers = auth.get_headers('POST', path, body)
              response = requests.post(
                  f'https://trading.api.thegrid.ai{path}',
                  json=payload,
                  headers={
                      'Content-Type': 'application/json',
                      **headers
                  }
              )
              transfer = response.json()
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/transfers/trading-to-consumption';
              const payload = { instrument_id: 'instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0', quantity: 100 };
              const body = JSON.stringify(payload);
              const headers = auth.getHeaders('POST', path, body);
              const response = await axios.post(
                `https://trading.api.thegrid.ai${path}`,
                payload,
                {
                  headers: {
                    'Content-Type': 'application/json',
                    ...headers
                  }
                }
              );
              const transfer = response.data;
        -
            lang: Go
            source: |
              import (
              	"bytes"
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/transfers/trading-to-consumption"
              payload := map[string]interface{}{
              	"instrument_id": "instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0",
              	"quantity":      100,
              }
              bodyBytes, _ := json.Marshal(payload)
              bodyStr := string(bodyBytes)
              headers, _ := auth.GetHeaders("POST", path, bodyStr)
              req, _ := http.NewRequest("POST", baseURL+path, bytes.NewBuffer(bodyBytes))
              req.Header.Set("Content-Type", "application/json")
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	TransferID string `json:"transfer_id"`
              	Status     string `json:"status"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TransferRequest'
            example:
              instrument_id: "instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0"
              quantity: 100
      responses:
        "202":
          description: |
            Transfer initiated (processed asynchronously)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransferResponse'
  /trading/transfer-histories:
    get:
      tags:
        - Transfers
      summary: List transfer history
      description: |
        Returns transfer histories for authenticated user.
      operationId: listTransferHistory
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/transfer-histories' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/transfer-histories'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              history = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/transfer-histories';
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const history = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/transfer-histories"
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []TransferHistory `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: market_id
            in: query
            schema:
              type: string
            description: Filter by market ID
        -
            name: instrument_id
            in: query
            schema:
              type: string
            description: Filter by instrument ID
        -
            name: start_datetime
            in: query
            schema:
              type: string
              format: date-time
            description: Filter transfers at or after this time (ISO8601 or Unix timestamp)
        -
            name: end_datetime
            in: query
            schema:
              type: string
              format: date-time
            description: Filter transfers at or before this time (ISO8601 or Unix timestamp)
        -
            name: order_by
            in: query
            schema:
              type: string
              enum: [transferred_at, quantity]
            description: Field to sort by
        -
            name: order_direction
            in: query
            schema:
              type: string
              enum: [asc, desc]
              default: asc
            description: Sort direction
        -
            $ref: '#/components/parameters/next'
        -
            $ref: '#/components/parameters/prev'
        -
            $ref: '#/components/parameters/limit'
      responses:
        "200":
          description: |
            Transfer history
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransferHistoryResponse'
              example:
                data:
                  -
                      id: 362f5970-84d7-4752-9256-72068a628a03
                      transfer_id: transfer_3f0f4bda-def0-4db9-bd64-a6a37d39535e
                      account_id: consumption_account_cbf73393ef9e2ed0
                      sender_account_id: trading_account_6e6ad9d28eaae559
                      instrument_id: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                      instrument_name: Test Instrument
                      market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                      quantity: 200
                      transferred_at: "2026-01-09T17:32:59Z"
                      inserted_at: "2026-01-09T17:32:59Z"
                      updated_at: "2026-01-09T17:32:59Z"
                  -
                      id: ea4050dd-3b67-4d9b-bae6-e26dd708ac0c
                      transfer_id: transfer_3f0f4bda-def0-4db9-bd64-a6a37d39535e
                      account_id: consumption_account_2e3ed8507574eec9
                      sender_account_id: trading_account_6e6ad9d28eaae559
                      instrument_id: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
                      instrument_name: Test Instrument
                      market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                      quantity: 100
                      transferred_at: "2026-01-09T17:31:59Z"
                      inserted_at: "2026-01-09T17:32:59Z"
                      updated_at: "2026-01-09T17:32:59Z"
                paging:
                  has_more: false
                  next_cursor: null
                  prev_cursor: null
  /trading/price-histories:
    get:
      tags:
        - Markets
      summary: Get price history (OHLCV)
      description: |
        Returns OHLCV (Open, High, Low, Close, Volume) candle data for charting. 
        Use this endpoint to build price charts and analyze historical market data.
      operationId: tradingGetPriceHistories
      x-hideTryItPanel: true
      x-codeSamples:
        -
            lang: bash
            label: cURL
            source: |
              curl -X GET 'https://trading-api.cortex.thegrid.ai/api/v1/trading/price-histories' \
                -H 'x-thegrid-signature: YOUR_SIGNATURE' \
                -H 'x-thegrid-timestamp: YOUR_TIMESTAMP' \
                -H 'x-thegrid-fingerprint: YOUR_FINGERPRINT'
        -
            lang: Python
            source: |
              import requests
              
              auth = SignatureAuth(private_key, public_key)  # See auth docs for setup
              path = '/api/v1/trading/price-histories'
              headers = auth.get_headers('GET', path, '')
              response = requests.get(
                  f'https://trading.api.thegrid.ai{path}',
                  headers=headers
              )
              candles = response.json()['data']
        -
            lang: JavaScript
            source: |
              import axios from 'axios';
              
              const auth = new SignatureAuth(privateKey, publicKey);  // See auth docs for setup
              const path = '/api/v1/trading/price-histories';
              const headers = auth.getHeaders('GET', path, '');
              const response = await axios.get(
                `https://trading.api.thegrid.ai${path}`,
                { headers }
              );
              const candles = response.data.data;
        -
            lang: Go
            source: |
              import (
              	"encoding/json"
              	"io"
              	"net/http"
              	"time"
              )
              
              auth, _ := NewSignatureAuth(privateKey, publicKey)  // See auth docs for setup
              const baseURL = "https://trading.api.thegrid.ai"
              path := "/api/v1/trading/price-histories"
              headers, _ := auth.GetHeaders("GET", path, "")
              req, _ := http.NewRequest("GET", baseURL+path, nil)
              for k, v := range headers {
              	req.Header.Set(k, v)
              }
              client := &http.Client{Timeout: 10 * time.Second}
              resp, _ := client.Do(req)
              defer resp.Body.Close()
              body, _ := io.ReadAll(resp.Body)
              var result struct {
              	Data []PriceHistory `json:"data"`
              }
              json.Unmarshal(body, &result)
      security:
        -
            signatureAuth: []
      parameters:
        -
            name: market_id
            in: query
            schema:
              type: string
            description: Filter by market ID
        -
            name: resolution
            in: query
            schema:
              type: string
              enum: [1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w, 1M]
            description: |
              Candle resolution/timeframe. Determines the time period each candle represents.
        -
            name: from
            in: query
            schema:
              type: integer
            description: Start of time range (Unix timestamp in seconds)
        -
            name: to
            in: query
            schema:
              type: integer
            description: End of time range (Unix timestamp in seconds)
        -
            name: order_by
            in: query
            schema:
              type: string
              enum: [period_start]
            description: Field to sort by
        -
            name: order_direction
            in: query
            schema:
              type: string
              enum: [asc, desc]
              default: asc
            description: Sort direction
        -
            $ref: '#/components/parameters/next'
        -
            $ref: '#/components/parameters/prev'
        -
            $ref: '#/components/parameters/limit'
      responses:
        "200":
          description: |
            OHLCV candle data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PriceHistoryResponse'
              example:
                data:
                  -
                      time: "2026-02-12T07:00:00Z"
                      market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                      resolution: 1h
                      open: "45.00"
                      high: "45.75"
                      low: "44.80"
                      close: "45.50"
                      volume: 1200
                      trade_count: 48
                  -
                      time: "2026-02-12T08:00:00Z"
                      market_id: market_b310e860-97cd-45eb-bdc3-5be0b79295d0
                      resolution: 1h
                      open: "45.50"
                      high: "46.25"
                      low: "45.25"
                      close: "46.00"
                      volume: 1500
                      trade_count: 62
                paging:
                  has_more: true
                  next_cursor: "eyJpZCI6InByaWNlXzEyMyJ9"
                  prev_cursor: null
        "401":
          $ref: '#/components/responses/Unauthorized'
        "422":
          $ref: '#/components/responses/ValidationError'
components:
  securitySchemes:
    signatureAuth:
      type: apiKey
      in: header
      name: x-thegrid-signature
      description: |
        Ed25519 signature authentication. **All three headers are required** for every request:
        
        | Header | Description |
        |--------|-------------|
        | `x-thegrid-signature` | Base64-encoded Ed25519 signature of `{timestamp}{METHOD}{path}{body}`
        | `x-thegrid-timestamp` | Unix timestamp in seconds (must be within 30 seconds of server time) |
        | `x-thegrid-fingerprint` | SHA256 hash of your public key (Base64-encoded, padding stripped) |
        
        [See full authentication docs](./overview-trading-api/authentication)
  headers:
    x-request-id:
      description: |
        Unique identifier for the request. Use this value when contacting support 
        to help diagnose issues. This header is returned on every response.
      schema:
        type: string
        example: "GIkgbPVEdBDYQbcAAChF"
    x-ratelimit-limit:
      description: The maximum number of requests allowed in the current time window
      schema:
        type: integer
        example: 100
    x-ratelimit-remaining:
      description: The number of requests remaining in the current time window
      schema:
        type: integer
        example: 95
    x-ratelimit-reset:
      description: Unix timestamp (seconds) when the rate limit window resets
      schema:
        type: integer
        example: 1640995200
    x-ratelimit-retry-after:
      description: Seconds to wait before retrying (only present when rate limited)
      schema:
        type: integer
        example: 30
  parameters:
    next:
      name: next
      in: query
      schema:
        type: string
      description: |
        Cursor for forward pagination. Pass the `next_cursor` value from a previous response to fetch the next page. Mutually exclusive with `prev`.
    prev:
      name: prev
      in: query
      schema:
        type: string
      description: |
        Cursor for backward pagination. Pass the `prev_cursor` value from a previous response to fetch the previous page. Mutually exclusive with `next`.
    limit:
      name: limit
      in: query
      schema:
        type: integer
        default: 50
        maximum: 100
      description: |
        Number of items to return per page (max: 100)
  schemas:
    ErrorResponse:
      type: object
      properties:
        errors:
          type: object
          properties:
            detail:
              type: string
    CursorPaging:
      type: object
      description: |
        Cursor-based pagination
      properties:
        has_more:
          type: boolean
        next_cursor:
          type: string
          nullable: true
        prev_cursor:
          type: string
          nullable: true
    MarketWithInstruments:
      type: object
      properties:
        market_id:
          type: string
        name:
          type: string
        description:
          type: string
          nullable: true
        market_type:
          type: string
          enum:
            - spot
        status:
          type: string
          description: |
            Market status. Known values include active, inactive, suspended; API may return other values.
        allowed_instruments:
          type: array
          items:
            type: string
        instruments:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
                format: uuid
                description: Internal database ID
              instrument_id:
                type: string
              symbol:
                type: string
              name:
                type: string
              description:
                type: string
                nullable: true
              instrument_type:
                type: string
              status:
                type: string
              trading_params:
                type: object
                nullable: true
                properties:
                  min_quantity:
                    type: integer
                  max_quantity:
                    type: integer
                  quantity_increment:
                    type: integer
                  fee:
                    type: string
                    description: Fee rate (decimal string)
              ai_specs:
                type: object
                nullable: true
                properties:
                  context_window:
                    type: string
                    description: Maximum context window size in tokens
                  token_throughput:
                    type: string
                    description: Minimum token throughput rate in tokens per second
                  tokens_per_unit:
                    type: integer
                    description: Number of tokens per tradeable unit
                  unit_definition:
                    type: string
                  qualifying_models:
                    type: array
                    items:
                      type: string
                  max_output_length:
                    type: integer
                    description: Maximum output length in tokens
                  min_performance_benchmark:
                    type: number
                    description: Minimum performance benchmark score
                  min_time_to_first_token_ms:
                    type: integer
                    description: Maximum time to first token in milliseconds
                  model_id:
                    type: string
                    description: Model identifier
                    nullable: true
                  model_version:
                    type: string
                    description: Model version
                    nullable: true
                  usage:
                    type: string
                    description: Usage type or category
              basic_info:
                type: object
                nullable: true
                properties:
                  service_type:
                    type: string
                  model_category:
                    type: string
                    nullable: true
                    description: Model category classification
              sla_requirements:
                type: object
                nullable: true
                properties:
                  availability_target:
                    type: number
                  availability_sla:
                    type: number
                    description: Availability SLA (percentage)
                    nullable: true
                  max_latency_ms:
                    type: integer
                  min_latency_ms:
                    type: integer
                    description: Minimum latency in milliseconds
                    nullable: true
                  quality_score_min:
                    type: number
              last_trade_at:
                type: string
                format: date-time
                nullable: true
              last_trade_price:
                type: string
                nullable: true
              last_quote_at:
                type: string
                format: date-time
                nullable: true
              total_volume:
                type: integer
                nullable: true
              volume_24h:
                type: integer
                nullable: true
              total_trades:
                type: integer
                nullable: true
              total_quotes:
                type: integer
                nullable: true
              price_range_24h_high:
                type: string
                nullable: true
                description: Highest price in last 24 hours
              price_range_24h_low:
                type: string
                nullable: true
                description: Lowest price in last 24 hours
              created_at:
                type: string
                format: date-time
                nullable: true
              updated_at:
                type: string
                format: date-time
                nullable: true
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    Ticker:
      type: object
      description: |
        Market ticker data including last trade, best bid/ask prices, and 24-hour volume.
      properties:
        last_price:
          type: string
          nullable: true
          description: |
            Last trade price (decimal string)
        last_trade_size:
          type: integer
          nullable: true
          description: |
            Last trade size
        last_trade_timestamp:
          type: string
          format: date-time
          nullable: true
          description: |
            Timestamp of the most recent trade (ISO8601)
        lowest_ask:
          type: string
          nullable: true
          description: |
            Best ask (decimal string)
        highest_bid:
          type: string
          nullable: true
          description: |
            Best bid (decimal string)
        volume_24h:
          type: integer
          nullable: true
          description: |
            24h volume
    OrderbookLevel:
      type: object
      description: |
        Single price level in the order book (buy or sell side).
      properties:
        price:
          type: string
        size:
          type: integer
        total:
          type: integer
        order_count:
          type: integer
    OrderbookResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            buy:
              type: array
              items:
                $ref: '#/components/schemas/OrderbookLevel'
            sell:
              type: array
              items:
                $ref: '#/components/schemas/OrderbookLevel'
            highest_bid:
              type: string
              nullable: true
            lowest_ask:
              type: string
              nullable: true
            highest_bid_price:
              type: string
              nullable: true
            lowest_ask_price:
              type: string
              nullable: true
            updated_at:
              type: string
              format: date-time
    PublicTrade:
      type: object
      description: |
        Public trade for a market (not scoped to the authenticated user; no order_id or trading_account_id).
      properties:
        id:
          type: string
          format: uuid
        trade_id:
          type: string
          description: Public trade ID
        market_id:
          type: string
        market_name:
          type: string
          nullable: true
        instrument_id:
          type: string
        instrument_symbol:
          type: string
          nullable: true
        instrument_name:
          type: string
          nullable: true
        price:
          type: string
        quantity:
          type: integer
        side:
          type: string
          enum:
            - buy
            - sell
        total_value:
          type: string
        status:
          type: string
        execution_timestamp:
          type: string
          format: date-time
          nullable: true
        settlement_timestamp:
          type: string
          format: date-time
          nullable: true
    InstrumentSummary:
      type: object
      properties:
        instrument_id:
          type: string
          example: instrument_e0b04b8a-ce1f-4ccc-a4ca-2a47825d69b0
        symbol:
          type: string
          example: CHAT-FAST
        name:
          type: string
          example: Chat Fast Tokens
        description:
          type: string
          example: Fast chat inference capacity
        type:
          type: string
          description: |
            Category of instrument.
            - `ai_commodity`: Tradeable AI inference capacity (e.g., tokens for LLM usage)
            - `currency`: Fiat currency used for settlement (e.g., USD)
          enum:
            - ai_commodity
            - currency
            - commodity
          example: ai_commodity
        status:
          type: string
          enum:
            - draft
            - active
            - inactive
            - suspended
            - deleted
          example: active
        basic_info:
          type: object
          nullable: true
          properties:
            service_type:
              type: string
              example: text_generation
            model_category:
              type: string
              description: Model category classification
              nullable: true
            currency_code:
              type: string
              example: USD
            precision:
              type: integer
              example: 2
        trading_params:
          type: object
          nullable: true
          properties:
            min_quantity:
              type: integer
              example: 1
            max_quantity:
              type: integer
              example: 10000
            quantity_increment:
              type: integer
              example: 1
            fee:
              type: string
              description: Fee rate (decimal string)
        ai_specs:
          type: object
          nullable: true
          properties:
            context_window:
              type: string
              description: |
                Maximum context window size in tokens
              example: "8000"
            token_throughput:
              type: string
              description: |
                Minimum token throughput rate in tokens per second
              example: "100"
            tokens_per_unit:
              type: integer
              description: |
                Number of tokens per tradeable unit
              example: 1000000
            unit_definition:
              type: string
              example: 1M tokens
            qualifying_models:
              type: array
              items:
                type: string
              description: |
                List of AI models that qualify for this instrument
              example:
                - gpt-5
                - gpt-5-mini
            max_output_length:
              type: integer
              description: Maximum output length in tokens
            min_performance_benchmark:
              type: number
              description: Minimum performance benchmark score
            min_time_to_first_token_ms:
              type: integer
              description: Maximum time to first token in milliseconds
            model_id:
              type: string
              description: Model identifier
              nullable: true
            model_version:
              type: string
              description: Model version
              nullable: true
            usage:
              type: string
              description: Usage type or category
    InstrumentListResponse:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/InstrumentSummary'
        paging:
          $ref: '#/components/schemas/CursorPaging'
    InstrumentDetail:
      type: object
      properties:
        instrument_id:
          type: string
        symbol:
          type: string
        name:
          type: string
        description:
          type: string
        type:
          type: string
          enum:
            - ai_commodity
            - currency
            - commodity
        status:
          type: string
          enum:
            - draft
            - active
            - inactive
            - suspended
            - deleted
        ai_specs:
          type: object
          nullable: true
          properties:
            context_window:
              type: string
              description: |
                Maximum context window size in tokens
            token_throughput:
              type: string
              description: |
                Minimum token throughput rate in tokens per second
            tokens_per_unit:
              type: integer
              description: |
                Number of tokens per tradeable unit
              example: 1000000
            unit_definition:
              type: string
            qualifying_models:
              type: array
              items:
                type: string
              description: |
                List of AI models that qualify for this instrument
            max_output_length:
              type: integer
              description: Maximum output length in tokens
            min_performance_benchmark:
              type: number
              description: Minimum performance benchmark score
            min_time_to_first_token_ms:
              type: integer
              description: Maximum time to first token in milliseconds
            model_id:
              type: string
              description: Model identifier
              nullable: true
            model_version:
              type: string
              description: Model version
              nullable: true
            usage:
              type: string
              description: Usage type or category
        basic_info:
          type: object
          nullable: true
          properties:
            service_type:
              type: string
            model_category:
              type: string
              description: Model category classification
              nullable: true
            currency_code:
              type: string
            precision:
              type: integer
        sla_requirements:
          type: object
          properties:
            availability_target:
              type: number
              description: |
                Target uptime as a percentage (e.g., 99.95 means 99.95% availability)
            availability_sla:
              type: number
              description: Availability SLA (percentage). May be present in API responses.
              nullable: true
            max_latency_ms:
              type: integer
              description: |
                Maximum acceptable response latency in milliseconds
            min_latency_ms:
              type: integer
              description: Minimum latency in milliseconds. May be present in API responses.
              nullable: true
            quality_score_min:
              type: number
              description: |
                Minimum quality score threshold (0-100)
        trading_params:
          type: object
          properties:
            min_quantity:
              type: integer
            max_quantity:
              type: integer
            quantity_increment:
              type: integer
            fee:
              type: string
              description: Fee rate (decimal string)
        last_trade_price:
          type: string
          nullable: true
        last_trade_at:
          type: string
          format: date-time
          nullable: true
        last_quote_at:
          type: string
          format: date-time
          nullable: true
          description: Timestamp of most recent quote
        total_volume:
          type: string
        volume_24h:
          type: string
        total_trades:
          type: integer
        total_quotes:
          type: integer
        price_range_24h_high:
          type: string
          nullable: true
          description: Highest price in last 24 hours
        price_range_24h_low:
          type: string
          nullable: true
          description: Lowest price in last 24 hours
    InstrumentDetailResponse:
      type: object
      properties:
        data:
          $ref: '#/components/schemas/InstrumentDetail'
    Order:
      type: object
      properties:
        id:
          type: string
        market_id:
          type: string
        market_name:
          type: string
          nullable: true
        instrument_id:
          type: string
        instrument_name:
          type: string
          nullable: true
        instrument_symbol:
          type: string
          nullable: true
        trader_id:
          type: string
        type:
          type: string
          enum:
            - limit
            - market
            - stop
            - stop_limit
        side:
          type: string
          enum:
            - buy
            - sell
        price:
          type: string
          nullable: true
          description: |
            Limit price per unit in quote currency (USD). Null for market orders.
        size:
          type: integer
          description: |
            Total order quantity in units
        filled_quantity:
          type: integer
          description: |
            Number of units that have been filled so far
        average_price:
          type: string
          nullable: true
          description: |
            Volume-weighted average fill price across all fills for this order
        fee:
          type: string
          description: |
            Trading fee charged for this order in quote currency (USD)
        status:
          type: string
          enum:
            - active
            - pending
            - partially_filled
            - filled
            - closed
            - cancellation_pending
        closure_reason:
          type: string
          nullable: true
          description: |
            Reason the order was closed. Only present when status is "closed" or "filled".
            - `filled`: Order was completely filled
            - `cancelled`: Order was manually cancelled by the user
            - `cancel_and_replace`: Order was cancelled as part of a cancel-and-replace operation
            - `expired`: Order expired (e.g., day orders at end of trading day)
            - `rejected`: Order was rejected by the matching engine
            - `partially_filled_no_liquidity`: Order was partially filled then closed because no remaining liquidity was available
            - `partially_filled_max_slippage`: Order was partially filled then closed because price moved beyond acceptable slippage
            - `partially_filled_insufficient_balance`: Order was partially filled then closed due to insufficient balance
            - `no_fill_no_liquidity`: Market order could not fill due to no available liquidity
            - `no_fill_max_slippage`: Market order could not fill within the acceptable slippage tolerance
            - `no_fill_insufficient_balance`: Order could not fill due to insufficient balance
          enum:
            - filled
            - cancelled
            - cancel_and_replace
            - expired
            - rejected
            - partially_filled_no_liquidity
            - partially_filled_max_slippage
            - partially_filled_insufficient_balance
            - no_fill_no_liquidity
            - no_fill_max_slippage
            - no_fill_insufficient_balance
            - null
        time_in_force:
          type: string
          enum:
            - gtc
            - ioc
            - fok
            - day
          description: |
            Order duration policy.
            - `gtc` (Good Till Cancelled): Order remains active until completely filled or manually cancelled
            - `ioc` (Immediate Or Cancel): Order executes immediately for available quantity, remainder is cancelled
            - `fok` (Fill Or Kill): Order must be completely filled immediately or entirely cancelled
            - `day`: Order expires at the end of the trading day if not filled
        stop_price:
          type: string
          nullable: true
        client_order_id:
          type: string
          nullable: true
        submitted_at:
          type: string
          format: date-time
        closed_at:
          type: string
          format: date-time
          nullable: true
        triggered_by_auto_top_up:
          type: boolean
          description: |
            Whether this order was automatically triggered by the auto top-up feature
    TradingOrderListResponse:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/Order'
        paging:
          $ref: '#/components/schemas/CursorPaging'
    TradingCreateOrderRequest:
      type: object
      required:
        - market_id
        - side
        - type
        - quantity
      properties:
        market_id:
          type: string
          description: |
            Market identifier where the order will be placed
          example: "market_CHAT-PRIME_USD"
        client_order_id:
          type: string
          description: |
            Optional client-provided order ID for idempotency. Must be unique per account. Duplicate IDs will return a 422 error with message "client_order_id already exists".
          example: "my-order-123"
          nullable: true
        side:
          type: string
          enum:
            - buy
            - sell
          description: |
            Order side: "buy" to purchase the instrument, "sell" to sell. Value is normalized to lowercase.
          example: "buy"
        type:
          type: string
          enum:
            - limit
            - market
          description: |
            Order type: "limit" executes at specified price or better, "market" executes immediately at best available price. Value is normalized to lowercase.
          example: "limit"
        price:
          type: string
          description: |
            Price per unit in quote currency (USD). **Required for limit orders, must be omitted for market orders.** Must be a positive number >= 0.0001 with at most 4 decimal places (tick size).
          example: "45.50"
        quantity:
          type: integer
          minimum: 1
          maximum: 100
          description: |
            Number of units to buy or sell. Must be a positive integer, maximum 100 per order.
          example: 100
        time_in_force:
          type: string
          enum:
            - gtc
            - ioc
            - fok
            - day
          description: |
            Order duration policy. Value is normalized to lowercase.
            - `gtc` (Good Till Cancelled): Order remains active until completely filled or manually cancelled
            - `ioc` (Immediate Or Cancel): Order executes immediately for available quantity, remainder is cancelled
            - `fok` (Fill Or Kill): Order must be completely filled immediately or entirely cancelled
            - `day`: Order expires at the end of the trading day if not filled
          default: gtc
          example: "gtc"
    TradeListResponse:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/UserTrade'
        paging:
          $ref: '#/components/schemas/CursorPaging'
    UserTrade:
      type: object
      description: |
        Trade details from the user's perspective
      properties:
        id:
          type: string
          format: uuid
        trade_id:
          type: string
          description: |
            Trade identifier
        market_id:
          type: string
        market_name:
          type: string
        instrument_id:
          type: string
        instrument_name:
          type: string
        instrument_symbol:
          type: string
        order_id:
          type: string
          description: |
            The user's order ID associated with this trade
        trading_account_id:
          type: string
          description: |
            The user's trading account ID
        price:
          type: string
        quantity:
          type: integer
        total_value:
          type: string
        fee:
          type: string
        side:
          type: string
          enum:
            - buy
            - sell
        status:
          type: string
          enum:
            - executed
            - settled
        execution_timestamp:
          type: string
          format: date-time
        settlement_timestamp:
          type: string
          format: date-time
    TradingAccount:
      type: object
      properties:
        account_id:
          type: string
        user_id:
          type: string
        instrument_id:
          type: string
        instrument_name:
          type: string
        instrument_symbol:
          type: string
        market_id:
          type: string
        market_name:
          type: string
        total_balance:
          type: integer
          description: |
            Sum of available and locked balances (units)
        available_balance:
          type: string
          description: |
            Balance available for placing new orders (decimal string)
        locked_balance:
          type: string
          description: |
            Balance currently locked in open orders (decimal string)
        last_trade_price:
          type: string
          nullable: true
        status:
          type: string
          enum:
            - active
            - inactive
        last_deposit_at:
          type: string
          format: date-time
          nullable: true
        last_trading_activity_at:
          type: string
          format: date-time
          nullable: true
        last_withdrawal_at:
          type: string
          format: date-time
          nullable: true
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    CurrencyTradingAccount:
      type: object
      properties:
        account_id:
          type: string
        user_id:
          type: string
        currency:
          type: string
        total_balance:
          type: string
        available_balance:
          type: string
        locked_balance:
          type: string
        status:
          type: string
        last_deposit_at:
          type: string
          format: date-time
          nullable: true
          description: |
            Timestamp of last deposit (null if none)
        last_trading_activity_at:
          type: string
          format: date-time
          nullable: true
          description: |
            Timestamp of last trading activity (null if none)
        last_withdrawal_at:
          type: string
          format: date-time
          nullable: true
          description: |
            Timestamp of last withdrawal (null if none)
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    ConsumptionAccountsResponse:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/ConsumptionAccount'
        paging:
          $ref: '#/components/schemas/CursorPaging'
    ConsumptionAccount:
      type: object
      properties:
        account_id:
          type: string
        user_id:
          type: string
        instrument_id:
          type: string
        total_balance:
          type: integer
          description: |
            Total balance in the account
        available_balance:
          type: integer
          description: |
            Available balance for consumption
        committed_balance:
          type: integer
          description: |
            Balance currently reserved for a consumption request. Unused tokens will be returned after request is fulfilled.
        uncommitted_balance:
          type: integer
          description: |
            Balance currently uncommitted
        status:
          type: string
          enum:
            - active
            - inactive
        total_commitments:
          type: integer
          description: |
            Total number of commitments
        total_deposits:
          type: integer
          description: |
            Total number of deposits
        total_transfers_in:
          type: integer
          description: |
            Total number of transfers into the account
        total_transfers_out:
          type: integer
          description: |
            Total number of transfers out of the account
        total_withdrawals:
          type: integer
          description: |
            Total number of withdrawals
        last_commitment_at:
          type: string
          format: date-time
          nullable: true
          description: |
            Timestamp of last commitment (null if none)
        last_deposit_at:
          type: string
          format: date-time
          nullable: true
          description: |
            Timestamp of last deposit (null if none)
        last_transfer_at:
          type: string
          format: date-time
          nullable: true
          description: |
            Timestamp of last transfer (null if none)
        last_withdrawal_at:
          type: string
          format: date-time
          nullable: true
          description: |
            Timestamp of last withdrawal (null if none)
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    TransferRequest:
      type: object
      required:
        - instrument_id
        - quantity
      properties:
        instrument_id:
          type: string
          description: |
            The instrument to transfer from your trading account to your consumption account
          example: "instrument_c18a986c-522b-475a-b319-f2d0ba04a64d"
        quantity:
          type: integer
          minimum: 1
          description: |
            Number of units to transfer. Must have sufficient available balance in your trading account.
          example: 100
    TransferResponse:
      type: object
      properties:
        status:
          type: string
          enum:
            - success
        transfer_id:
          type: string
    TransferHistory:
      type: object
      properties:
        id:
          type: string
          format: uuid
        transfer_id:
          type: string
        account_id:
          type: string
        sender_account_id:
          type: string
        instrument_id:
          type: string
        instrument_name:
          type: string
        market_id:
          type: string
        quantity:
          type: integer
        transferred_at:
          type: string
          format: date-time
        inserted_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    TransferHistoryResponse:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/TransferHistory'
        paging:
          $ref: '#/components/schemas/CursorPaging'
    PriceHistory:
      type: object
      description: |
        OHLCV candle data for a specific time period
      properties:
        time:
          type: string
          format: date-time
          description: |
            Period start time (ISO8601)
        market_id:
          type: string
          description: |
            Market identifier
        resolution:
          type: string
          enum: [1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w, 1M]
          description: |
            Candle resolution/timeframe
        open:
          type: string
          description: |
            Opening price for the period (decimal string)
        high:
          type: string
          description: |
            Highest price during the period (decimal string)
        low:
          type: string
          description: |
            Lowest price during the period (decimal string)
        close:
          type: string
          description: |
            Closing price for the period (decimal string)
        volume:
          type: integer
          description: |
            Total trading volume during the period
        trade_count:
          type: integer
          description: |
            Number of trades during the period
    PriceHistoryResponse:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/PriceHistory'
        paging:
          $ref: '#/components/schemas/CursorPaging'
  responses:
    Unauthorized:
      description: |
        Unauthorized - Invalid or missing authentication headers
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit:
          $ref: '#/components/headers/x-ratelimit-limit'
        x-ratelimit-remaining:
          $ref: '#/components/headers/x-ratelimit-remaining'
        x-ratelimit-reset:
          $ref: '#/components/headers/x-ratelimit-reset'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            data: null
            error: "Invalid signature"
            errors:
              detail: "The provided signature does not match the expected value"
            meta:
              request_id: "GIkgbPVEdBDYQbcAAChF"
              timestamp: "2026-01-15T10:30:00Z"
    NotFound:
      description: |
        Not found - The requested resource does not exist
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit:
          $ref: '#/components/headers/x-ratelimit-limit'
        x-ratelimit-remaining:
          $ref: '#/components/headers/x-ratelimit-remaining'
        x-ratelimit-reset:
          $ref: '#/components/headers/x-ratelimit-reset'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            data: null
            error: "Resource not found"
            errors:
              detail: "The requested resource could not be found"
            meta:
              request_id: "GIkgbPVEdBDYQbcAAChF"
              timestamp: "2026-01-15T10:30:00Z"
    ValidationError:
      description: |
        Validation error - Request parameters failed validation
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit:
          $ref: '#/components/headers/x-ratelimit-limit'
        x-ratelimit-remaining:
          $ref: '#/components/headers/x-ratelimit-remaining'
        x-ratelimit-reset:
          $ref: '#/components/headers/x-ratelimit-reset'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            data: null
            error: "Validation failed"
            errors:
              detail: "One or more fields failed validation"
              fields:
                price: "must be a positive number"
                quantity: "must be at least 1"
            meta:
              request_id: "GIkgbPVEdBDYQbcAAChF"
              timestamp: "2026-01-15T10:30:00Z"
    RateLimitExceeded:
      description: |
        Rate limit exceeded - Too many requests in the current time window
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit:
          $ref: '#/components/headers/x-ratelimit-limit'
        x-ratelimit-remaining:
          description: Will be 0 when rate limited
          schema:
            type: integer
            example: 0
        x-ratelimit-reset:
          $ref: '#/components/headers/x-ratelimit-reset'
        x-ratelimit-retry-after:
          $ref: '#/components/headers/x-ratelimit-retry-after'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            data: null
            error: "Rate limit exceeded"
            errors:
              detail: "You have exceeded the rate limit. Please wait before making more requests."              
              retry_after: 30
            meta:
              request_id: "GIkgbPVEdBDYQbcAAChF"
              timestamp: "2026-01-15T10:30:00Z"
