# REST

### Authentication

All order-related endpoints require a valid signature. The signature is created by signing the order/cancel hash with the user's private key or an authorized delegate wallet.

***

### Orders

#### Get Open Orders

Retrieves all open orders for a user.

**Endpoint:** `GET /api/orders`

**Query Parameters:**

| Parameter | Type   | Required | Description             |
| --------- | ------ | -------- | ----------------------- |
| `user`    | string | Yes      | User's Ethereum address |

**Example Request:**

```
GET /api/orders?user=0x1234567890abcdef1234567890abcdef12345678
```

**Success Response (200):**

```json
{
  "success": true,
  "data": [
    {
      "hash": "0x...",
      "user_address": "0x...",
      "base_token": "0x...",
      "asset": "btcusd",
      "amount": "1000000000",
      "price": "10000000000000",
      "side": true,
      "nonce": 1234567890,
      "leverage": "1000000000",
      "closing_order": false,
      "remaining_amount": "1000000000",
      "closed": false,
      "stop": false,
      "stop_price": "0",
      "stopped": false,
      "is_market": false,
      "post_only": false,
      "decimals": 2,
      "amount_dec": 4,
      "margin_currency_symbol": "USDC",
      "created_at": "2024-01-15T10:30:00Z"
    }
  ]
}
```

#### Create Order

Creates a new trading order.

**Endpoint:** `POST /api/order`

**Request Body:**

```json
{
  "hash": "0x...",
  "user_address": "0x...",
  "base_token": "0x...",
  "asset": "btcusd",
  "amount": "1000000000",
  "price": "10000000000000",
  "side": true,
  "nonce": 1234567890,
  "leverage": "1000000000",
  "closing_order": false,
  "v": 27,
  "r": "0x...",
  "s": "0x...",
  "remaining_amount": "1000000000",
  "closed": false,
  "stop": false,
  "stop_price": "0",
  "stopped": false,
  "is_market": false,
  "post_only": false,
  "decimals": 2,
  "amount_dec": 4,
  "margin_currency_symbol": "USDC",
  "replace_hash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
```

**Field Descriptions:**

| Field              | Type    | Description                                           |
| ------------------ | ------- | ----------------------------------------------------- |
| `hash`             | string  | Order hash (keccak256 of order parameters)            |
| `user_address`     | string  | User's Ethereum address                               |
| `base_token`       | string  | Margin currency token address                         |
| `asset`            | string  | Trading pair symbol (e.g., "btcusd", "ethusd")        |
| `amount`           | string  | Order amount (as string, scaled by 1e8)               |
| `price`            | string  | Order price (as string, scaled by 1e8)                |
| `side`             | boolean | `true` = buy/long, `false` = sell/short               |
| `nonce`            | integer | Unique nonce for the order                            |
| `leverage`         | string  | Leverage amount (scaled by 1e8), `0` for cross margin |
| `closing_order`    | boolean | `true` if this is a reduce-only order                 |
| `v`, `r`, `s`      | -       | ECDSA signature components                            |
| `remaining_amount` | string  | Remaining unfilled amount                             |
| `stop`             | boolean | `true` if this is a stop order                        |
| `stop_price`       | string  | Trigger price for stop orders                         |
| `is_market`        | boolean | `true` for market orders                              |
| `post_only`        | boolean | `true` to only add liquidity (maker only)             |
| `replace_hash`     | string  | Hash of order to replace (for order amendments)       |

**Success Response (200):**

```json
{
  "success": true,
  "message": "Order created",
  "data": {
    "hash": "0x..."
  }
}
```

**Error Response (400):**

```json
{
  "success": false,
  "error": "Insufficient balance"
}
```

**Possible Errors:**

* `Nonce too large`
* `Invalid order hash - please refresh and try again`
* `Invalid Signature`
* `Delegate expired`
* `Order with this hash already exists`
* `Maximum 100 open orders allowed`
* `Insufficient balance`
* `Leverage too high`
* `Too much leverage`
* `Minimum order value is 10 USD`
* `Maximum order value for this asset is X USD`
* `Min acceptable price is X`
* `Max acceptable price is X`

***

#### Cancel Order

Cancels an existing open order.

**Endpoint:** `POST /api/cancel-order`

**Request Body:**

```json
{
  "order_hash": "0x...",
  "v": 27,
  "r": "0x...",
  "s": "0x..."
}
```

**Field Descriptions:**

| Field         | Type   | Description                       |
| ------------- | ------ | --------------------------------- |
| `order_hash`  | string | Hash of the order to cancel       |
| `v`, `r`, `s` | -      | ECDSA signature of the order hash |

**Success Response (200):**

```json
{
  "success": true,
  "message": "Order cancelled",
  "data": {
    "hash": "0x..."
  }
}
```

**Error Response (400):**

```json
{
  "success": false,
  "error": "Order not found"
}
```

**Possible Errors:**

* `Order not found`
* `Liquidation order cannot be canceled`
* `Invalid Signature`
* `Delegate expired`

***

### Trades

#### Get User Trades

Retrieves trade history for a user (last 100 trades).

**Endpoint:** `GET /api/trades`

**Query Parameters:**

| Parameter | Type   | Required | Description             |
| --------- | ------ | -------- | ----------------------- |
| `user`    | string | Yes      | User's Ethereum address |

**Example Request:**

```
GET /api/trades?user=0x1234567890abcdef1234567890abcdef12345678
```

**Success Response (200):**

