> 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-trading-data.md).

# Subscription to trading data

This page describes mechanism of receiving trading data via websocket

## Trade sessions <a href="#authorization-and-connection" id="authorization-and-connection"></a>

If there is a need to receive updates on trade session switching, you should use this websocket. It will inform you about every change in trading session periods, such as the end of the *main* period and the beginning of the *post close* period. All required instructions on the configuration of this connection can be found below.&#x20;

### Connection <a href="#authorization-and-connection" id="authorization-and-connection"></a>

In order to receive the *trade session switch* data, the connection should be opened to `wss://sandbox-api.traderevolution.com/traderevolution/v1/stream/tradeSessions`**.**&#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 session period switch

The request body must contain the following parameters:

**Body**

<table><thead><tr><th width="198">Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>event</code></td><td>string</td><td>Should be always <code>subscribe</code> in this case.</td></tr><tr><td><code>requestId</code></td><td>integer</td><td>Request identifier generated by the client side. Will be used in the response. </td></tr><tr><td><code>payload</code></td><td>object</td><td>An object that contains information about the session to which the subscription is made, see table below.</td></tr></tbody></table>

**Payload object**

| Parameter   | Value                                                                                                                                                                                                                |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sessionId` | Optional parameter that defines the ID of the session to which the user is going to subscribe. If this parameter is not specified, then the user will be subscribed to all sessions that are provided by the server. |
| `st*`       | The subscription type is specified here. The `sessionSwitch` value should be used in this case.                                                                                                                      |

**Request body example**

```json
{
	"event": "subscribe",
	"requestId": 123,
	"payload": {
		"sessionId": 22465,
		"st": "sessionSwitch"
	}
}
```

**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",
	"errmsg": "Error"
}
```

{% endtab %}
{% endtabs %}

As for the *subscribe* request, the optional `sessionId` parameter can also be specified in the payload. If not specified - the subscription will be done to all sessions, according to user settings.

In order to *unsubscribe* from updates, the message with the same structure as for subscription but with `"event": "unsubscribe"` should be sent in a WebSocket connection.

{% hint style="warning" %}
To unsubscribe from all events at once, omit `sessionId` in the `payload`. If `sessionId` is included, only subscriptions for that session will be canceled.
{% endhint %}

#### **Response structure for sessionSwitch subscription**

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

| Parameter   | Value                                                                            |
| ----------- | -------------------------------------------------------------------------------- |
| `d`         | Considered below in more details.                                                |
| `s`         | Subscription status indicator: `ok` or `error` in case the subscription fails.   |
| `errmsg`    | This parameter contains the text of the error which occurred when ***s=error***. |
| `st`        | Always returned as `sessionSwitch` here.                                         |
| `sessionId` | Identifier of this session.                                                      |

**Object d structure**

| Name                   | Description                                                                                        |
| ---------------------- | -------------------------------------------------------------------------------------------------- |
| `tradeSessionStatusId` | Identifier of the current trade session status.                                                    |
| `currentSession`       | Name of the current session.                                                                       |
| `tiId`                 | tradableId of the instrument. Will be specified only if switching is individual for an instrument. |

**Response example**

```json
{
	"s": "ok",
	"st": "sessionSwitch",
	"sessionId": 3843,
        "d": {
		"tradeSessionStatusId": 10609,
		"currentSession": “Main session”
	}
}
```

**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.                |
| `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. |

## Trade events

### Connection <a href="#authorization-and-connection" id="authorization-and-connection"></a>

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

### Subscribing to Trade events data

The request body must contain the following parameters:

**Body**

<table><thead><tr><th width="219">Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>event</code></td><td>string</td><td>Should be always <code>subscribe</code> in this case.</td></tr><tr><td><code>requestId</code></td><td>integer</td><td>Request identifier generated by the client side. Will be used in the response.</td></tr><tr><td><code>payload</code></td><td>object</td><td>An object that contains information about the session to which the subscription is made, see table below.</td></tr></tbody></table>

**Payload object**

| Parameter   | Value                                                                                                                                                                                          |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accountId` | Optional parameter that defines the ID of the account for which the subscription will be made. If this parameter is not specified, then you will be subscribed to the updates of all accounts. |
| `st*`       | The subscription type is specified here. All available values are listed below this table.                                                                                                     |

**Subscription types for trade events data**

* **orders** – this subscription is used for receiving updates on orders;
* **openPositions** and **closePositions** – subscription to the updates for any position events of the account;
* **executions** – this subscription allows receiving updates for all trade events of the account;
* **riskRules** – subscription to this stream provides information about risk rules related warnings;
* **marginWarning** – subscription to this stream provides information about margin warnings;
* **stopOut** – subscription to this stream provides information about stop-out events.

**Request body example**

```json
{
	"event": "subscribe",
	"requestId": 123,
	"payload": {
		"accountId": 13466,
		"st": "orders"
	}
}
```

A successful response to each type of subscription will be described below.

To stop receiving trade event updates, send an **unsubscribe** request with the same structure as the subscription request, but with `"event": "unsubscribe"`.

**Request body example**

```json
{
	"event": "unsubscribe",
	"requestId": 123,
	"payload": {
		"accountId": 13466,
		"st": "orders"
	}
}
```

{% hint style="warning" %}
To unsubscribe from **all trade events** associated with a specific account, omit the `st` parameter and specify only the `accountId`. If neither `accountId` nor `st` is specified, the unsubscription applies only to **non-account-specific subscriptions**.
{% endhint %}

### **Orders updates**

An object with the following parameters will be returned in the response for the subscription to the orders updates:

