# General

### REST API

#### Base URL

`https://back.dmex.app/`

#### Endpoints

**1. Get Candles**

* **Method**: `GET`
* **Path**: `/candles`
* **Query Parameters**:
  * `symbol` (required): Asset symbol (e.g., "btcusd")
  * `interval` (required): Time interval ("1", "5", "15", "60", "240", "1440")
  * `from` (optional): Start timestamp
  * `to` (optional): End timestamp
  * `limit` (optional): Number of candles (default: 500)

**Example Request**:

```
GET /candles?symbol=btcusd&interval=60&limit=100
```

**Response**:

```json
{
  "s": "ok",
  "c": [50000, 50100, 50050],
  "o": [49950, 50000, 50100],
  "h": [50200, 50150, 50200],
  "l": [49900, 49980, 50000],
  "v": [1500, 1200, 800],
  "t": [1640995200, 1640998800, 1641002400]
}
```

**2. Server Ping**

* **Method**: `GET`
* **Path**: `/sPing`

**Response**:

```json
{
  "status": "ok",
  "timestamp": 1640995200000
}
```

**3. Contracts**

* **Method**: `GET`
* **Path**: `/contracts`
* **Description**: Returns all available derivative contracts

**Response**:

```json
[
  {
    "ticker_id": "BTC-USD",
    "base_currency": "BTC",
    "target_currency": "USD",
    "last_price": "50000.00",
    "base_volume": "150.25",
    "target_volume": "7512500.00",
    "bid": "49950.00",
    "ask": "50050.00",
    "high": "51000.00",
    "low": "49000.00",
    "product_type": "Perpetual",
    "open_interest": "1000.50",
    "open_interest_usd": "50025000.00",
    "index_price": "50000.00",
    "index_name": "BTC Index",
    "index_currency": "BTC",
    "start_timestamp": 0,
    "end_timestamp": 0,
    "funding_rate": "0.00010000",
    "next_funding_rate": "0.00010000",
    "next_funding_rate_timestamp": 1641002400,
    "contract_type": "Vanilla",
    "contract_price": "50000.00",
    "contract_price_currency": "USD"
  }
]
```

**4. Orderbook**

* **Method**: `GET`
* **Path**: `/orderbook`
* **Query Parameters**:
  * `ticker_id` (required): Ticker ID (e.g., "BTC-USD")
  * `depth` (optional): Number of orders per side (default: 100, max: 500)

**Example Request**:

```
GET /orderbook?ticker_id=BTC-USD&depth=50
```

**Response**:

```json
{
  "ticker_id": "BTC-USD",
  "timestamp": 1640995200000,
  "bids": [
    ["49950.00", "1.5"],
    ["49900.00", "2.0"]
  ],
  "asks": [
    ["50050.00", "1.2"],
    ["50100.00", "0.8"]
  ]
}
```

***

### WebSocket API

#### Connection

* **URL**: `wss://back.dmex.app/ws`
* **Protocol**: WebSocket
* **Authentication**: Required for most operations

#### Message Format

All WebSocket messages follow this JSON structure:

```json
{
  "type": "message_type",
  "data": {
    // Message-specific data
  }
}
```

#### Client to Server Messages

**1. Authentication**

```json
{
  "type": "auth",
  "data": {
    "user_address": "0x1234567890abcdef...",
  }
}
```

**Response**: User data, balances, positions, orders, etc.

**2. Subscribe to Asset**

```json
{
  "type": "subscribeAsset",
  "data": {
    "asset": "btcusdt"
  }
}
```

**Response**: Asset data, orderbook, trades

**10. Ping**

```
"ping"
```

**Response**: Connection stays alive

#### Server to Client Messages

**1. Asset Data**

```json
{
  "type": "assets",
  "data": [
    {
      "symbol": "btcusd",
      "last_price": "50000.00",
      "mark_price": 50100.00,
      "high": 51000.00,
      "low": 49000.00,
      "volume": 1500.50,
      "change": 2.5,
      "funding_rate": "0.0001",
      "open_interest": 25000000.00,
      "daily_trades": 1250
    }
  ]
}
```

**2. User Parameters**

```json
{
  "type": "params_user",
  "data": {
    "risk_limit": "5000",
    "mm_multiplier": "1.0",
    "fr_multiplier": "1.0",
    "btc_deposit_address": "bc1q...",
    "eth_deposit_address": "0x...",
    "xmr_deposit_address": "4...",
    "tron_deposit_address": "T...",
    "solana_deposit_address": "..."
  }
}
```

**3. Balances**

