# Schema

## Enums

### OrderSideEnum

| Status String | Integer Value | Description |
| ------------- | ------------- | ----------- |
| `BUY`         | `1`           | Buy order   |
| `SELL`        | `2`           | Sell order  |

### OrderTypeEnum

| Status String | Integer Value | Description  |
| ------------- | ------------- | ------------ |
| `LIMIT`       | `1`           | Limit order  |
| `MARKET`      | `2`           | Market order |

### TimeInForceEnum

| Status String | Integer Value | Description                                                                    |
| ------------- | ------------- | ------------------------------------------------------------------------------ |
| `GTC`         | `1`           | Good Til Canceled. An order stays on the book unless canceled.                 |
| `FOK`         | `2`           | Fill or Kill (**not supported yet**). Expires if not fully filled immediately. |
| `IOC`         | `3`           | Immediate Or Cancel. Fills as much as possible before expiring.                |
| `GTX`         | `4`           | Post Only. Expires if the order would be filled immediately.                   |

### TransferAssetTypeEnum

| Status String    | Integer Value | Description                                                |
| ---------------- | ------------- | ---------------------------------------------------------- |
| `EVM_DEPOSIT`    | `0`           | Indicate this transfer is a deposit from the evm chain.    |
| `PERPS_DEPOSIT`  | `1`           | Indicate this transfer is a deposit from the perps chain.  |
| `EVM_WITHDRAW`   | `2`           | Indicate this transfer is a withdrawal to the evm chain.   |
| `PERPS_WITHDRAW` | `3`           | Indicate this transfer is a withdrawal to the perps chain. |
| `INTERNAL`       | `4`           | Indicate this transfer is an internal transfer.            |
| `SPOT_WITHDRAW`  | `5`           | Indicate this transfer is a withdrawal to the spot chain.  |
| `SPOT_DEPOSIT`   | `6`           | Indicate this transfer is a deposit to the spot chain.     |

### APIKeyTypeEnum

| Status String | Integer Value | Description                                                      |
| ------------- | ------------- | ---------------------------------------------------------------- |
| `EVM`         | `1`           | Use evm private key as secret key and evm address as public key. |

### SignatureTypeEnum

| Status String      | Integer Value | Description                                                     |
| ------------------ | ------------- | --------------------------------------------------------------- |
| `EIP712`           | `1`           | EIP-712 signature with engine-specific domain.                  |
| `EIP712_UNIVERSAL` | `2`           | EIP-712 signature with universal domain (for `AddAPIKey` only). |

### OrderStatusEnum

| Status String      | Integer Value | Description                                                 |
| ------------------ | ------------- | ----------------------------------------------------------- |
| `NEW`              | `1`           | The order has been accepted into the engine.                |
| `PARTIALLY_FILLED` | `2`           | The order is partially filled in the engine.                |
| `FILLED`           | `3`           | The order is fully filled in the engine.                    |
| `CANCELED`         | `4`           | The order has been canceled by the user.                    |
| `REJECTED`         | `5`           | The order has been rejected and was not processed.          |
| `EXPIRED`          | `6`           | The order expired according to order rules (FOK, IOC, etc.) |
| `TRIGGERED`        | `10`          | perps only, for triggered TP/SL orders                      |

### ExecutionTypeEnum

| Status String      | Integer Value | Description                                                                                                                                     |
| ------------------ | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `NEW`              | `1`           | The order has been accepted into the engine.                                                                                                    |
| `PARTIALLY_FILLED` | `2`           | The order is partially filled in the engine.                                                                                                    |
| `FILLED`           | `3`           | The order is fully filled in the engine.                                                                                                        |
| `CANCELED`         | `4`           | The order has been canceled by the user.                                                                                                        |
| `REJECTED`         | `5`           | The order has been rejected and was not processed.                                                                                              |
| `MODIFIED`         | `6`           | The order has been modified, only reduce size.                                                                                                  |
| `EXPIRED`          | `7`           | The order was canceled according to the order type's rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill) |
| `REPLACED`         | `8`           | The order has been amended, both size and price changed.                                                                                        |

### OrderModifierEnum - perps only

| Status String   | Integer Value | Description                             |
| --------------- | ------------- | --------------------------------------- |
| `NORMAL`        | `1`           | Normal order.                           |
| `STOP`          | `2`           | Stop order.                             |
| `BRACKET`       | `3`           | Normal order in order with TP/SL group. |
| `ATTACHED_STOP` | `4`           | Stop order in order with TP/SL group.   |

### MarginModeEnum - perps only

| Status String | Integer Value | Description           |
| ------------- | ------------- | --------------------- |
| `ISOLATED`    | `1`           | Isolated margin mode. |
| `CROSS`       | `2`           | Cross margin mode.    |

### PositionSideEnum - perps only

| Status String | Integer Value | Description                                          |
| ------------- | ------------- | ---------------------------------------------------- |
| `BOTH`        | `1`           | Oneway mode.                                         |
| `LONG`        | `2`           | Hedge mode. **not supported in order placement yet** |
| `SHORT`       | `3`           | Hedge mode. **not supported in order placement yet** |

### StopTypeEnum - perps only

| Status String | Integer Value | Description        |
| ------------- | ------------- | ------------------ |
| `STOP_LOSS`   | `1`           | Stop loss order.   |
| `TAKE_PROFIT` | `2`           | Take profit order. |

### TriggerTypeEnum - perps only

| Status String | Integer Value | Description                                                           |
| ------------- | ------------- | --------------------------------------------------------------------- |
| `LAST_PRICE`  | `1`           | Trigger by last trade price. **not supported in order placement yet** |
| `MARK_PRICE`  | `2`           | Trigger by mark price.                                                |
| `INDEX_PRICE` | `3`           | Trigger by index price. **not supported in order placement yet**      |

## Hex String

A string starts with `0x`, the rest parts consist of `0` to `9`, `a` to `z` and `A` to `Z`.

## Decimal String

The canonical form of a decimal string is a standardized representation that removes ambiguity and allows for direct comparison. Key rules include removing the optional plus sign, prohibiting exponential notation, and ensuring there is at least one digit to the left and right of the decimal point.

### Examples

| Original String | Canonical Form | Reason                                                       |
| --------------- | -------------- | ------------------------------------------------------------ |
| `00123`         | `123`          | Remove leading zeros.                                        |
| `+32.1`         | `32.1`         | Remove the leading plus sign.                                |
| `32.100`        | `32.1`         | Remove trailing zeros.                                       |
| `0.500`         | `0.5`          | Remove trailing zeros.                                       |
| `1.234e+2`      | `123.4`        | Convert from exponential notation and remove trailing zeros. |
| `001.230`       | `1.23`         | Remove leading zeros and trailing zeros.                     |

## REST Types

### Exchange Types

#### Common Types

**TransferAssetRequest**

| Name            | Type                    | Required | Restrictions                  | Description                                      |
| --------------- | ----------------------- | -------- | ----------------------------- | ------------------------------------------------ |
| `id`            | `uint64`                | `true`   | none                          | The unique identifier for this transfer request. |
| `fromAccountID` | `uint64`                | `true`   | none                          | The account ID of sender.                        |
| `toAccountID`   | `uint64`                | `true`   | none                          | The account ID of receiver.                      |
| `coinID`        | `uint64`                | `true`   | none                          | The coinID to send.                              |
| `amount`        | `DecimalString`         | `true`   | positive value                | The amount of coin to send.                      |
| `type`          | `TransferAssetTypeEnum` | `true`   | use integer value of the enum | Type of transfer                                 |

**ReplaceOrderRequest**

| Name        | Type                   | Required | Restrictions | Description                         |
| ----------- | ---------------------- | -------- | ------------ | ----------------------------------- |
| `accountID` | `uint64`               | `true`   | none         | The account ID                      |
| `orders`    | `Array<ReplaceParams>` | `true`   | non-empty    | List of non-empty order replacement |

**ReplaceParams**

