Subscriptions
It is important for trading to have access to up-to-date exchange data without having to request it manually. For this purpose WebSocket API offers a mechanism of subscription to the interested data.
The system within the subscription returns messages containing updates for the tracked security and the data type in response to a single request. The subscription will be valid as long as the WebSocket connection is active, which makes it possible to receive up-to-date data during the whole trading session by a single request.
The following describes the main features of WebSocket subscriptions management.
Interfaces
Subscriptions management and exchange data retrieval from the ALOR Broker trading system uses the /ws
WebSocket interface. Full path to the interface will differ depending on the used system environment:
Address | Environment |
---|---|
wss://api.alor.ru/ws | Production environment. Requires a real trading account |
wss://apidev.alor.ru/ws | Test environment. Uses a test trading account |
The server accepts requests only via the WebSocket Secure (wss
) protocol due to the data security policy. An attempt to connect using the insecure WebSocket (ws
) protocol will be rejected by the server with a 406 Not Acceptable
response.
Creating a request
Regardless of the subscription type, the request you send to create it must always meet the following requirements:
- Executed by an authorized user
- Refers to a specific type of transaction
- Has a unique identifier to distinguish it from other requests
To fulfill these requirements, the message body for each supported request must contain the required token
, opcode
, and guid
parameters filled in.
The details of how these parameters should be applied are described below.
Authorization
All operations performed using WebSocket API require authorization to confirm the identity of API users and their rights to perform the requested actions. To confirm these rights, the Access Token of the API user passed to the server as the value of the token
parameter is used.
Unlike order management commands, the Access Token must be specified in every request sent to the /ws
interface whether creating a new subscription or canceling it.
To authorize a request, set Access Token as the value of the token
parameter in the message body.
Example of authorized request body
{
"opcode": "OrderBookGetAndSubscribe",
"code": "SBER",
"depth": 10,
"exchange": "MOEX",
"format": "Simple",
"frequency": 0,
"guid": "c328fcf1-e495-408a-a0ed-e20f95d6b813",
"token": "eyJhbGciOiJ..."
}
Where token
is Access Token provided for authorization purposes.
If authorization is successful, the server will respond with a single message with the code 200
confirming that the subscription has been created.
Example of a response body confirming the creation of a subscription
{
"message": "Handled successfully",
"httpCode": 200,
"requestGuid": "c328fcf1-e495-408a-a0ed-e20f95d6b813"
}
After that, the WebSocket connection in which the subscription was created will start getting messages with response code 100
containing the requested information.
Example of a response body containing requested data
{
"data": {
"snapshot": true,
"bids": [
{
"price": 257.70,
"volume": 157
}
],
"asks": [
{
"price": 257.71,
"volume": 288
}
],
"timestamp": 1702631123,
"ms_timestamp": 1702631123780,
"existing": true
},
"guid": "c328fcf1-e495-408a-a0ed-e20f95d6b813"
}
If authorization fails (For example, the provided Access Token is invalid), the server will return a response with the code 401
and immediately terminate the connection.
Example of a message body containing a subscription creation rejection
{
"requestGuid": "c328fcf1-e495-408a-a0ed-e20f95d6b813",
"httpCode": 401,
"message": "Invalid JWT token!"
}
- Request execution requires user authorization
- Each request must be authorized separately
- Authorization of requests can be done using Access Token as the value of the
token
parameter - The Access Token used must be valid for both the selected system environment and the moment the request is executed.
- Failed authorization attempt terminates the established WebSocket connection
Identification
Each WebSocket connection gives API user an opportunity to create multiple simultaneously active subscriptions, within which the server will return requested information. To identify messages sent and received as components of a single subscription, the guid
parameter is used, passed to the server in the request body and returned in all responses within the same subscription.
The guid
parameter should be assigned to the subscription by the API user, not by the server. Ensure that the software you are using provides a mechanism for generating such values.
As the value of the guid
parameter, the server accepts any custom string value unique to the established WebSocket connection. The following combinations of characters will be equal as a valid value:
- 123456
- abcdefABCDEF
- !@№;%:?*()-_=+/|"'
- c328fcf1-e495-408a-a0ed-e20f95d6b813
- Client-31075-Subscription-51-SBER-Quotes
So, depending on the task, the guid
can contain either a randomly generated or a personalized value.
When using wildcard characters as part of the identifier, make sure to preserve the integrity of the JSON object being sent. Symbols breaking the syntax should be excluded or escaped with the \
symbol. The escape character is not counted as part of the identifier, so, for example, the value /|\"
will be interpreted by the system as /|"
.
WebSocket connections are isolated from each other, so the same value of the guid
parameter can be used in multiple requests if they are created in different connections.
If the subscription creation request contains a guid
value that is non-unique for the WebSocket connection, the server will keep this connection active but replace the old subscription having this ID with a new one. This is one of the differences between the subscription management and the order management interfaces.
- A single WebSocket connection supports the ability to create multiple simultaneously active subscriptions
- Each request must contain filled in
guid
parameter - Response messages returned by the server within a subscription contain the same
guid
value that was passed to the server in the initial message - The
guid
parameter must be filled in by the API user - The value of the parameter can be random
- Wildcard characters breaking JSON object integrity must be escaped or excluded from the value of the parameter
- The parameter value must be unique for the WebSocket connection used. Only the value that has not been used in requests since the connection was established is considered unique
- The same value of the
guid
parameter can be used without any consequences in other WebSocket connections - Using a non-unique value when creating a new subscription replaces the previously created subscription
Operation code
При работе с HTTP API все действия пользователя определяются заданным в качестве пути URL ресурса и HTTP-глаголом, указывающим на метод взаимодействия (GET, PUT, POST, DELETE). В случае с WebSocket API метод взаимодействия определяется кодом операции, передаваемым в рамках WebSocket-соединения клиентском сообщении.
Как и в случае с HTTP-глаголами, коды операции строго определены и не допускают изменений в формулировке или написании. Разница заключается в том, что HTTP-глаголы определены общепринятым стандартом RFC 9110, тогда как для WebSocket API коды операций определяются выбранным создателями системы способом реализации метода.
Точное значение кода для каждой из операций представлено на странице описания соответствующего запроса.
To create a subscription to the selected security quotes, use the QuotesSubscribe
operation code. This code must be passed to the system as-is to successfully execute the request.
Such options as quotessubscribe
, QuoteSubscribe
, SubscribeQuotes
or Quotes:Subscribe
will be rejected by the system as unknown operations.
Creating a subscription
Data channel subscription can be made by sending to the established WebSocket-connection a message containing the actual access token (token
), code of the requested operation (opcode
), unique subscription identifier (guid
) and additional parameters defining the subscription details.
For example, this is what a request to create an order book subscription looks like:
{
"opcode": "OrderBookGetAndSubscribe",
"code": "SBER",
"depth": 10,
"exchange": "MOEX",
"format": "Simple",
"frequency": 0,
"guid": "c328fcf1-e495-408a-a0ed-e20f95d6b813",
"token": "eyJhbGciOiJ..."
}
Where:
opcode
is the code of requested operationcode
is the security code (ticker)depth
is the market depthexchange
is the exchange codeformat
is the response data representation formatfrequency
is the maximum frequency of server data output in millisecondsguid
is the unique identifier for the subscription being created. All messages returned in response by the server corresponding to this subscription will have this guid field value.token
is the Access Token to authorize the request
The value for the guid
field should be provided by the user. Ensure that the software you are using provides a mechanism for generating unique identifiers for the messages you send.
Canceling a subscription
To cancel a subscription to a data channel, send a message with the unsubscribe
operation code and the guid
value of the subscription to be canceled.
An example of a request body for canceling a subscription (Canceling a previously created order book subscription):
{
"opcode": "unsubscribe",
"token": "eyJhbGciOiJ...",
"guid": "c328fcf1-e495-408a-a0ed-e20f95d6b813"
}
WebSocket connections are isolated from each other, so the subscription must be canceled within the same connection where it was created.
Limitations and recommendations
When using the WebSocket API, keep in mind the following limitations and conditions on the data channel usage applied by the system.
Limitation | Recommendation |
---|---|
For some reasons, the server may break an established WebSocket connection without attempting to restore it | Ensure that the software you use has a mechanism to automatically reconnect when the connection is lost |
The server limits the number of simultaneously active subscriptions to several hundred thousand per user. If the limit is exceeded, the user will be temporarily (for a few minutes) restricted from creating new subscriptions. Subscriptions created earlier will remain in force. | Ensure that the software you use provides a mechanism to cancel subscriptions without interrupting the WebSocket connection |
The server limits the number of unprocessed messages in a single WebSocket connection to no more than 5000 records. If the limit is exceeded, the user will be temporarily (from a few minutes up to two hours) blocked from creating new subscriptions, and the trouble WebSocket connection will be terminated by the server with the message |
|
A large number of active WebSocket connections negatively affects system stability. Actions that harm the system may lead to temporary blocking of the user who committed such behavior | Limit the number of simultaneous connections to 10 by distributing valid interested data channel subscriptions among them. |