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

# API Documentation

### Overview

VEXAR provides comprehensive REST and WebSocket APIs for automated trading, market data access, and account management.

### Getting Started

#### Base URLs

```
REST API: https://api.vexatrade.com/v1
WebSocket: wss://stream.vexatrade.com
```

#### Authentication

**Generating API Keys**

1. Log in to VEXAR
2. Navigate to Account → API Management
3. Click "Generate New API Key"
4. Set permissions:
   * 🔍 Read: View account data
   * 💸 Trade: Place and cancel orders
   * ⚖️ Withdraw: Withdraw funds (optional)
5. Save API Key and Secret securely

⚠️ **Secret is shown only once!**

**Authentication Methods**

**API Key Authentication:**

```http
GET /v1/account/balance
X-API-KEY: your_api_key_here
X-API-SIGNATURE: generated_signature
X-API-TIMESTAMP: 1704067200000
```

**Signature Generation:**

```python
import hmac
import hashlib
import time

def generate_signature(secret, timestamp, method, path, body=''):
    message = f"{timestamp}{method}{path}{body}"
    signature = hmac.new(
        secret.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()
    return signature

# Example
timestamp = int(time.time() * 1000)
method = 'GET'
path = '/v1/account/balance'
signature = generate_signature(api_secret, timestamp, method, path)
```

### REST API

#### Rate Limits

| Tier       | Requests/Minute | Orders/Second |
| ---------- | --------------- | ------------- |
| Free       | 1,000           | 10            |
| Pro        | 10,000          | 100           |
| Enterprise | Custom          | Custom        |

#### Market Data Endpoints

**Get Ticker**

```http
GET /v1/market/ticker/{symbol}
```

**Parameters:**

* `symbol` (string, required): Trading pair (e.g., BTCUSDT)

**Response:**

```json
{
  "symbol": "BTCUSDT",
  "lastPrice": "42350.50",
  "volume24h": "1234567890",
  "high24h": "43200.00",
  "low24h": "41800.00",
  "priceChange24h": "+2.45%",
  "timestamp": 1704067200000
}
```

**Get Order Book**

```http
GET /v1/market/orderbook/{symbol}
```

**Parameters:**

* `symbol` (string, required)
* `depth` (integer, optional, default: 20): Number of price levels

**Response:**

```json
{
  "symbol": "BTCUSDT",
  "timestamp": 1704067200000,
  "bids": [
    ["42350.00", "0.5"],
    ["42349.50", "1.2"]
  ],
  "asks": [
    ["42350.50", "0.8"],
    ["42351.00", "1.5"]
  ]
}
```

**Get Recent Trades**

```http
GET /v1/market/trades/{symbol}
```

**Parameters:**

* `symbol` (string, required)
* `limit` (integer, optional, default: 50, max: 500)

**Response:**

```json
{
  "symbol": "BTCUSDT",
  "trades": [
    {
      "id": "12345",
      "price": "42350.50",
      "amount": "0.5",
      "side": "buy",
      "timestamp": 1704067200000
    }
  ]
}
```

#### Trading Endpoints

**Place Order**

```http
POST /v1/trading/order
Content-Type: application/json
X-API-KEY: your_api_key
X-API-SIGNATURE: signature
X-API-TIMESTAMP: timestamp
```

**Request Body:**

```json
{
  "symbol": "BTCUSDT",
  "side": "buy",
  "type": "limit",
  "price": "42000.00",
  "amount": "0.1",
  "leverage": 10,
  "timeInForce": "GTC"
}
```

**Parameters:**

* `symbol` (string, required)
* `side` (string, required): "buy" or "sell"
* `type` (string, required): "market", "limit", "stop"
* `price` (string, required for limit/stop)
* `amount` (string, required)
* `leverage` (integer, optional, 1-20)
* `timeInForce` (string, optional): "GTC", "IOC", "FOK"

**Response:**

```json
{
  "orderId": "ORD-123456",
  "status": "pending",
  "symbol": "BTCUSDT",
  "side": "buy",
  "type": "limit",
  "price": "42000.00",
  "amount": "0.1",
  "filled": "0",
  "remaining": "0.1",
  "timestamp": 1704067200000
}
```

**Cancel Order**

```http
DELETE /v1/trading/order/{orderId}
```

**Response:**

```json
{
  "orderId": "ORD-123456",
  "status": "cancelled",
  "timestamp": 1704067200000
}
```

**Get Open Orders**