| Name          | Type            | Required | Restrictions                         | Description                                                 |
| ------------- | --------------- | -------- | ------------------------------------ | ----------------------------------------------------------- |
| `symbolID`    | `uint64`        | `true`   | none                                 | The symbol ID                                               |
| `clOrdID`     | `string`        | `true`   | should match `^[0-9a-zA-Z_-]{1,36}$` | The unique identifier for this replacement request.         |
| `origOrderID` | `uint64`        | `false`  | none                                 | The unique identifier of the order to be replaced.          |
| `origClOrdID` | `string`        | `false`  | should match `^[0-9a-zA-Z_-]{1,36}$` | The client-provided identifier of the order to be replaced. |
| `price`       | `DecimalString` | `false`  | none                                 | The new price for the order                                 |
| `quantity`    | `DecimalString` | `false`  | none                                 | The new quantity for the order                              |

#### ScheduleCancelRequest

| Name                 | Type     | Required | Restrictions | Description    |
| -------------------- | -------- | -------- | ------------ | -------------- |
| `accountID`          | `uint64` | `true`   | none         | The account ID |
| `scheduledTimestamp` | `uint64` | `false`  | none         | none           |

#### Spot only types

**BatchNewOrderRequest**

| Name        | Type                       | Required | Restrictions | Description              |
| ----------- | -------------------------- | -------- | ------------ | ------------------------ |
| `accountID` | `uint64`                   | `true`   | none         | none                     |
| `orders`    | `Array<BatchNewOrderItem>` | `true`   | non-empty    | List of non-empty orders |

**BatchNewOrderItem**

| Name          | Type              | Required | Restrictions                         | Description            |
| ------------- | ----------------- | -------- | ------------------------------------ | ---------------------- |
| `symbolID`    | `uint64`          | `true`   | none                                 | none                   |
| `clOrdID`     | `string`          | `true`   | should match `^[0-9a-zA-Z_-]{1,36}$` | none                   |
| `side`        | `OrderSideEnum`   | `true`   | use integer value of the enum        | none                   |
| `type`        | `OrderTypeEnum`   | `true`   | use integer value of the enum        | none                   |
| `timeInForce` | `TimeInForceEnum` | `true`   | use integer value of the enum        | none                   |
| `price`       | `DecimalString`   | `false`  | none                                 | none                   |
| `quantity`    | `DecimalString`   | `false`  | none                                 | none                   |
| `funds`       | `DecimalString`   | `false`  | none                                 | market buy orders only |

**BatchCancelOrderRequest**

| Name        | Type                          | Required | Restrictions | Description                           |
| ----------- | ----------------------------- | -------- | ------------ | ------------------------------------- |
| `accountID` | `uint64`                      | `true`   | none         | none                                  |
| `cancels`   | `Array<BatchCancelOrderItem>` | `true`   | non-empty    | List of non-empty order cancellations |

**BatchCancelOrderItem**

| Name          | Type     | Required | Restrictions                         | Description                                                 |
| ------------- | -------- | -------- | ------------------------------------ | ----------------------------------------------------------- |
| `symbolID`    | `uint64` | `true`   | none                                 | none                                                        |
| `clOrdID`     | `string` | `true`   | should match `^[0-9a-zA-Z_-]{1,36}$` | The unique identifier for this cancellation request.        |
| `orderID`     | `uint64` | `false`  | none                                 | The unique identifier of the order to be canceled.          |
| `origClOrdID` | `string` | `false`  | should match `^[0-9a-zA-Z_-]{1,36}$` | The client-provided identifier of the order to be canceled. |

#### Perps only types

**PerpsNewOrderRequest**

| Name        | Type                    | Required | Restrictions | Description              |
| ----------- | ----------------------- | -------- | ------------ | ------------------------ |
| `accountID` | `uint64`                | `true`   | none         | The account ID           |
| `symbolID`  | `uint64`                | `true`   | none         | Symbol ID                |
| `orders`    | `Array<PerpsOrderItem>` | `true`   | non-empty    | List of orders to submit |

**PerpsOrderItem**

| Name           | Type                | Required | Restrictions                         | Description                            |
| -------------- | ------------------- | -------- | ------------------------------------ | -------------------------------------- |
| `clOrdID`      | `string`            | `true`   | should match `^[0-9a-zA-Z_-]{1,36}$` | Client order ID (unique per account)   |
| `modifier`     | `OrderModifierEnum` | `true`   | use integer value of the enum        | Order modifier                         |
| `side`         | `OrderSideEnum`     | `true`   | use integer value of the enum        | Order side                             |
| `type`         | `OrderTypeEnum`     | `true`   | use integer value of the enum        | Order type                             |
| `timeInForce`  | `TimeInForceEnum`   | `true`   | use integer value of the enum        | Time in force                          |
| `price`        | `DecimalString`     | `false`  | none                                 | none                                   |
| `quantity`     | `DecimalString`     | `false`  | none                                 | none                                   |
| `funds`        | `DecimalString`     | `false`  | none                                 | Market buy orders only                 |
| `stopPrice`    | `DecimalString`     | `false`  | none                                 | Trigger price for TP/SL                |
| `stopType`     | `StopTypeEnum`      | `false`  | use integer value of the enum        | Stop type for TP/SL                    |
| `triggerType`  | `TriggerTypeEnum`   | `false`  | use integer value of the enum        | For TP/SL; only `MARK_PRICE` supported |
| `reduceOnly`   | `bool`              | `true`   | none                                 | Reduce-only flag                       |
| `positionSide` | `PositionSideEnum`  | `true`   | use integer value of the enum        | Only `BOTH` is supported               |

**PerpsCancelOrderRequest**

| Name        | Type                     | Required | Restrictions | Description              |
| ----------- | ------------------------ | -------- | ------------ | ------------------------ |
| `accountID` | `uint64`                 | `true`   | none         | The account ID           |
| `cancels`   | `Array<PerpsCancelItem>` | `true`   | non-empty    | List of orders to cancel |

**PerpsCancelItem**

| Name       | Type     | Required | Restrictions                         | Description            |
| ---------- | -------- | -------- | ------------------------------------ | ---------------------- |
| `symbolID` | `uint64` | `true`   | none                                 | Symbol ID              |
| `orderID`  | `uint64` | `false`  | none                                 | The order ID to cancel |
| `clOrdID`  | `string` | `false`  | should match `^[0-9a-zA-Z_-]{1,36}$` | The client order ID    |

**ModifyOrderRequest**

| Name        | Type            | Required | Restrictions                         | Description                           |
| ----------- | --------------- | -------- | ------------------------------------ | ------------------------------------- |
| `accountID` | `uint64`        | `true`   | none                                 | Account ID                            |
| `symbolID`  | `uint64`        | `true`   | none                                 | Symbol ID                             |
| `orderID`   | `uint64`        | `false`  | none                                 | Order to be replaced                  |
| `clOrdID`   | `string`        | `false`  | should match `^[0-9a-zA-Z_-]{1,36}$` | Client-provided identifier to replace |
| `price`     | `DecimalString` | `false`  | none                                 | The new price                         |
| `quantity`  | `DecimalString` | `false`  | none                                 | The new quantity                      |
| `stopPrice` | `DecimalString` | `false`  | none                                 | The new stop price                    |

**UpdateLeverageRequest**

| Name         | Type             | Required | Restrictions                  | Description         |
| ------------ | ---------------- | -------- | ----------------------------- | ------------------- |
| `accountID`  | `uint64`         | `true`   | none                          | The account ID      |
| `symbolID`   | `uint64`         | `true`   | none                          | Symbol ID           |
| `leverage`   | `uint32`         | `true`   | none                          | Leverage level      |
| `marginMode` | `MarginModeEnum` | `true`   | use integer value of the enum | 1=ISOLATED, 2=CROSS |

**UpdateMarginRequest**

| Name        | Type            | Required | Restrictions | Description                                   |
| ----------- | --------------- | -------- | ------------ | --------------------------------------------- |
| `accountID` | `uint64`        | `true`   | none         | The account ID                                |
| `symbolID`  | `uint64`        | `true`   | none         | Symbol ID                                     |
| `amount`    | `DecimalString` | `true`   | non-zero     | Amount to add (positive) or remove (negative) |

### REST Response

#### Succeed Response

**Properties**

| Name        | Type     | Required | Restrictions | Description                                                    |
| ----------- | -------- | -------- | ------------ | -------------------------------------------------------------- |
| `code`      | `int32`  | `true`   | none         | Always `0`                                                     |
| `data`      | `Object` | `true`   | none         | Check format in each endpoint                                  |
| `timestamp` | `uint64` | `true`   | none         | The timestamp in milliseconds when this response is just sent. |