```json
{
  "success": true,
  "data": [
    {
      "hash": "0x...",
      "user": "0x...",
      "asset": "btcusd",
      "base_token": "0x...",
      "amount": "1000000000",
      "price": "10000000000000",
      "side": true,
      "fee": "100000",
      "created_at": "2024-01-15T10:30:00Z"
    }
  ]
}
```

***

### Positions

#### Get Open Positions

Retrieves all open positions for a user.

**Endpoint:** `GET /api/positions/open`

**Query Parameters:**

| Parameter | Type   | Required | Description             |
| --------- | ------ | -------- | ----------------------- |
| `user`    | string | Yes      | User's Ethereum address |

**Example Request:**

```
GET /api/positions/open?user=0x1234567890abcdef1234567890abcdef12345678
```

**Success Response (200):**

```json
{
  "success": true,
  "data": [
    {
      "tx_hash": "0x...",
      "hash": "0x...",
      "base_token": "0x...",
      "asset": "btcusd",
      "side": true,
      "size": "1000000000",
      "entry_block": "12345678",
      "value": "50000000000",
      "entry_price": "10000000000000",
      "last_price": "10100000000000",
      "mark_price": 0.5,
      "liquidation_price": "9000000000000",
      "margin": "5000000000",
      "unrealized_pnl": "100000000",
      "realized_pnl": "0",
      "funding_rate": "100000",
      "decimals": 2,
      "amount_dec": 4,
      "margin_dec": 6,
      "margin_symbol": "USDC",
      "profit": "0",
      "loss": "0",
      "funding_cost": "0",
      "ur_funding_cost": "0",
      "created_at": "2024-01-15T10:30:00Z",
      "liquidated": false,
      "global_mm": 0.005,
      "is_cross": false,
      "cross_margin": "0"
    }
  ]
}
```

***

#### Get Closed Positions

Retrieves closed positions for a user (last 100).

**Endpoint:** `GET /api/positions/closed`

**Query Parameters:**

| Parameter | Type   | Required | Description             |
| --------- | ------ | -------- | ----------------------- |
| `user`    | string | Yes      | User's Ethereum address |

**Example Request:**

```
GET /api/positions/closed?user=0x1234567890abcdef1234567890abcdef12345678
```

**Success Response (200):**

```json
{
  "success": true,
  "data": [
    {
      "tx_hash": "0x...",
      "hash": "0x...",
      "base_token": "0x...",
      "asset": "btcusd",
      "side": true,
      "liquidated": false,
      "profit": "500000000",
      "loss": "0",
      "funding_cost": "10000000",
      "ur_funding_cost": "0",
      "created_at": "2024-01-15T10:30:00Z",
      "global_mm": 0.005,
      "decimals": 2,
      "amount_dec": 4
    }
  ]
}
```

***

### Binary Contracts

#### Get Settled Binary Contracts

Retrieves historical settled binary contracts for a given underlying asset and contract duration.

**Endpoint:** `GET /settled-binary-contracts`

**Query Parameters:**

| Parameter      | Type    | Required | Description                                          |
| -------------- | ------- | -------- | ---------------------------------------------------- |
| `underlying`   | string  | Yes      | Underlying asset symbol (e.g., "BTCUSDT", "ETHUSDT") |
| `contractLife` | integer | Yes      | Contract duration in minutes (e.g., 15, 60)          |

**Example Request:**

```
GET /settled-binary-contracts?underlying=btcusd&contractLife=15
```

**Success Response (200):**

```json
[
  {
    "symbol": "BTCUSDT-1706356800-105000-15",
    "underlying_symbol": "BTCUSDT",
    "target": 105000.00,
    "final_price": 105234.56,
    "is_above_target": true,
    "started_at": 1706356800,
    "settled_at": 1706357700
  },
  {
    "symbol": "BTCUSDT-1706355900-104500-15",
    "underlying_symbol": "BTCUSDT",
    "target": 104500.00,
    "final_price": 104123.45,
    "is_above_target": false,
    "started_at": 1706355900,
    "settled_at": 1706356800
  }
]
```

**Response Field Descriptions:**

| Field               | Type    | Description                               |
| ------------------- | ------- | ----------------------------------------- |
| `symbol`            | string  | Unique binary contract identifier         |
| `underlying_symbol` | string  | The underlying asset (e.g., "BTCUSD")     |
| `target`            | float   | Strike/target price for the contract      |
| `final_price`       | float   | Settlement price at contract expiry       |
| `is_above_target`   | boolean | `true` if final price was above target    |
| `started_at`        | integer | Contract start time (Unix timestamp)      |
| `settled_at`        | integer | Contract settlement time (Unix timestamp) |

**Error Responses:**

| Status | Message                                  |
| ------ | ---------------------------------------- |
| 400    | Missing required parameter: underlying   |
| 400    | Missing required parameter: contractLife |
| 400    | Invalid contractLife parameter           |
| 500    | Failed to fetch settled contracts        |

***

### Error Handling

All endpoints return errors in a consistent format:

```json
{
  "success": false,
  "error": "Error message describing what went wrong"
}
```

**HTTP Status Codes:**

| Code | Description                                          |
| ---- | ---------------------------------------------------- |
| 200  | Success                                              |
| 400  | Bad Request (validation error, business logic error) |
| 405  | Method Not Allowed                                   |

***

### Notes

* All `*big.Int` values are represented as strings to preserve precision
* Amounts and prices are scaled by `1e8` unless otherwise specified
* Timestamps are in ISO 8601 format (UTC)
* Ethereum addresses and hashes should include the `0x` prefix


---

# 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/rest.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.