```http
GET /v1/trading/orders
```

**Parameters:**

* `symbol` (string, optional): Filter by symbol
* `limit` (integer, optional, default: 50)

**Response:**

```json
{
  "orders": [
    {
      "orderId": "ORD-123456",
      "symbol": "BTCUSDT",
      "side": "buy",
      "type": "limit",
      "price": "42000.00",
      "amount": "0.1",
      "filled": "0.05",
      "remaining": "0.05",
      "status": "partial",
      "timestamp": 1704067200000
    }
  ]
}
```

#### Account Endpoints

**Get Balance**

```http
GET /v1/account/balance
```

**Response:**

```json
{
  "balances": [
    {
      "asset": "USDC",
      "total": "10000.00",
      "available": "8500.00",
      "locked": "1500.00"
    },
    {
      "asset": "BTC",
      "total": "0.5",
      "available": "0.3",
      "locked": "0.2"
    }
  ],
  "timestamp": 1704067200000
}
```

**Get Positions**

```http
GET /v1/account/positions
```

**Response:**

```json
{
  "positions": [
    {
      "symbol": "BTCUSDT",
      "side": "long",
      "size": "0.5",
      "entryPrice": "42000.00",
      "markPrice": "42500.00",
      "liquidationPrice": "37800.00",
      "leverage": 10,
      "unrealizedPnl": "250.00",
      "realizedPnl": "0",
      "margin": "2100.00",
      "timestamp": 1704067200000
    }
  ]
}
```

### WebSocket API

#### Connection

```javascript
const ws = new WebSocket('wss://stream.vexatrade.com');

ws.onopen = () => {
  console.log('Connected');
  
  // Subscribe to ticker
  ws.send(JSON.stringify({
    method: 'subscribe',
    params: ['ticker@BTCUSDT']
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(data);
};
```

#### Subscription Channels

**Ticker Channel**

**Subscribe:**

```json
{
  "method": "subscribe",
  "params": ["ticker@BTCUSDT"]
}
```

**Message:**

```json
{
  "channel": "ticker@BTCUSDT",
  "data": {
    "symbol": "BTCUSDT",
    "lastPrice": "42350.50",
    "volume24h": "1234567890",
    "priceChange24h": "+2.45%",
    "timestamp": 1704067200000
  }
}
```

**Order Book Channel**

**Subscribe:**

```json
{
  "method": "subscribe",
  "params": ["orderbook@BTCUSDT"]
}
```

**Message:**

```json
{
  "channel": "orderbook@BTCUSDT",
  "data": {
    "bids": [["42350.00", "0.5"]],
    "asks": [["42350.50", "0.8"]],
    "timestamp": 1704067200000
  }
}
```

**Trades Channel**

**Subscribe:**

```json
{
  "method": "subscribe",
  "params": ["trades@BTCUSDT"]
}
```

**User Data Channel (Authenticated)**

**Subscribe:**

```json
{
  "method": "subscribe",
  "params": ["user@orders", "user@positions"],
  "apiKey": "your_api_key",
  "signature": "generated_signature",
  "timestamp": 1704067200000
}
```

### Code Examples

#### Python

**Basic Trading Bot:**

```python
import requests
import hmac
import hashlib
import time

class VexarClient:
    def __init__(self, api_key, api_secret):
        self.api_key = api_key
        self.api_secret = api_secret
        self.base_url = 'https://api.vexatrade.com/v1'
    
    def _generate_signature(self, timestamp, method, path, body=''):
        message = f"{timestamp}{method}{path}{body}"
        return hmac.new(
            self.api_secret.encode(),
            message.encode(),
            hashlib.sha256
        ).hexdigest()
    
    def _request(self, method, path, data=None):
        timestamp = int(time.time() * 1000)
        body = json.dumps(data) if data else ''
        signature = self._generate_signature(timestamp, method, path, body)
        
        headers = {
            'X-API-KEY': self.api_key,
            'X-API-SIGNATURE': signature,
            'X-API-TIMESTAMP': str(timestamp),
            'Content-Type': 'application/json'
        }
        
        url = f"{self.base_url}{path}"
        response = requests.request(method, url, headers=headers, data=body)
        return response.json()
    
    def get_ticker(self, symbol):
        return self._request('GET', f'/market/ticker/{symbol}')
    
    def place_order(self, symbol, side, price, amount, leverage=1):
        data = {
            'symbol': symbol,
            'side': side,
            'type': 'limit',
            'price': str(price),
            'amount': str(amount),
            'leverage': leverage
        }
        return self._request('POST', '/trading/order', data)

# Usage
client = VexarClient('your_api_key', 'your_secret')
ticker = client.get_ticker('BTCUSDT')
print(f"BTC Price: ${ticker['lastPrice']}")

# Place order
order = client.place_order('BTCUSDT', 'buy', 42000, 0.1, leverage=10)
print(f"Order placed: {order['orderId']}")
```