**Examples**

```json
{
  "code": 0,
  "data": null,
  "timestamp": 1767501757000
}
```

#### Error Response

**Properties**

| Name        | Type     | Required | Restrictions | Description                                                    |
| ----------- | -------- | -------- | ------------ | -------------------------------------------------------------- |
| `code`      | `int32`  | `true`   | none         | Error code. Always negative.                                   |
| `error`     | `string` | `true`   | none         | Error message                                                  |
| `timestamp` | `uint64` | `true`   | none         | The timestamp in milliseconds when this response is just sent. |

**Examples**

```json
{
  "code": -1,
  "error": "nonce is invalid",
  "timestamp": 1767501757000
}
```

### Symbol

#### SpotSymbol

| Name                   | Type            | Required | Description                                                                |
| ---------------------- | --------------- | -------- | -------------------------------------------------------------------------- |
| `id`                   | `uint64`        | `true`   | Unique symbol ID                                                           |
| `name`                 | `string`        | `true`   | Unique symbol name, e.g. `vBTC_vUSDC`                                      |
| `displayName`          | `string`        | `true`   | Display name for UI, e.g. `BTC/USDC`                                       |
| `baseCoinID`           | `uint64`        | `true`   | Base coin ID                                                               |
| `baseCoin`             | `string`        | `false`  | Base coin name                                                             |
| `baseCoinPrecision`    | `uint8`         | `false`  | Base coin precision                                                        |
| `quoteCoinID`          | `uint64`        | `true`   | Quote coin ID                                                              |
| `quoteCoin`            | `string`        | `false`  | Quote coin name                                                            |
| `quoteCoinPrecision`   | `uint8`         | `false`  | Quote coin precision                                                       |
| `pricePrecision`       | `int32`         | `true`   | Decimal precision of order price. Price filter parameters.                 |
| `tickSize`             | `DecimalString` | `true`   | Tick size of order price. Price filter parameters.                         |
| `minPrice`             | `DecimalString` | `true`   | Minimum order price. Price filter parameters.                              |
| `maxPrice`             | `DecimalString` | `true`   | Maximum order price. Price filter parameters.                              |
| `quantityPrecision`    | `int32`         | `true`   | Decimal precision of order quantity. Lot size filter parameters.           |
| `stepSize`             | `DecimalString` | `true`   | Step size of order quantity. Lot size filter parameters.                   |
| `minQuantity`          | `DecimalString` | `true`   | Minimum order quantity. Lot size filter parameters.                        |
| `maxQuantity`          | `DecimalString` | `true`   | Maximum order quantity. Lot size filter parameters.                        |
| `marketMinQuantity`    | `DecimalString` | `true`   | Minimum order quantity in market order. Market lot size filter parameters. |
| `marketMaxQuantity`    | `DecimalString` | `true`   | Maximum order quantity in market order. Market lot size filter parameters. |
| `minNotional`          | `DecimalString` | `true`   | Minimum order notional value. Notional filter parameters.                  |
| `maxNotional`          | `DecimalString` | `true`   | Maximum order notional value. Notional filter parameters.                  |
| `buyLimitUpRatio`      | `DecimalString` | `true`   | Limit order price limitation parameters                                    |
| `sellLimitDownRatio`   | `DecimalString` | `true`   | Limit order price limitation parameters                                    |
| `marketDeviationRatio` | `DecimalString` | `true`   | Market order price limitation parameters                                   |
| `makerFee`             | `DecimalString` | `true`   | Default maker fee ratio                                                    |
| `takerFee`             | `DecimalString` | `true`   | Default taker fee ratio                                                    |
| `status`               | `string`        | `true`   | `TRADING`, `HALT`                                                          |

#### PerpsSymbol

| Name                   | Type                | Required | Description                                                                |
| ---------------------- | ------------------- | -------- | -------------------------------------------------------------------------- |
| `id`                   | `uint64`            | `true`   | Symbol ID                                                                  |
| `name`                 | `string`            | `true`   | Symbol name, e.g. `BTC-USD`                                                |
| `displayName`          | `string`            | `true`   | Symbol name in UI                                                          |
| `baseCoin`             | `string`            | `true`   | Base asset                                                                 |
| `quoteCoinID`          | `uint64`            | `true`   | Settlement coin ID                                                         |
| `quoteCoin`            | `string`            | `true`   | Settlement coin name                                                       |
| `quoteCoinPrecision`   | `uint8`             | `true`   | Settlement coin precision                                                  |
| `pricePrecision`       | `int32`             | `true`   | Decimal precision of order price. Price filter parameters.                 |
| `tickSize`             | `DecimalString`     | `true`   | Tick size of order price. Price filter parameters.                         |
| `minPrice`             | `DecimalString`     | `true`   | Minimum order price. Price filter parameters.                              |
| `maxPrice`             | `DecimalString`     | `true`   | Maximum order price. Price filter parameters.                              |
| `quantityPrecision`    | `int32`             | `true`   | Decimal precision of order quantity. Lot size filter parameters.           |
| `openInterestCap`      | `DecimalString`     | `false`  | Open interest capacity in base coin                                        |
| `openInterestCapUSD`   | `DecimalString`     | `false`  | Open interest capacity in quote coin                                       |
| `stepSize`             | `DecimalString`     | `true`   | Step size of order quantity. Lot size filter parameters.                   |
| `minQuantity`          | `DecimalString`     | `true`   | Minimum order quantity. Lot size filter parameters.                        |
| `maxQuantity`          | `DecimalString`     | `true`   | Maximum order quantity. Lot size filter parameters.                        |
| `marketMinQuantity`    | `DecimalString`     | `true`   | Minimum order quantity in market order. Market lot size filter parameters. |
| `marketMaxQuantity`    | `DecimalString`     | `true`   | Maximum order quantity in market order. Market lot size filter parameters. |
| `minNotional`          | `DecimalString`     | `true`   | Minimum order notional value. Notional filter parameters.                  |
| `maxNotional`          | `DecimalString`     | `true`   | Maximum order notional value. Notional filter parameters.                  |
| `buyLimitUpRatio`      | `DecimalString`     | `true`   | Limit order price limitation parameters                                    |
| `sellLimitDownRatio`   | `DecimalString`     | `true`   | Limit order price limitation parameters                                    |
| `marketDeviationRatio` | `DecimalString`     | `true`   | Market order price limitation parameters                                   |
| `maxLeverage`          | `uint32`            | `true`   | Maximum leverage allowed                                                   |
| `initLeverage`         | `uint32`            | `true`   | Initial leverage                                                           |
| `marginTiers`          | `Array<MarginTier>` | `true`   | Supported margin tiers                                                     |
| `fundingInterval`      | `uint32`            | `true`   | Funding interval in seconds; must be a multiple of `3600`.                 |
| `interestRate`         | `DecimalString`     | `true`   | 8h interest rate; always `0.0001`                                          |
| `maxFundingRate`       | `DecimalString`     | `true`   | Maximum funding rate per funding interval                                  |
| `minFundingRate`       | `DecimalString`     | `true`   | Minimum funding rate per funding interval                                  |
| `makerFee`             | `DecimalString`     | `true`   | Default maker fee ratio                                                    |
| `takerFee`             | `DecimalString`     | `true`   | Default taker fee ratio                                                    |
| `status`               | `string`            | `true`   | Symbol status: `TRADING`, `HALT`                                           |

**MarginTier**

| Name                    | Type            | Required | Description                           |
| ----------------------- | --------------- | -------- | ------------------------------------- |
| `maxNotionalValue`      | `DecimalString` | `true`   | Maximum notional value for this tier  |
| `maintenanceMarginRate` | `DecimalString` | `true`   | Maintenance margin rate for this tier |
| `maxLeverage`           | `uint32`        | `true`   | Maximum leverage allowed in this tier |
| `maintenanceDeduction`  | `DecimalString` | `true`   | Maintenance deduction amount          |

### Coin

#### SpotCoin

| Name        | Type     | Required | Description                            |
| ----------- | -------- | -------- | -------------------------------------- |
| `id`        | `uint64` | `true`   | Unique coin ID                         |
| `name`      | `string` | `true`   | Unique coin name, e.g. `vBTC`, `vUSDC` |
| `precision` | `uint8`  | `true`   | Coin decimal precision                 |