| Parameter   | Value                                                                            |
| ----------- | -------------------------------------------------------------------------------- |
| `d`         | Object with order arrays.                                                        |
| `s`         | Subscription status indicator: `ok` or `error` in case the subscription fails.   |
| `errmsg`    | This parameter contains the text of the error which occurred when ***s=error***. |
| `st`        | Always returned as `orders` here.                                                |
| `accountId` | Identifier of the account.                                                       |

**Response example**

```json
{
	"s": "ok"
	"st": "orders"
      "d": {
		"orders": [
			[
				"1273461", "241404", "1.1", "sell", "limit", "working", "1", "1.379", "1.37895", null, "IOC", null, "1686907919334", "1687869920000", "true", "642603", null, null, null, null
			]
		]
	}
}
```

Each orders array has the same sequence of parameters as in `OrdersResponse` model.

{% hint style="success" %}
You can find the detailed description of orders fields available by following the link to `OrdersResponse` model:\
<https://guide.traderevolution.com/traderevolution-api/traderevolution-apis/client-rest-api/account-management#active-orders-of-the-account>
{% endhint %}

### Positions updates

An object with the following parameters will be returned in the response for the subscription to the positions updates:

| Parameter   | Value                                                                            |
| ----------- | -------------------------------------------------------------------------------- |
| `d`         | Object with positions arrays.                                                    |
| `s`         | Subscription status indicator: `ok` or `error` in case the subscription fails.   |
| `errmsg`    | This parameter contains the text of the error which occurred when ***s=error***. |
| `st`        | Always returned as `orders` here.                                                |
| `accountId` | Identifier of the account.                                                       |

Each positions array has the same sequence of parameters as in `PositionsResponse` model.

{% hint style="success" %}
You can find the detailed description of positions fields available by following the link to `PositionsResponse` model:​\
<https://guide.traderevolution.com/traderevolution-api/traderevolution-apis/client-api/account-management#positions-of-the-account>
{% endhint %}

### Trades updates

An object with the following parameters will be returned in the response for the subscription to the trades updates:

| Parameter   | Value                                                                            |
| ----------- | -------------------------------------------------------------------------------- |
| `d`         | Object with execution array.                                                     |
| `s`         | Subscription status indicator: `ok` or `error` in case the subscription fails.   |
| `errmsg`    | This parameter contains the text of the error which occurred when ***s=error***. |
| `st`        | Type of the subscription.                                                        |
| `accountId` | Identifier of the account.                                                       |

**Response**&#x20;

```json
{
  {
    "id": "id"
  },
  {
    "id": "price"
  },
  {
    "id": "side"
  },
  {
    "id": "createdDate"
  },
  {
    "id": "qty"
  },
  {
    "id": "orderId"
  },
  {
    "id": "positionId"
  },
  {
    "id": "tradableInstrumentId"
  },
  {
    "id": "instrumentName"
  },
  {
    "id": "instrumentType"
  },
  {
    "id": "tradingExchange"
  },
  {
    "id": "pnl"
  }
}
```

Note that the WebSocket execution structure differs from the Client REST API. Therefore, execution data is delivered as executions objects, where each object includes the following fields: Trade ID, Price, Side, Created Date (Unix timestamp), Quantity, Order ID, Position ID, Tradable Instrument ID, Instrument Name, Instrument Type, Trading Exchange and PnL.

### Risk rule events

An object with the following parameters will be returned in the response for the subscription to the risk rules updates:

| Parameter   | Value                                                                                              |
| ----------- | -------------------------------------------------------------------------------------------------- |
| `d`         | Object that contains information about the triggered risk rule. The structure is considered below. |
| `s`         | Subscription status indicator: `ok` or `error` in case the subscription fails.                     |
| `errmsg`    | This parameter contains the text of the error which occurred when ***s=error***.                   |
| `st`        | Type of the subscription.                                                                          |
| `accountId` | Identifier of the account.                                                                         |

Object `d` contains:

* `riskRuleType` – identifier of the risk rule that was triggered, represented as a string name, for example, `MAX_POSITION_COUNT`.
* `comment` – text definition if any.

### Margin warning events

An object with the following parameters will be returned in the response for the subscription to the margin warnings:

| Parameter   | Value                                                                                               |
| ----------- | --------------------------------------------------------------------------------------------------- |
| `d`         | Object that contains information about the margin warning event. The structure is considered below. |
| `s`         | Subscription status indicator: `ok` or `error` in case the subscription fails.                      |
| `errmsg`    | This parameter contains the text of the error which occurred when ***s=error***.                    |
| `st`        | Type of the subscription.                                                                           |
| `accountId` | Identifier of the account.                                                                          |

Object `d` contains:

* `projectedBalance` – defines the Projected balance after the stop out.
* `marginUsed` – shows the used margin.
* `stopOutType` - shows the type of stop out.

### Stop out events

An object with the following parameters will be returned in the response for the subscription to the margin warnings:

| Parameter   | Value                                                                                         |
| ----------- | --------------------------------------------------------------------------------------------- |
| `d`         | Object that contains information about the stop out event. The structure is considered below. |
| `s`         | Subscription status indicator: `ok` or `error` in case the subscription fails.                |
| `errmsg`    | This parameter contains the text of the error which occurred when ***s=error***.              |
| `st`        | Type of the subscription.                                                                     |
| `accountId` | Identifier of the account.                                                                    |

Object `d` contains:

* `projectedBalance` – defines the Projected balance after the stop out.
* `marginUsed` – shows the used margin.
* `stopOutType` - shows the type of stop out.
