> For the complete documentation index, see [llms.txt](https://guide.traderevolution.com/traderevolution-api/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://guide.traderevolution.com/traderevolution-api/traderevolution-apis/client-api/subscription-to-market-data.md).

# Subscription to market data

This page describes mechanism of receiving market data via websocket

## Connection

In order to receive market data, the connection should be opened to `wss://sandbox-api.traderevolution.com/traderevolution/v1/stream/quotes`**.**&#x20;

{% hint style="warning" %}
Please note that the URL specified for connection is default, but it can be customized according to the customer's requirements.
{% endhint %}

There is a "Ping-Pong" mechanism for WebSocket connections. To maintain active WebSocket connections and detect client inactivity, the following message format is used:

```json
{"event": "PING", "t": 1731538318526}
{"event": "PONG", "t": 1731538318526}
```

## Subscribing to market data

The request body must contain the following parameters:

**Body**

| Name        | Type    | Description                                                                                                                  |
| ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `event`     | string  | Should be always `subscribe` in this case.                                                                                   |
| `requestId` | integer | Request identifier generated by the client side. Will be used in the response.                                               |
| `payload`   | object  | An object that contains information about the instrument to which the subscription for market data is made, see table below. |

**Payload object**

| Parameter    | Value                                                                                                                                                                                                                                                                                                            |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tiId*`      | The tradable ID of the instrument is specified here.                                                                                                                                                                                                                                                             |
| `accountId`  | This ID is used for determining routes that are available for account. The data will be returned by subscriptions. If this account has no subscriptions to the market data routes, then an error will be in the response.                                                                                        |
| `st*`        | The subscription type is specified here. The following types are supported: `level1`***,*** `level2`***,*** `trades`***,*** `dailyBar`***,*** `candles`***.***                                                                                                                                                   |
| `resolution` | This parameter specifies the aggregation type and is required for use with the ***st = candles*** only. Available values are: `1m`***,*** `5m`***,*** `15m`***,*** `30m`***,*** `1H`***,*** `4H`***,*** `1D`***,*** `1W`***,*** `1M`***.*** If the parameter is not specified the default value of `1m` is used. |

**Request body example**

```json
{
	"event": "subscribe",
	"requestId": 123,
	"payload": {
		"tiId": 22465,
		"accountId": 580,
		"st": "candles",
		"resolution": "5m"
	}
}


```

**Response**

The server will return the following parameters in a response:

* `event` - always returns “subscribe”.
* `requestId` - id of the request to which the response was sent.
* `s` - subscription status: `ok` - if successful, or `error` - if the subscription failed.
* `errmsg` - returns an error message in case the subscription fails.

{% tabs %}
{% tab title="200" %}

```json
{
	"event": "subscribe",
	"requestId": 123,
	"s": "ok"
}
```

{% endtab %}

{% tab title="400" %}

```json
{
	"event": "subscribe",
	"requestId": 123,
	"s": "error",
	"errormsg": "Error"
}
```

{% endtab %}
{% endtabs %}

**Possible errors**

| errmsg text                                 | Error                                                                                                                |
| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `Authorization error`                       | All subscription requests must be made after authorization. Otherwise, the following error will be received.         |
| `Unsupported event`                         | If an unsupported ***event*** is specified in the request, then the following error will be received.                |
| `Invalid subscription type`                 | If an unsupported ***subscription type*** is specified in the request, then the following error will be received.    |
| `Required fields are missing: <parameters>` | This error means that some required fields are not specified, with their indication.                                 |
| `Insufficient permissions`                  | If the specified subscription type is not available to the user by permission settings, then this error is received. |

{% hint style="warning" %}
**Behavior after subscription**

For the following subscription types(st), the server immediately sends the latest available data snapshot after a successful subscription:

* level1 – last known quote (best bid/ask)
* level2 – current market depth snapshot
* dailyBar – latest daily OHLC bar

This allows clients to display market data without waiting for the first live update.

For trades and candles, no initial data is sent — updates will arrive only when new trade or candle data is available.
{% endhint %}

## Market data streaming

### Level 1

An object with the following parameters will be returned in the response for the subscription to the Level 1 data:

<table><thead><tr><th width="374">Parameter</th><th>Value</th></tr></thead><tbody><tr><td><code>d</code></td><td>Considered below in more details.</td></tr><tr><td><code>s</code></td><td>Subscription status indicator: <code>ok</code> or <code>error</code> in case the subscription fails.</td></tr><tr><td><code>errmsg</code></td><td>This parameter contains the text of the error which occurred when <em><strong>s=error</strong></em>.</td></tr><tr><td><code>st</code></td><td>Always returned as <code>level1</code> for level 1.</td></tr></tbody></table>

**Object d structure**

| Name   | Description                                 |
| ------ | ------------------------------------------- |
| `ap`   | ASK                                         |
| `bp`   | BID                                         |
| `as`   | ASK volume                                  |
| `bs`   | BID volume                                  |
| `t`    | Date/Time in milliseconds (*UTC time zone*) |
| `tiId` | tradableId of the instrument                |

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
	"d": {
		"ap": 140.50,
		"bp": 139.50,
		"as": 10000,
		"bs": 50000,
		"t": 166687337600,
		"tiId": 22462,
	"st": "level1",
	"s": "ok"
	}
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
After subscribing to level1, the server immediately sends the last available quote (if present), even before any new updates are received.
{% endhint %}

### Level 2

Immediately after the subscription, a snapshot of the order book is sent by the server. An object with the following parameters will be returned in the response for the subscription to the Level 2 data:

<table><thead><tr><th width="374">Parameter</th><th>Value</th></tr></thead><tbody><tr><td><code>d</code></td><td>Considered below in more details.</td></tr><tr><td><code>s</code></td><td>Subscription status indicator, always <code>ok</code>.</td></tr><tr><td><code>st</code></td><td>Always returned as <code>level2</code> for level 2.</td></tr></tbody></table>

**Object d structure**

| Name   | Description                                                                                                                                                                                                                                                                                                                                                       |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tiId` | tradableId of the instrument.                                                                                                                                                                                                                                                                                                                                     |
| `asks` | <p>An array of objects. Each object determines the price level on the ask side. The object contains the following parameters: <br><code>p</code> - price<br><code>s</code> - volume<br><code>t</code> - date/time in milliseconds (<em>UTC time zone)</em></p><p><code>src</code> - source<br><code>quoteId</code> - position of this quote in the order book</p> |
| `bids` | An array of objects. Each object determines the price level on the bid side. The object contains the same parameters as for the *ask* side.                                                                                                                                                                                                                       |

**Response**

The response is sorted by the ***p*** (price) parameter: for the ***bid*** side - in descending order, and for the ***ask*** side - in ascending order.

{% hint style="warning" %}
This snapshot is sent immediately after a successful subscription.
{% endhint %}

### Trades

The object with the following parameters will be returned in the response for the subscription to the Trades:

<table><thead><tr><th width="374">Parameter</th><th>Value</th></tr></thead><tbody><tr><td><code>d</code></td><td>Considered below in more details.</td></tr><tr><td><code>s</code></td><td>Subscription status indicator:<code>ok</code> or <code>error</code> in case the subscription fails.</td></tr><tr><td><code>errmsg</code></td><td>This parameter contains the text of the error which occurred when <em><strong>s=error</strong></em>.</td></tr><tr><td><code>st</code></td><td>Always returned as <code>trades</code> for level 3.</td></tr></tbody></table>

**Object d structure**

| Name   | Description                                 |
| ------ | ------------------------------------------- |
| `tiId` | tradableId of the instrument                |
| `p`    | Price of the trade                          |
| `s`    | Volume of the trade                         |
| `src`  | Source of this trade                        |
| `t`    | Date/Time in milliseconds (*UTC time zone)* |

{% hint style="warning" %}
Unlike other types, the server does not send a snapshot of the last trade after subscription. New messages will be delivered only when new trades occur.
{% endhint %}

### Daily bar

Only daily bars with the type selected in the ***Display quotes by*** setting on the instrument level are sent here. An object with the following parameters will be returned in the response:

<table><thead><tr><th width="374">Parameter</th><th>Value</th></tr></thead><tbody><tr><td><code>d</code></td><td>Considered below in more details.</td></tr><tr><td><code>s</code></td><td>Subscription status indicator: <code>ok</code> or <code>error</code> in case the subscription fails.</td></tr><tr><td><code>errmsg</code></td><td>This parameter contains the text of the error which occurred when <em><strong>s=error</strong></em>.</td></tr><tr><td><code>st</code></td><td>Always returned as <code>dailyBar</code> for this type.</td></tr></tbody></table>

**Object d structure**

| Name   | Description                                 |
| ------ | ------------------------------------------- |
| `tiId` | tradableId of the instrument.               |
| `o`    | Bar open price                              |
| `h`    | High price                                  |
| `l`    | Low price                                   |
| `p`    | Previous close price                        |
| `v`    | Volume                                      |
| `t`    | Date/Time in milliseconds (*UTC time zone)* |

{% hint style="warning" %}
The latest available daily bar is sent immediately after a successful subscription.
{% endhint %}

### Candles

This type of subscription allows subscribing to the aggregated data. The type of aggregation should be specified in the `resolution` parameter. An object with the following parameters will be returned in the response:

<table><thead><tr><th width="374">Parameter</th><th>Value</th></tr></thead><tbody><tr><td><code>d</code></td><td>Considered below in more details.</td></tr><tr><td><code>s</code></td><td>Subscription status indicator: <code>ok</code> or <code>error</code> in case the subscription fails.</td></tr><tr><td><code>errmsg</code></td><td>This parameter contains the text of the error which occurred when <em><strong>s=error</strong></em>.</td></tr><tr><td><code>st</code></td><td>Always returned as <code>candles</code> for this type.</td></tr><tr><td><code>res</code></td><td>Resolution that was received in the request.</td></tr></tbody></table>

**Object d structure**

| Name   | Description                                 |
| ------ | ------------------------------------------- |
| `tiId` | tradableId of the instrument.               |
| `o`    | Bar open price                              |
| `h`    | High price                                  |
| `l`    | Low price                                   |
| `c`    | Bar close price                             |
| `v`    | Volume                                      |
| `T`    | Number of ticks                             |
| `t`    | Date/Time in milliseconds (*UTC time zone)* |

If an access token was expired during the streaming process, the `errmsg` will contain the ***Authorization error*** text.

## Unsubscribing from market data

The unsubscribing request stops streaming, its body must contain the following parameters:

**Body**

| Name        | Type    | Description                                                                                                      |
| ----------- | ------- | ---------------------------------------------------------------------------------------------------------------- |
| `event`     | string  | Should be always `unsubscribe` in this case.                                                                     |
| `requestId` | integer | Request identifier generated by the client side. Will be used in the response.                                   |
| `payload`   | object  | An object that contains information about the instrument from which the unsubscription is made, see table below. |

**Payload object**

| Parameter    | Value                                                                                                                                                                                                                                                                                                             |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tiId*`      | Tradable ID of the instrument.                                                                                                                                                                                                                                                                                    |
| `accountId`  | This ID is used for determining routes that are available for account. You can unsubscribe from the required routes only.                                                                                                                                                                                         |
| `st*`        | The subscription type is specified here. You can unsubscribe from the following types: `level1`***,*** `level2`***,*** `trades`***,*** `dailyBar`***,*** `candles`***.***                                                                                                                                         |
| `resolution` | This parameter specifies the aggregation type and should be used with the ***st = candles*** only. Available values are: `1m`***,*** `5m`***,*** `15m`***,*** `30m`***,*** `1H`***,*** `4H`***,*** `1D`***,*** `1W`***,*** `1M`***.*** So the unsubscription will be performed for the specified resolution only. |

**Request body example**

```json
{
	"event": "unsubscribe",
	"requestId": 321,
	"payload": {
		"tiId": 33549,
		"accountId": 124,
		"st": "candles",
		"resolution": "1m"
	}
}


```

**Response**

The server will return the following parameters in a response:

* `event` - always returns “unsubscribe”.
* `requestId` - id of the request to which the response was sent.
* `s` - unsubscription status: `ok` - if successful, or `error` - if the subscription failed.
* `errmsg` - returns an error message in case the unsubscription fails.

**Possible errors**

| errmsg text                                 | Error                                                                                                             |
| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `Unsupported event`                         | If an unsupported ***event*** is specified in the request, then the following error will be received.             |
| `Invalid subscription type`                 | If an unsupported ***subscription type*** is specified in the request, then the following error will be received. |
| `Required fields are missing: <parameters>` | This error means that some required fields are not specified, with their indication.                              |

**Unsubscribing from all market data for an account**

It is possible to unsubscribe from **all market data subscriptions** associated with a specific account by providing only the `accountId` in the `payload`, without specifying `tiId` and `st`.

**Request body example**

```json
{
  "event": "unsubscribe",
  "requestId": 555,
  "payload": {
    "accountId": 12345
  }
}
```

This request will cancel **all active market data subscriptions** for the specified account.