#### PerpsCoin

| Name          | Type            | Required | Description                       |
| ------------- | --------------- | -------- | --------------------------------- |
| `id`          | `uint64`        | `true`   | Unique coin ID                    |
| `name`        | `string`        | `true`   | Unique coin name                  |
| `precision`   | `uint8`         | `true`   | Coin decimal precision            |
| `marginRatio` | `DecimalString` | `true`   | Margin ratio of this coin         |
| `price`       | `DecimalString` | `false`  | Current oracle price of this coin |

### Ticker

#### SpotTicker

| Name          | Type            | Required | Description                           |
| ------------- | --------------- | -------- | ------------------------------------- |
| `symbol`      | `string`        | `true`   | Symbol name                           |
| `lastPx`      | `DecimalString` | `true`   | Last trade price                      |
| `lastSz`      | `DecimalString` | `false`  | Last trade quantity                   |
| `openPx`      | `DecimalString` | `true`   | Open price                            |
| `highPx`      | `DecimalString` | `true`   | High price                            |
| `lowPx`       | `DecimalString` | `true`   | Low price                             |
| `vwap`        | `DecimalString` | `false`  | Weighted average price                |
| `change`      | `DecimalString` | `true`   | Price change                          |
| `changePct`   | `number`        | `true`   | Price change percent                  |
| `volume`      | `DecimalString` | `true`   | Total traded base asset volume        |
| `quoteVolume` | `DecimalString` | `true`   | Total traded quote asset volume       |
| `bidPx`       | `DecimalString` | `true`   | Best bid price                        |
| `bidSz`       | `DecimalString` | `true`   | Best bid quantity                     |
| `askPx`       | `DecimalString` | `true`   | Best ask price                        |
| `askSz`       | `DecimalString` | `true`   | Best ask quantity                     |
| `openTime`    | `uint64`        | `true`   | Statistics open time in milliseconds  |
| `closeTime`   | `uint64`        | `true`   | Statistics close time in milliseconds |

#### PerpsTicker

| Name              | Type            | Required | Description                           |
| ----------------- | --------------- | -------- | ------------------------------------- |
| `symbol`          | `string`        | `true`   | Symbol name                           |
| `lastPx`          | `DecimalString` | `true`   | Last trade price                      |
| `lastSz`          | `DecimalString` | `false`  | Last trade quantity                   |
| `vwap`            | `DecimalString` | `false`  | Weighted average price                |
| `change`          | `DecimalString` | `false`  | Price change                          |
| `changePct`       | `number`        | `false`  | Price change percent                  |
| `openPx`          | `DecimalString` | `true`   | Open price                            |
| `highPx`          | `DecimalString` | `true`   | High price                            |
| `lowPx`           | `DecimalString` | `true`   | Low price                             |
| `volume`          | `DecimalString` | `true`   | Total traded base asset volume        |
| `quoteVolume`     | `DecimalString` | `true`   | Total traded quote asset volume       |
| `bidPx`           | `DecimalString` | `true`   | Best bid price                        |
| `bidSz`           | `DecimalString` | `true`   | Best bid quantity                     |
| `askPx`           | `DecimalString` | `true`   | Best ask price                        |
| `askSz`           | `DecimalString` | `true`   | Best ask quantity                     |
| `fundingRate`     | `DecimalString` | `true`   | Current funding rate                  |
| `nextFundingTime` | `uint64`        | `true`   | Next funding time in milliseconds     |
| `indexPrice`      | `DecimalString` | `true`   | Current index price                   |
| `markPrice`       | `DecimalString` | `true`   | Current mark price                    |
| `openInterest`    | `DecimalString` | `true`   | Current open interest                 |
| `openTime`        | `uint64`        | `true`   | Statistics open time in milliseconds  |
| `closeTime`       | `uint64`        | `true`   | Statistics close time in milliseconds |

### Mini Ticker

#### MiniTicker

| Name          | Type            | Required | Description                           |
| ------------- | --------------- | -------- | ------------------------------------- |
| `symbol`      | `string`        | `true`   | Symbol name                           |
| `lastPx`      | `DecimalString` | `true`   | Last trade price                      |
| `openPx`      | `DecimalString` | `true`   | Open price                            |
| `highPx`      | `DecimalString` | `true`   | High price                            |
| `lowPx`       | `DecimalString` | `true`   | Low price                             |
| `volume`      | `DecimalString` | `true`   | Total traded base asset volume        |
| `quoteVolume` | `DecimalString` | `true`   | Total traded quote asset volume       |
| `openTime`    | `uint64`        | `true`   | Statistics open time in milliseconds  |
| `closeTime`   | `uint64`        | `true`   | Statistics close time in milliseconds |

### Mark Price Ticker (perps only)

#### MarkPriceTicker

| Name              | Type            | Required | Description                       |
| ----------------- | --------------- | -------- | --------------------------------- |
| `symbol`          | `string`        | `true`   | Symbol name                       |
| `fundingRate`     | `DecimalString` | `true`   | Current funding rate              |
| `nextFundingTime` | `uint64`        | `true`   | Next funding time in milliseconds |
| `indexPrice`      | `DecimalString` | `true`   | Current index price               |
| `markPrice`       | `DecimalString` | `true`   | Current mark price                |
| `openInterest`    | `DecimalString` | `true`   | Current open interest             |

### Book Ticker

#### BookTicker

| Name     | Type            | Required | Description       |
| -------- | --------------- | -------- | ----------------- |
| `symbol` | `string`        | `true`   | Symbol name       |
| `bidPx`  | `DecimalString` | `true`   | Best bid price    |
| `bidSz`  | `DecimalString` | `true`   | Best bid quantity |
| `askPx`  | `DecimalString` | `true`   | Best ask price    |
| `askSz`  | `DecimalString` | `true`   | Best ask quantity |

### Orderbook

#### OrderBook

| Name          | Type                  | Required | Description                        |
| ------------- | --------------------- | -------- | ---------------------------------- |
| `blockTime`   | `uint64`              | `true`   | Block time in milliseconds         |
| `blockHeight` | `uint64`              | `true`   | Block number                       |
| `updateID`    | `uint64`              | `true`   | Last update ID for sync            |
| `bids`        | `Array<[price, qty]>` | `true`   | Bid levels (price, quantity pairs) |
| `asks`        | `Array<[price, qty]>` | `true`   | Ask levels (price, quantity pairs) |

### Candle/KLines

#### RPCKline

| Name | Type            | Required | Description                     |
| ---- | --------------- | -------- | ------------------------------- |
| `t`  | `uint64`        | `true`   | Kline open time in milliseconds |
| `o`  | `DecimalString` | `true`   | Open price                      |
| `h`  | `DecimalString` | `true`   | High price                      |
| `l`  | `DecimalString` | `true`   | Low price                       |
| `c`  | `DecimalString` | `true`   | Close price                     |
| `v`  | `DecimalString` | `true`   | Base asset volume               |
| `q`  | `DecimalString` | `true`   | Quote asset volume              |
| `n`  | `uint64`        | `false`  | Number of trades                |

### Market Trades

#### Trade

| Name | Type            | Required | Description                |
| ---- | --------------- | -------- | -------------------------- |
| `t`  | `uint64`        | `true`   | Trade ID                   |
| `T`  | `uint64`        | `true`   | Trade time in milliseconds |
| `s`  | `string`        | `true`   | Symbol name                |
| `p`  | `DecimalString` | `true`   | Price                      |
| `q`  | `DecimalString` | `true`   | Quantity                   |
| `S`  | `OrderSideEnum` | `true`   | Side: `BUY` or `SELL`      |
| `bi` | `uint64`        | `false`  | Buyer account ID           |
| `si` | `uint64`        | `false`  | Seller account ID          |

### User Balance

#### SpotAccountBalances

| Name          | Type                 | Required | Description                |
| ------------- | -------------------- | -------- | -------------------------- |
| `blockTime`   | `uint64`             | `true`   | Block time in milliseconds |
| `blockHeight` | `uint64`             | `true`   | Block number               |
| `balances`    | `Array<SpotBalance>` | `true`   | List of non zero balances  |

**SpotBalance**

