# API

## X-API-Key Authentication Guide

### Overview

vDEX supports two authentication methods for accessing protected endpoints:

1. **Bearer Token (JWT)** - For client-side applications (web, mobile)
2. **X-API-Key** - For server-side applications (trading bots, automated systems)

This guide focuses on **X-API-Key** authentication for server-to-server communication.

### Getting Your API Key

Your API key is automatically generated when you first log in to the platform. To retrieve it:

1. [Contact our support team](https://t.me/VDEX_Community)
2. Provide your wallet address for verification
3. We'll send you your API key securely

Self-custodial API key generation is coming soon.

### API Key Format

```
vdex_<64-hexadecimal-characters>

Example:
vdex_f7e6d5c4b3a2918273645f5e4d3c2b1a0f9e8d7c6b5a4938271605f4e3d2c1b0

```

### How to Use

#### Basic Usage

Add the `X-API-Key` header to your HTTP requests:

```bash
curl -X GET <https://api.vdex.com/v1/user/balance> \\\\
  -H "X-API-Key: vdex_your_api_key_here"

```

### Available Endpoints

All authenticated endpoints support both Bearer token and X-API-Key authentication:

For complete API documentation, visit: <https://d3p6ozwmy1xgo4.cloudfront.net/index.html#/>

### Environment Variable Setup

#### .env File

```bash
# .env
VDEX_API_KEY=vdex_your_api_key_here
VDEX_BASE_URL=https://api.vdex.com/v1

```

#### Load in Your Application

**Node.js:**

```jsx
require('dotenv').config();
const apiKey = process.env.VDEX_API_KEY;

```

**Python:**

```python
from dotenv import load_dotenv
import os

load_dotenv()
api_key = os.getenv('VDEX_API_KEY')

```

**Go:**

```go
import "github.com/joho/godotenv"

godotenv.Load()
apiKey := os.Getenv("VDEX_API_KEY")

```

### Error Responses

#### Authentication Errors

```json
{
  "error": "missing authentication",
  "code": 401
}

```

**Solution:** Ensure `X-API-Key` header is present

```json
{
  "error": "invalid api key",
  "code": 401
}

```

**Solution:** Verify your API key is correct

```json
{
  "error": "invalid api key format",
  "code": 401
}

```

#### Placing an Order and Getting Balance (JavaScript/TypeScript)

Use your `X-API-Key` in the `X-API-Key` header. Examples below use Node 18+ native `fetch`.

```tsx
// setup.ts
import 'dotenv/config'

interface RequestHeaders {
  [key: string]: string
}

interface CreateLeverageOrderRequest {
  price: number
  leverage_type: 'cross' | 'isolated'
  quantity: number
  direction: 'buy' | 'sell'
  order_type: 'MarketOpen' | 'LimitOpen'
  expiration_time_in_min?: number
  base_asset_id: string
  initial_margin_asset_id: string
  initial_margin: number
  leverage: number
  take_profit_price?: number
  take_profit_amount?: number
  stop_loss_price?: number
  stop_loss_amount?: number
  is_mobile?: boolean
}

function getBaseUrl() {
  const baseUrl = process.env.VDEX_BASE_URL || '<https://api.vdex.com>'
  return baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl
}

function createHeaders({ apiKey }: { apiKey: string }): RequestHeaders {
  if (!apiKey || !apiKey.startsWith('vdex_')) throw new Error('Missing or invalid VDEX_API_KEY')
  return {
    'X-API-Key': apiKey,
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
}

async function httpJson<T>({ url, method, headers, body }: {
  url: string
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
  headers: RequestHeaders
  body?: unknown
}): Promise<T> {
  const res = await fetch(url, {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined
  })
  if (!res.ok) {
    const text = await res.text().catch(() => '')
    throw new Error(`HTTP ${res.status} ${res.statusText}${text ? `: ${text}` : ''}`)
  }
  return res.json() as Promise<T>
}

// GET /v2/users/balances
export async function getBalances(): Promise<unknown> {
  const baseUrl = getBaseUrl()
  const headers = createHeaders({ apiKey: process.env.VDEX_API_KEY as string })
  return httpJson({ url: `${baseUrl}/v2/users/balances`, method: 'GET', headers })
}

// POST /v2/orders
export async function placeOrder(order: CreateLeverageOrderRequest): Promise<unknown> {
  const baseUrl = getBaseUrl()
  const headers = createHeaders({ apiKey: process.env.VDEX_API_KEY as string })
  return httpJson({ url: `${baseUrl}/v2/orders`, method: 'POST', headers, body: order })
}

// Example usage
async function main() {
  const balances = await getBalances()
  console.log('balances', balances)

  const order: CreateLeverageOrderRequest = {
    price: 65000,
    leverage_type: 'cross',
    quantity: 0.01,
    direction: 'buy',
    order_type: 'LimitOpen',
    expiration_time_in_min: 60,
    base_asset_id: 'BTCUSD',
    initial_margin_asset_id: 'USDT',
    initial_margin: 100,
    leverage: 10,
    take_profit_price: 70000,
    stop_loss_price: 62000
  }

  const placed = await placeOrder(order)
  console.log('order', placed)
}

main().catch(err => {
  console.error(err)
  process.exit(1)
})

```

* Replace `base_asset_id`, `initial_margin_asset_id`, and other fields with valid values for your market. You can query supported pairs via `GET /v2/tokens/supported-pairs`.
* For market orders, set `order_type` to `MarketOpen` and omit `price`.

#### cURL quick examples

* Get balances:

```bash
curl -sS -X GET "$VDEX_BASE_URL/v2/users/balances" \\\\
  -H "X-API-Key: $VDEX_API_KEY" \\\\
  -H "Accept: application/json"

```

* Place order:

```bash
curl -sS -X POST "$VDEX_BASE_URL/v2/orders" \\\\
  -H "X-API-Key: $VDEX_API_KEY" \\\\
  -H "Content-Type: application/json" \\\\
  -d '{
    "price": 65000,
    "leverage_type": "cross",
    "quantity": 0.01,
    "direction": "buy",
    "order_type": "LimitOpen",
    "expiration_time_in_min": 60,
    "base_asset_id": "BTCUSD",
    "initial_margin_asset_id": "USDT",
    "initial_margin": 100,
    "leverage": 10,
    "take_profit_price": 70000,
    "stop_loss_price": 62000
  }'

```


---

# Agent Instructions: Querying This Documentation

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

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

```
GET https://docs.vdex.trade/trading/api.md?ask=<question>
```

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

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