```json
{
  "type": "balances",
  "data": [
    {
      "currency": "btc",
      "available": "1.5",
      "total": "2.0",
      "reserved": "0.5"
    }
  ]
}
```

**4. Positions**

```json
{
  "type": "positions",
  "data": [
    {
      "symbol": "btcusd",
      "side": "long",
      "size": "1.5",
      "entry_price": "49500.00",
      "mark_price": "50000.00",
      "liquidation_price": "45000.00",
      "unrealized_pnl": "750.00",
      "margin": "5000.00",
      "leverage": "10",
      "margin_type": "isolated"
    }
  ]
}
```

**5. Orders**

```json
{
  "type": "orders",
  "data": [
    {
      "id": "order_hash",
      "symbol": "btcusd",
      "side": "buy",
      "amount": "1.0",
      "price": "49000.00",
      "filled": "0.5",
      "status": "open|filled|cancelled",
      "type": "limit|market",
      "timestamp": 1640995200000
    }
  ]
}
```

**6. Trades**

```json
{
  "type": "trades",
  "data": [
    {
      "symbol": "btcusd",
      "price": "50000.00",
      "amount": "0.5",
      "side": "buy",
      "timestamp": 1640995200000
    }
  ]
}
```

**7. Orderbook**

```json
{
  "type": "orderbook",
  "data": {
    "symbol": "btcusd",
    "bids": [
      ["49950.00", "1.5"],
      ["49900.00", "2.0"]
    ],
    "asks": [
      ["50050.00", "1.2"],
      ["50100.00", "0.8"]
    ]
  }
}
```

**8. Mark Price Updates**

```json
{
  "type": "mark_price",
  "data": {
    "symbol": "btcusd",
    "price": 50125.50,
    "timestamp": 1640995200000
  }
}
```

**9. Funding Rate Updates**

```json
{
  "type": "funding_rate",
  "data": {
    "symbol": "btcusd",
    "funding_rate": "0.0001"
  }
}
```

**10. Error Messages**

```json
{
  "type": "error",
  "data": {
    "message": "Error description"
  }
}
```

**11. Success Messages**

```json
{
  "type": "success",
  "data": {
    "message": "Operation successful"
  }
}
```

***

### Authentication

#### WebSocket Authentication

1. Connect to WebSocket endpoint
2. Send authentication message with user address and unique ID
3. Server validates and responds with user data

#### Message Signing

For sensitive operations (orders, withdrawals, margin updates), messages must be signed:

* **hash**: Keccak256 hash of message data
* **v**: Recovery ID (27 or 28)
* **r**: First 32 bytes of signature
* **s**: Last 32 bytes of signature
* **user**: User's Ethereum address

***

### Rate Limiting

#### Global Limits

* **Global**: 1000 requests per second with burst of 5000
* **Per IP**: 1 request per second with burst of 5

#### Connection Limits

* **Max connections per user**: 5
* **Max total connections**: Configurable via environment

#### Rate Limit Headers

Rate limit information is not exposed in headers but enforced server-side.

***

### Error Handling

#### WebSocket Errors

```json
{
  "type": "error",
  "data": {
    "message": "Error description"
  }
}
```

#### HTTP Errors

* **400 Bad Request**: Invalid parameters
* **404 Not Found**: Endpoint or resource not found
* **429 Too Many Requests**: Rate limit exceeded
* **500 Internal Server Error**: Server error

#### Common Error Messages

* `"Invalid wallet"`: Authentication failed
* `"Too Many Requests"`: Rate limit exceeded
* `"Ticker not found"`: Invalid asset symbol
* `"SERVER MAX ALLOWED CONNECTIONS REACHED"`: Connection limit exceeded
* `"Invalid Signature"`: Message signature validation failed

***

### Data Types

#### Precision

* **Prices**: Stored as big integers with 1e8 precision
* **Amounts**: Stored as big integers with asset-specific precision
* **Funding Rates**: Stored as big integers with 1e16 precision

#### Timestamps

* **WebSocket**: Unix timestamps in milliseconds
* **REST**: Unix timestamps in seconds or milliseconds (endpoint-specific)

#### Asset Symbols

* Format: `{base}usd` (e.g., "btcusd", "ethusd")
* Case-insensitive but returned in lowercase

#### Order Sides

* `"buy"` or `"sell"`

#### Order Types

* `"limit"`: Limit order
* `"market"`: Market order

#### Margin Types

* `"isolated"`: Isolated margin
* `"cross"`: Cross margin

#### Order Status

* `"open"`: Active order
* `"filled"`: Completely filled
* `"cancelled"`: Cancelled order
* `"partially_filled"`: Partially filled


---

# 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.dmex.app/api-docs/general.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.