| Name     | Type            | Required | Description                      |
| -------- | --------------- | -------- | -------------------------------- |
| `id`     | `uint64`        | `true`   | Unique coin ID                   |
| `coin`   | `string`        | `true`   | Coin name                        |
| `total`  | `DecimalString` | `true`   | Total balance (including locked) |
| `locked` | `DecimalString` | `true`   | Locked balance in open orders    |

#### PerpsAccountBalance

| Name          | Type                  | Required | Description                |
| ------------- | --------------------- | -------- | -------------------------- |
| `blockTime`   | `uint64`              | `true`   | Block time in milliseconds |
| `blockHeight` | `uint64`              | `true`   | Block number               |
| `balances`    | `Array<PerpsBalance>` | `true`   | List of non zero balances  |

**PerpsBalance**

| Name          | Type            | Required | Description                          |
| ------------- | --------------- | -------- | ------------------------------------ |
| `id`          | `uint64`        | `true`   | Coin ID                              |
| `coin`        | `string`        | `true`   | Coin name                            |
| `total`       | `DecimalString` | `true`   | The wallet balance                   |
| `marginRatio` | `DecimalString` | `true`   | The margin ratio of this coin        |
| `price`       | `DecimalString` | `false`  | The oracle price of this coin in USD |

### User Order

#### SpotAccountOpenOrder

| Name          | Type               | Required | Description                |
| ------------- | ------------------ | -------- | -------------------------- |
| `blockTime`   | `uint64`           | `true`   | Block time in milliseconds |
| `blockHeight` | `uint64`           | `true`   | Block number               |
| `orders`      | `Array<SpotOrder>` | `true`   | List of open orders        |

**SpotOrder**

| Name            | Type              | Required | Description                         |
| --------------- | ----------------- | -------- | ----------------------------------- |
| `orderID`       | `uint64`          | `true`   | Order ID                            |
| `clOrdID`       | `string`          | `false`  | Client order ID                     |
| `symbol`        | `string`          | `true`   | Symbol name                         |
| `side`          | `OrderSideEnum`   | `true`   | Order side                          |
| `type`          | `OrderTypeEnum`   | `true`   | Order type                          |
| `timeInForce`   | `TimeInForceEnum` | `false`  | Time in force                       |
| `price`         | `DecimalString`   | `false`  | Order price                         |
| `origQty`       | `DecimalString`   | `false`  | Original quantity                   |
| `origQty`       | `funds`           | `false`  | Order Original funds                |
| `executedQty`   | `DecimalString`   | `true`   | Executed quantity                   |
| `executedValue` | `DecimalString`   | `true`   | Cumulative quote quantity           |
| `marginFrozen`  | `DecimalString`   | `true`   | Margin frozen by this order         |
| `status`        | `OrderStatusEnum` | `true`   | Order status                        |
| `createdAt`     | `uint64`          | `false`  | Order creation time in milliseconds |
| `updatedAt`     | `uint64`          | `false`  | Order update time in milliseconds   |

#### PerpsAccountOpenOrder

| Name          | Type                | Required | Description                |
| ------------- | ------------------- | -------- | -------------------------- |
| `blockTime`   | `uint64`            | `true`   | Block time in milliseconds |
| `blockHeight` | `uint64`            | `true`   | Block number               |
| `orders`      | `Array<PerpsOrder>` | `true`   | List of open orders        |

**PerpsOrder**

| Name               | Type               | Required | Description                                                    |
| ------------------ | ------------------ | -------- | -------------------------------------------------------------- |
| `orderID`          | `uint64`           | `true`   | Order ID                                                       |
| `clOrdID`          | `string`           | `false`  | Client order ID                                                |
| `symbol`           | `string`           | `true`   | Symbol name                                                    |
| `side`             | `OrderSideEnum`    | `true`   | Order side                                                     |
| `type`             | `OrderTypeEnum`    | `true`   | Order type                                                     |
| `timeInForce`      | `TimeInForceEnum`  | `false`  | Time in force                                                  |
| `price`            | `DecimalString`    | `false`  | Order price                                                    |
| `origQty`          | `DecimalString`    | `false`  | Original quantity                                              |
| `funds`            | `DecimalString`    | `false`  | Order Original funds                                           |
| `executedQty`      | `DecimalString`    | `true`   | Executed quantity                                              |
| `executedValue`    | `DecimalString`    | `true`   | Cumulative quote quantity                                      |
| `marginFrozen`     | `DecimalString`    | `true`   | Margin frozen by this order                                    |
| `status`           | `OrderStatusEnum`  | `true`   | Order status                                                   |
| `createdAt`        | `uint64`           | `false`  | Order creation time in milliseconds                            |
| `updatedAt`        | `uint64`           | `false`  | Order update time in milliseconds                              |
| `positionSide`     | `PositionSideEnum` | `true`   | Position side                                                  |
| `reduceOnly`       | `boolean`          | `true`   | Reduce only flag                                               |
| `stopPrice`        | `DecimalString`    | `false`  | Stop price for TP/SL                                           |
| `stopType`         | `StopTypeEnum`     | `false`  | Stop type for TP/SL                                            |
| `triggerType`      | `TriggerTypeEnum`  | `false`  | Trigger type for TP/SL                                         |
| `positionID`       | `uint64`           | `false`  | Position ID this order is associated with (for position TP/SL) |
| `primaryOrderID`   | `uint64`           | `false`  | Primary order ID this stop is attached to (for attached stops) |
| `attachedOrderIDs` | `Array<uint64>`    | `false`  | Order IDs of stops attached to this order (TP/SL)              |

### User Position (perps only)

#### PerpsAccountOpenPosition

| Name          | Type              | Required | Description                |
| ------------- | ----------------- | -------- | -------------------------- |
| `blockTime`   | `uint64`          | `true`   | Block time in milliseconds |
| `blockHeight` | `uint64`          | `true`   | Block number               |
| `positions`   | `Array<Position>` | `true`   | List of open positions     |

**Position**

| Name            | Type               | Required | Description                                                          |
| --------------- | ------------------ | -------- | -------------------------------------------------------------------- |
| `id`            | `uint64`           | `true`   | Position ID                                                          |
| `symbol`        | `string`           | `true`   | Symbol name                                                          |
| `marginMode`    | `MarginModeEnum`   | `true`   | Margin mode                                                          |
| `side`          | `PositionSideEnum` | `true`   | Position side. Always BOTH for now.                                  |
| `size`          | `DecimalString`    | `true`   | Position size. Negative means short, positive means long.            |
| `initialMargin` | `DecimalString`    | `true`   | Position initial margin. If isolated, this is also isolated margin.  |
| `avgEntryPrice` | `DecimalString`    | `true`   | Average position entry price                                         |
| `cumOpenCost`   | `DecimalString`    | `true`   | Cumulative position open cost                                        |
| `cumTradingFee` | `DecimalString`    | `true`   | Cumulative trading fee                                               |
| `cumClosedSize` | `DecimalString`    | `true`   | Total closed size during the position lifetime                       |
| `avgClosePrice` | `DecimalString`    | `true`   | Average position close price                                         |
| `maxSize`       | `DecimalString`    | `true`   | Max position size during the position lifetime                       |
| `realizedPnL`   | `DecimalString`    | `true`   | Realized profit and loss, includes trading fees and liquidation loss |
| `leverage`      | `uint32`           | `true`   | Position leverage                                                    |
| `active`        | `bool`             | `true`   | The position is active/working                                       |
| `isTakenOver`   | `bool`             | `true`   | Whether the position is taken over by liquidator                     |
| `takeOverPrice` | `DecimalString`    | `true`   | Mark price when taken over.                                          |
| `createdAt`     | `uint64`           | `true`   | Position creation timestamp, in milliseconds                         |
| `updatedAt`     | `uint64`           | `true`   | Position updated timestamp, in milliseconds                          |

* If position side is `BOTH`, then positive position size is `LONG`, negative position size is `SHORT`, zero position size means position is closed.
* If position side is `LONG` or `SHORT`. The position size is positive or zero, zero means position is closed.
* For now, position side is always `BOTH`.

### User Funding (perps only)

#### PerpsUserFunding