#### JavaScript/Node.js

**WebSocket Streaming:**

```javascript
const WebSocket = require('ws');

class VexarStream {
  constructor() {
    this.ws = new WebSocket('wss://stream.vexatrade.com');
    this.setupHandlers();
  }
  
  setupHandlers() {
    this.ws.on('open', () => {
      console.log('Connected to VEXAR');
    });
    
    this.ws.on('message', (data) => {
      const message = JSON.parse(data);
      this.handleMessage(message);
    });
    
    this.ws.on('error', (error) => {
      console.error('WebSocket error:', error);
    });
  }
  
  subscribe(channels) {
    this.ws.send(JSON.stringify({
      method: 'subscribe',
      params: channels
    }));
  }
  
  handleMessage(message) {
    const { channel, data } = message;
    
    if (channel.startsWith('ticker')) {
      console.log(`${data.symbol}: $${data.lastPrice}`);
    } else if (channel.startsWith('trades')) {
      console.log(`Trade: ${data.side} ${data.amount} @ $${data.price}`);
    }
  }
}

// Usage
const stream = new VexarStream();
stream.subscribe([
  'ticker@BTCUSDT',
  'ticker@ETHUSDT',
  'trades@BTCUSDT'
]);
```

### Error Handling

#### Error Codes

| Code | Message               | Description               |
| ---- | --------------------- | ------------------------- |
| 400  | Bad Request           | Invalid parameters        |
| 401  | Unauthorized          | Invalid API key/signature |
| 403  | Forbidden             | Insufficient permissions  |
| 404  | Not Found             | Resource not found        |
| 429  | Too Many Requests     | Rate limit exceeded       |
| 500  | Internal Server Error | Server error              |

#### Error Response Format

```json
{
  "error": {
    "code": 400,
    "message": "Invalid order amount",
    "details": {
      "field": "amount",
      "reason": "Must be greater than 0"
    }
  },
  "timestamp": 1704067200000
}
```

### Best Practices

#### Rate Limiting

```python
import time
from collections import deque

class RateLimiter:
    def __init__(self, max_requests, time_window):
        self.max_requests = max_requests
        self.time_window = time_window
        self.requests = deque()
    
    def wait_if_needed(self):
        now = time.time()
        
        # Remove old requests
        while self.requests and self.requests[0] < now - self.time_window:
            self.requests.popleft()
        
        # Wait if at limit
        if len(self.requests) >= self.max_requests:
            sleep_time = self.time_window - (now - self.requests[0])
            if sleep_time > 0:
                time.sleep(sleep_time)
            self.requests.popleft()
        
        self.requests.append(time.time())

# Usage
limiter = RateLimiter(max_requests=10, time_window=1.0)  # 10 req/sec

for i in range(100):
    limiter.wait_if_needed()
    make_api_request()
```

#### Error Retry Logic

```python
import time

def retry_with_backoff(func, max_retries=3):
    for attempt in range(max_retries):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            wait_time = (2 ** attempt) + random.uniform(0, 1)
            print(f"Retry {attempt + 1}/{max_retries} after {wait_time:.2f}s")
            time.sleep(wait_time)

# Usage
result = retry_with_backoff(lambda: client.place_order(...))
```

### Resources

#### SDK Libraries

**Official:**

* Python: `pip install vexar-python`
* JavaScript: `npm install vexar-js`
* Go: `go get github.com/vexar/vexar-go`

**Community:**

* Ruby: vexar-ruby
* Rust: vexar-rs

#### Tools

* API Playground: [api.vexatrade.com/playground](https://api.vexatrade.com/playground)
* Postman Collection: [Download](https://api.vexatrade.com/postman)

#### Support

* API Discord: #api-support
* Email: api.vexatrade.com
* Documentation: [docs.vexatrade.com/api](https://docs.vexatrade.com/api)

***

*Next: Troubleshooting →*


---

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

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

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

```
GET https://vexar.gitbook.io/docs/api-reference/api-documentation.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.