| Name           | Type               | Required | Description                       |
| -------------- | ------------------ | -------- | --------------------------------- |
| `symbol`       | `string`           | `true`   | Symbol name                       |
| `positionID`   | `uint64`           | `true`   | Position ID                       |
| `positionSide` | `PositionSideEnum` | `true`   | `LONG` or `SHORT`                 |
| `fundingFee`   | `DecimalString`    | `true`   | Funding fee (negative = received) |
| `feeCoin`      | `string`           | `true`   | The name of the fee coin          |
| `timestamp`    | `uint64`           | `true`   | Funding time in milliseconds      |

### User API Key

#### APIKey

| Name        | Type             | Required | Description                             |
| ----------- | ---------------- | -------- | --------------------------------------- |
| `name`      | `string`         | `true`   | API key name                            |
| `type`      | `APIKeyTypeEnum` | `true`   | API key type. String value of the enum. |
| `publicKey` | `HexString`      | `true`   | Public key (hex string)                 |
| `expiresAt` | `uint64`         | `true`   | Expiration timestamp (milliseconds)     |

### Fee Rate

#### FeeRate

| Name              | Type            | Required | Description                                                                           |
| ----------------- | --------------- | -------- | ------------------------------------------------------------------------------------- |
| `makerFeeRate`    | `DecimalString` | `true`   | Effective maker fee rate after discounts. Negative values indicate a maker rebate.    |
| `takerFeeRate`    | `DecimalString` | `true`   | Effective taker fee rate after discounts.                                             |
| `feeTier`         | `int`           | `true`   | Fee tier (0-6) determined by the user's 14-day weighted trading volume.               |
| `stakingTier`     | `int`           | `true`   | Staking tier (0-6) determined by the user's SOSO token staking amount.                |
| `makerRebateTier` | `int`           | `true`   | Maker rebate tier (0-3) determined by the user's share of global 14-day maker volume. |

### User Trade

#### UserTrade

| Name       | Type            | Required | Description                 |
| ---------- | --------------- | -------- | --------------------------- |
| `symbol`   | `string`        | `true`   | Symbol name                 |
| `tradeID`  | `uint64`        | `true`   | Trade ID                    |
| `orderID`  | `uint64`        | `true`   | Order ID                    |
| `clOrdID`  | `string`        | `true`   | Client Order ID             |
| `side`     | `OrderSideEnum` | `true`   | Trade side: `BUY` or `SELL` |
| `price`    | `DecimalString` | `true`   | Trade price                 |
| `quantity` | `DecimalString` | `true`   | Trade quantity              |
| `fee`      | `DecimalString` | `false`  | Commission amount           |
| `feeCoin`  | `string`        | `false`  | Commission asset            |
| `isMaker`  | `bool`          | `false`  | Whether trade was maker     |
| `time`     | `uint64`        | `true`   | Trade time in milliseconds  |

## WebSocket Types

### Misc types

#### WsPingRequest

```typescript
interface WsPingRequest {
  op: "ping";
}
```

#### WsPingResponse

```typescript
// send when server receive WsPingRequest from client
interface WsPingResponse {
  op: "pong";
}
```

#### WsErrorResponse

```typescript
// for unexpected error, like Invalid JSON
interface WsErrorResponse {
  op: "error";
  error: string; // Error message
  connID: string; // WebSocket connection ID
}
```

#### WsSubscriptionRequest

```typescript
interface WsSubscriptionRequest {
  op: "subscribe" | "unsubscribe";
  id: number | null; // Optional client originated request identifier sent as acknowledgment in the response.
  params: WsSubscriptionParams;
}
```

#### WsSubscriptionResponse

```typescript
interface WsSubscriptionResponse {
  op: "subscribe" | "unsubscribe";
  id: number | null; // Optional client originated request identifier sent as acknowledgment in the response.
  result: WsSubscriptionResult | null;
  success: boolean; // Indicates if the request was successfully processed by the engine.
  error: string | null; // Condition: If success is false. Error message.
  connID: string; // WebSocket connection ID
  time_in: number; // The timestamp when the subscription was received on the wire, just prior to parsing data, in milliseconds.
  time_out: number; // The timestamp when the acknowledgement was sent on the wire, just prior to transmitting data, in milliseconds.
}
```

#### WsSubscriptionParams

```typescript
type WsSubscriptionParams =
  | WsTickerSubscriptionParams
  | WsAllTickerSubscriptionParams
  | WsMiniTickerSubscriptionParams
  | WsAllMiniTickerSubscriptionParams
  | WsBookTickerSubscriptionParams
  | WsAllBookTickerSubscriptionParams
  | WsMarkPriceSubscriptionParams
  | WsAllMarkPriceSubscriptionParams
  | WsL2BookSubscriptionParams
  | WsL4BookSubscriptionParams
  | WsCandleSubscriptionParams
  | WsTradeSubscriptionParams
  | WsUserFrontendStateSubscriptionParams
  | WsAccountUpdateSubscriptionParams
  | WsOrderUpdateSubscriptionParams
  | WsUserTradeSubscriptionParams
  | WsUserEventSubscriptionParams;
```

#### WsSubscriptionResult

```typescript
type WsSubscriptionResult =
  | WsTickerSubscriptionResult
  | WsAllTickerSubscriptionResult
  | WsMiniTickerSubscriptionResult
  | WsAllMiniTickerSubscriptionResult
  | WsBookTickerSubscriptionResult
  | WsAllBookTickerSubscriptionResult
  | WsMarkPriceSubscriptionResult
  | WsAllMarkPriceSubscriptionResult
  | WsL2BookSubscriptionResult
  | WsL4BookSubscriptionResult
  | WsCandleSubscriptionResult
  | WsTradeSubscriptionResult
  | WsUserFrontendStateSubscriptionResult
  | WsAccountUpdateSubscriptionResult
  | WsOrderUpdateSubscriptionResult
  | WsUserTradeSubscriptionResult
  | WsUserEventSubscriptionResult;
```

#### WsTickerSubscriptionParams

```typescript
interface WsTickerSubscriptionParams {
  channel: "ticker";
  symbols: Array<string>; // A list of currency pairs
}
```

#### WsTickerSubscriptionResult

```typescript
interface WsTickerSubscriptionResult {
  channel: "ticker";
  symbol: string;
}
```

#### WsAllTickerSubscriptionParams

```typescript
interface WsAllTickerSubscriptionParams {
  channel: "allTicker";
}
```

#### WsAllTickerSubscriptionResult

```typescript
type WsAllTickerSubscriptionResult = WsAllTickerSubscriptionParams;
```

#### WsMiniTickerSubscriptionParams

```typescript
interface WsMiniTickerSubscriptionParams {
  channel: "miniTicker";
  symbols: Array<string>; // A list of currency pairs
}
```

#### WsMiniTickerSubscriptionResult

```typescript
interface WsMiniTickerSubscriptionResult {
  channel: "miniTicker";
  symbol: string;
}
```

#### WsAllMiniTickerSubscriptionParams

```typescript
interface WsAllMiniTickerSubscriptionParams {
  channel: "allMiniTicker";
}
```

#### WsAllMiniTickerSubscriptionResult

```typescript
type WsAllMiniTickerSubscriptionResult = WsAllMiniTickerSubscriptionParams;
```

#### WsBookTickerSubscriptionParams

```typescript
interface WsBookTickerSubscriptionParams {
  channel: "bookTicker";
  symbols: Array<string>; // A list of currency pairs
}
```

#### WsBookTickerSubscriptionResult

```typescript
interface WsBookTickerSubscriptionResult {
  channel: "bookTicker";
  symbol: string;
}
```

#### WsAllBookTickerSubscriptionParams

```typescript
interface WsAllBookTickerSubscriptionParams {
  channel: "allBookTicker";
}
```

#### WsAllBookTickerSubscriptionResult

```typescript
type WsAllBookTickerSubscriptionResult = WsAllBookTickerSubscriptionParams;
```

#### WsMarkPriceSubscriptionParams

```typescript
interface WsMarkPriceSubscriptionParams {
  channel: "markPrice";
  symbols: Array<string>; // A list of currency pairs
}
```

#### WsMarkPriceSubscriptionResult

```typescript
interface WsMarkPriceSubscriptionResult {
  channel: "markPrice";
  symbol: string;
}
```

#### WsAllMarkPriceSubscriptionParams

```typescript
interface WsAllMarkPriceSubscriptionParams {
  channel: "allMarkPrice";
}
```

#### WsAllMarkPriceSubscriptionResult

```typescript
type WsAllMarkPriceSubscriptionResult = WsAllMarkPriceSubscriptionParams;
```

#### WsL2BookSubscriptionParams

```typescript
interface WsL2BookSubscriptionParams {
  channel: "l2Book";
  symbol: string;
  tickSize: string; // supported tickSizes are symbol.tickSize * (1, 2, 5, 10, 100, 1000)
}
```

#### WsL2BookSubscriptionResult

```typescript
type WsL2BookSubscriptionResult = WsL2BookSubscriptionParams;
```

#### WsL4BookSubscriptionParams

```typescript
interface WsL4BookSubscriptionParams {
  channel: "l4Book";
  symbol: string;
  level: number | null; // Possible values: [10, 25, 100, 500, 1000], Default 10
}
```

#### WsL4BookSubscriptionResult

```typescript
interface WsL4BookSubscriptionResult {
  channel: "l4Book";
  symbol: string;
  level: number;
}
```

#### WsCandleSubscriptionParams

```typescript
interface WsCandleSubscriptionParams {
  channel: "candle";
  symbol: string;
  // spot: "1m", "5m", "15m", "30m", "1h", "4h", "8h", "12h", "1D", "3D", "1W", "1M"
  // perps: "1m", "5m", "15m", "30m", "1h", "4h", "1D", "1W", "1M"
  interval: string;
}
```

#### WsCandleSubscriptionResult

```typescript
type WsCandleSubscriptionResult = WsCandleSubscriptionParams;
```

#### WsTradeSubscriptionParams

```typescript
interface WsTradeSubscriptionParams {
  channel: "trade";
  symbols: Array<string>;
}
```

#### WsTradeSubscriptionResult

```typescript
type WsTradeSubscriptionResult = WsTradeSubscriptionParams;
```

#### WsUserFrontendStateSubscriptionParams

```typescript
interface WsUserFrontendStateSubscriptionParams {
  channel: "accountState";
  user: string;
  accountID: number | null; // default is primary account ID of the user
}
```

#### WsUserFrontendStateSubscriptionResult

```typescript
interface WsUserFrontendStateSubscriptionResult {
  channel: "accountState";
  user: string;
  accountID: number;
}
```

#### WsAccountUpdateSubscriptionParams

```typescript
interface WsAccountUpdateSubscriptionParams {
  channel: "accountUpdate";
  user: string;
  accountID: number | null; // default is primary account ID of the user
}
```

#### WsAccountUpdateSubscriptionResult

```typescript
interface WsAccountUpdateSubscriptionResult {
  channel: "accountUpdate";
  user: string;
  accountID: number;
}
```

#### WsOrderUpdateSubscriptionParams

```typescript
interface WsOrderUpdateSubscriptionParams {
  channel: "accountOrderUpdate";
  user: string;
  accountID: number | null; // default is primary account ID of the user
  symbols: Array<string> | null; // default push all updates
}
```

#### WsOrderUpdateSubscriptionResult

```typescript
interface WsOrderUpdateSubscriptionResult {
  channel: "accountOrderUpdate";
  user: string;
  accountID: number;
  symbol: string | null; // null for all symbol subscription
}
```

#### WsUserTradeSubscriptionParams

```typescript
interface WsUserTradeSubscriptionParams {
  channel: "accountTrade";
  user: string;
  accountID: number | null; // default is primary account ID of the user
  symbols: Array<string> | null; // default push all updates
}
```

#### WsUserTradeSubscriptionResult

```typescript
interface WsUserTradeSubscriptionResult {
  channel: "accountTrade";
  user: string;
  accountID: number;
  symbol: string | null; // default push all updates
}
```

#### WsUserEventSubscriptionParams

```typescript
interface WsUserEventSubscriptionParams {
  channel: "accountEvent";
  user: string;
  accountID: number | null; // default is primary account ID of the user
}
```

#### WsUserEventSubscriptionResult

```typescript
interface WsUserEventSubscriptionResult {
  channel: "accountEvent";
  user: string;
  accountID: number;
}
```

### Ticker

#### WsTickerData

```typescript
interface WsTickerData {
  s: string; // The symbol of the currency pair
  c: string; // Close price / Last Price within the past 24 hours
  Q: string; // Last traded quantity within the past 24 hours
  w: string; // 24-hour volume weighted average price.
  a: string; // Best ask price.
  A: string; // Best ask quantity.
  b: string; // Best bid price.
  B: string; // Best bid quantity.
  p: string; // 24-hour price change (in quote currency).
  P: number; // 24-hour price change (in percentage points).
  o: string; // Open price
  h: string; // High price
  l: string; // Low price
  v: string; // Total traded base asset volume
  q: string; // Total traded quote asset volume
  O: number; // Statistics open time
  C: number; // Statistics close time
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
}
```

### Mini Ticker

#### WsMiniTickerData

```typescript
interface WsMiniTickerData {
  s: string; // The symbol of the currency pair
  c: string; // Close price / Last Price within the past 24 hours
  o: string; // Open price
  h: string; // High price
  l: string; // Low price
  v: string; // Total traded base asset volume
  q: string; // Total traded quote asset volume
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
}
```

### Book Ticker

#### WsBookTickerData

```typescript
interface WsBookTickerData {
  s: string; // The symbol of the currency pair
  u: number; // order book updateID
  a: string; // Best ask price.
  A: string; // Best ask quantity.
  b: string; // Best bid price.
  B: string; // Best bid quantity.
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
}
```

### Mark Price (perps only)

#### WsMarkPriceData

```typescript
interface WsMarkPriceData {
  s: string; // The symbol of the currency pair
  oi: string; // Current open interest in base asset.
  p: string; // Current mark price
  i: string; // Current index price
  r: string; // Current estimated funding rate
  T: string; // Next funding time
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
}
```

### Book Depth Snapshot

#### WsDepthSnapshotData

```typescript
interface WsDepthSnapshotData {
  s: string; // The symbol of the currency pair
  u: number; // order book updateID
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
  a: Array<[string, string]>; // The list of levels in ask side. Tuple of <price, qty>.
  b: Array<[string, string]>; // The list of levels in bid side. Tuple of <price, qty>.
}
```

### Book Depth Update

#### WsDepthUpdateData

```typescript
interface WsDepthUpdateData {
  s: string; // The symbol of the currency pair
  U: number; // The first order book updateID
  u: number; // The last order book updateID
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
  a: Array<[string, string]>; // The list of updated ask side levels. Tuple of <price, qty>.
  b: Array<[string, string]>; // The list of updated bid side levels. Tuple of <price, qty>.
}
```

### Candle / Kline

#### Candle

```typescript
interface Candle {
  t: number; // Kline start time
  T: number; // Kline close time
  s: string; // Symbol
  i: string; // Interval
  o: string; // Open price
  c: string; // Close price
  h: string; // High price
  l: string; // Low price
  v: string; // Base asset volume
  q: string; // Quote asset volume
  n: number; // Number of trades
  x: boolean; // Is this kline closed?
}
```

### Account Update

* Spot Account Update

#### WsSpotBalance

```typescript
interface WsSpotBalance {
  i: number; // asset/coin id
  a: string; // asset/coin name
  t: string; // wallet balance, including locked by open orders
  l: string; // locked balance by open orders
}
```

#### WsSpotAccountUpdate

```typescript
interface WsSpotAccountUpdate {
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
  T: number; // The update time in milliseconds, the timestamp of the block where this update happens
  h: number; // the block height of this update
  B: Array<WsSpotBalance>; // List of updated balances
}
```

* Perp Account Update

#### WsPerpsBalanceLite

```typescript
interface WsPerpsBalanceLite {
  i: number; // asset/coin id
  a: string; // asset/coin name
  wb: string; // wallet balance
}
```

#### WsPerpsPositionLite

```typescript
interface WsPerpsPositionLite {
  i: number; // position id
  s: string; // symbol
  sz: string; // position size.
  ep: string; // position entry Price
  iw: string | null; // isolated wallet balance (if isolated position)
  ps: PositionSideEnum; // position side
}
// If position side is `BOTH`, then positive position size is LONG, negative position size is SHORT, zero position size means position is closed.
// If position side is `LONG` or `SHORT`. The position size is positive or zero, zero means position is closed.
// For now, position side is always `BOTH`.
```

#### WsPerpsAccountUpdate

```typescript
interface WsPerpsAccountUpdate {
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
  T: number; // The update time in milliseconds, the timestamp of the block where this update happens
  h: number; // the block height of this update
  B: Array<WsPerpsBalanceLite>; // List of updated balances
  P: Array<WsPerpsPositionLite>; // List of updated positions
}
```

### Order Update

* Spot Order Update

#### WsSpotOrder

```typescript
interface WsSpotOrder {
  s: string; // Symbol
  c: string; // Client Order ID
  i: number; // System-generated unique Order ID
  S: OrderSideEnum; // Order Side, "BUY" is buy, "SELL" is sell
  o: OrderTypeEnum; // Order Type, LIMIT or MARKET
  f: TimeInForceEnum; // Time In Force, GTC, IOC or GTX
  p: string; // Price in quote currency
  q: string; // original order size
  F: string | null; // original funds of this order
  X: OrderStatusEnum; // Current order status
  z: string; // Cumulative filled quantity = sum executed trade.sz
  v: string; // Cumulative filled value = sum executed trade.sz * trade.px
  M: string; // margin locked by this order
}
```

#### WsSpotOrderUpdate

```typescript
type WsSpotOrderUpdate = WsSpotOrder & {
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
  T: number; // The update time in milliseconds, the timestamp of the block where this trade happens
  t: number | null; // Trade ID
  l: string | null; // Last executed quantity
  L: string | null; // Last executed price
  n: string | null; // Commission amount
  m: boolean | null; // whether this trade the maker side?
  x: ExecutionTypeEnum; // Current execution type
  r: string | null; // execution reason
};
```

* Perp Order Update

#### WsPerpsOrder

```typescript
type WsPerpsOrder = WsSpotOrder & {
  ps: PositionSideEnum; // position side
  R: boolean; // Is this reduce only
  sp: string | null; // stop price
  st: StopTypeEnum | null; // stop type
  tt: TriggerTypeEnum | null; // trigger type
```

```typescript
  pid: number | null; // Position ID this order is associated with (for position TP/SL)
  poid: number | null; // Primary order ID this stop is attached to (for attached stops)
  aoids: Array<number> | null; // Order IDs of stops attached to this order (TP/SL)
};
```

#### WsPerpsOrderUpdate

```typescript
type WsPerpsOrderUpdate = WsPerpsOrder & {
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
  T: number; // The update time in milliseconds, the timestamp of the block where this trade happens
  t: number | null; // Trade ID
  l: string | null; // Last executed quantity
  L: string | null; // Last executed price
  n: string | null; // Commission amount
  m: boolean | null; // whether this trade the maker side?
  x: ExecutionTypeEnum; // Current execution type
  r: string | null; // execution reason
};
```

### Market Trades

#### WsTrade

```typescript
interface WsTrade {
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
  T: number; // The trade time in milliseconds, the timestamp of the block where this trade happens
  t: number; // Trade ID
  s: string; // Symbol
  S: OrderSideEnum; // If side is "BUY", buyer is the taker, seller is the maker. If side is "SELL", buyer is the maker, seller is the taker.
  p: string; // trade price
  q: string; // trade quantity
  bi: number; // Buyer Account ID
  si: number; // Seller Account ID
}
```

### User Trades

* Spot

#### WsSpotUserTrade

```typescript
interface WsSpotUserTrade {
  T: number; // The trade time in milliseconds, the timestamp of the block where this trade happens
  t: number; // Trade ID
  s: string; // Symbol
  i: number; // Order ID
  c: string; // Client Order ID
  S: OrderSideEnum; // order side
  p: string; // trade price
  q: string; // trade quantity
  f: string; // trading fee
  m: boolean; // whether this trade the maker side?
}
```

* Perps

#### WsPerpsUserTrade

```typescript
type WsPerpsUserTrade = WsSpotUserTrade & {
  d: string; // used for frontend display, Long, Short, Close Long, Close Short, Long -> Short, Short -> Long
};
```

### User Frontend State

* Spot

#### WsSpotState

```typescript
interface WsSpotState {
  user: string; // User evm address
  aid: number; // Account ID
  uid: number; // User ID
  B: Array<WsSpotBalance>; // List of balances
  O: Array<WsSpotOrder>; // List of latest 100 open orders
}
```

* Perps

#### WsPerpsBalance

```typescript
interface WsPerpsBalance {
  i: number; // Coin ID
  a: string; // Coin Name
  wb: string; // The wallet balance
  mr: string; // The margin ratio of this coin in percentage
  px: string; // The oracle price of this coin in USD
}
```

#### WsPerpsPosition

```typescript
interface WsPerpsPosition {
  i: number; // Position ID
  s: string; // Symbol
  m: MarginModeEnum; // Margin Mode, ISOLATED or CROSS
  ps: PositionSideEnum; // Position Side
  sz: string; // position size, positive is long, negative is short, zero means position closed
  iw: string | null; // Isolated margin for isolated positions
  ep: string; // Average position entry price
  co: string; // Cumulative position open cost
  cf: string; // Cumulative trading fee
  cc: string; // Total closed size during the position lifetime
  cp: string; // Average position close price
  ms: string; // Max position size during the position lifetime
  cr: string; // Realized profit and loss, also includes trading fee and liquidation loss
  ur: string; // Unrealized  profit and loss
  l: number; // Position Leverage
  lp: string; // Position liquidation price
}
// If position side is `BOTH`, then positive position size is LONG, negative position size is SHORT, zero position size means position is closed.
// If position side is `LONG` or `SHORT`. The position size is positive or zero, zero means position is closed.
// For now, position side is always `BOTH`.
```

#### WsPerpsSymbolConfig

```typescript
interface WsPerpsSymbolConfig {
  s: string; // Symbol
  l: number; // leverage
  m: MarginModeEnum; // Margin Mode, ISOLATED or CROSS
}
```

#### WsPerpsBalanceDetailed

```typescript
type WsPerpsBalanceDetailed = WsPerpsBalance & {
  iw: string | null; // isolated frozen margin for position or open orders, only for vUSDC
  aw: string; // available wallet balance for margin
  ww: string; // available wallet balance for withdrawal
  wm: string; // wallet balance corresponding margin
  am: string; // available wallet balance corresponding margin
};
```

#### WsPerpsState

```typescript
interface WsPerpsState {
  user: string; // user evm address
  aid: number; // Account ID
  uid: number; // User ID
  av: string; // Cross account value
  am: string; // available margin for cross position
  ami: string; // available margin for isolated position
  amw: string; // available margin for transfer
  im: string; // isolated frozen margin for position
  cm: string; // cross frozen margin for position
  oim: string; // isolated frozen margin for open position
  ocm: string; // cross frozen margin for open position
  B: Array<WsPerpsBalanceDetailed>; // List of balances
  O: Array<WsPerpsOrder>; // List of latest 100 open orders
  P: Array<WsPerpsPosition>; // List of open perps position
  S: Array<WsPerpsSymbolConfig>; // List of touched symbol config
}
```

### User Event

#### PerpsLiquidatedPosition

```typescript
interface PerpsLiquidatedPosition {
  s: string; // symbol
  ps: PositionSideEnum; // position side
  sz: string; // position size, positive is long, negative is short
  mp: string; // mark price at liquidation
  lp: string | null; // actual liquidation price for this position.
}
// If position side is `BOTH`, then positive position size is LONG, negative position size is SHORT, zero position size means position is closed.
// If position side is `LONG` or `SHORT`. The position size is positive or zero, zero means position is closed.
// For now, position side is always `BOTH`.
```

#### WsUserLiquidation

```typescript
// Perp only
// both liquidator and liquidated user will receive the same event.
interface WsUserLiquidation {
  E: number; // The timestamp when this event was sent on the wire, just prior to transmitting data, in milliseconds.
  type: "liquidation";
  lid: number; // liquidator account ID
  aid: number; // Account ID
  av: string; // Account value. for isolated positions this is the isolated margin
  mm: MarginModeEnum; // margin mode
  B: Array<WsPerpsBalanceLite>; // list of liquidated balances
  P: Array<PerpsLiquidatedPosition>; // list of liquidated positions
}
```

#### WsUserEvent

```typescript
type WsUserEvent = WsUserLiquidation;
```
