Binance websocket api php
Table of Contents generated with DocToc
Web Socket Streams for Binance (2019-11-13)
General WSS information
- The base endpoint is: wss://stream.binance.com:9443
- Streams can be accessed either in a single raw stream or in a combined stream
- Raw streams are accessed at /ws/
- Combined streams are accessed at /stream?streams= / /
- Combined stream events are wrapped as follows:
- All symbols for streams are lowercase
- A single connection to stream.binance.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark
- The websocket server will send a ping frame every 3 minutes. If the websocket server does not receive a pong frame back from the connection within a 10 minute period, the connection will be disconnected. Unsolicited pong frames are allowed.
- WebSocket connections have a limit of 5 incoming messages per second. A message is considered:
- A PING frame
- A PONG frame
- A JSON controlled message (e.g. subscribe, unsubscribe)
- A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned.
- A single connection can listen to a maximum of 1024 streams.
Live Subscribing/Unsubscribing to streams
- The following data can be sent through the websocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below.
- The id used in the JSON payloads is an unsigned INT used as an identifier to uniquely identify the messages going back and forth.
- In the response, if the result received is null this means the request sent was a success for non-query requests (e.g. Subscribing/Unsubscribing).
Subscribe to a stream
Unsubscribe to a stream
Currently, the only property that can be set is whether combined stream payloads are enabled or not. The combined property is set to false when connecting using /ws/ («raw streams») and true when connecting using /stream/ .
Error Message | Description |
---|---|
Parameter used in the SET_PROPERTY or GET_PROPERTY was invalid | |
Value should only be true or false | |
Property name provided was invalid | |
Parameter id had to be provided or the value provided in the id parameter is an unsupported type | |
Possible typo in the provided method or provided method was neither of the expected values | |
Unnecessary parameters provided in the data | |
Property name was not provided | |
method was not provided in the data | |
JSON data sent has incorrect syntax. |
Detailed Stream information
Aggregate Trade Streams
The Aggregate Trade Streams push trade information that is aggregated for a single taker order.
Stream Name: @aggTrade
Update Speed: Real-time
Payload:
The Trade Streams push raw trade information; each trade has a unique buyer and seller.
Stream Name: @trade
Update Speed: Real-time
Payload:
The Kline/Candlestick Stream push updates to the current klines/candlestick every second.
Kline/Candlestick chart intervals:
m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
Stream Name: @kline_
Update Speed: 2000ms
Payload:
Individual Symbol Mini Ticker Stream
24hr rolling window mini-ticker statistics. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
Stream Name: @miniTicker
Update Speed: 1000ms
Payload:
All Market Mini Tickers Stream
24hr rolling window mini-ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array.
Stream Name: !miniTicker@arr
Update Speed: 1000ms
Payload:
Individual Symbol Ticker Streams
24hr rolling window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
Stream Name: @ticker
Update Speed: 1000ms
Payload:
All Market Tickers Stream
24hr rolling window ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array.
Stream Name: !ticker@arr
Update Speed: 1000ms
Payload:
Individual Symbol Book Ticker Streams
Pushes any update to the best bid or ask’s price or quantity in real-time for a specified symbol.
Stream Name: @bookTicker
Update Speed: Real-time
Payload:
All Book Tickers Stream
Pushes any update to the best bid or ask’s price or quantity in real-time for all symbols.
Stream Name: !bookTicker
Update Speed: Real-time
Payload:
Partial Book Depth Streams
Top bids and asks, pushed every second. Valid are 5, 10, or 20.
Stream Names: @depth OR @depth @100ms
Update Speed: 1000ms or 100ms
Payload:
Diff. Depth Stream
Order book price and quantity depth updates used to locally manage an order book.
Stream Name: @depth OR @depth@100ms
Update Speed: 1000ms or 100ms
Payload:
How to manage a local order book correctly
Источник
Binance websocket api php
Table of Contents generated with DocToc
Web Socket Streams for Binance (2019-11-13)
General WSS information
- The base endpoint is: wss://stream.binance.us:9443
- Streams can be accessed either in a single raw stream or in a combined stream
- Raw streams are accessed at /ws/
- Combined streams are accessed at /stream?streams= / /
- Combined stream events are wrapped as follows:
- All symbols for streams are lowercase
- A single connection to stream.binance.us is only valid for 24 hours; expect to be disconnected at the 24 hour mark
- The websocket server will send a ping frame every 3 minutes. If the websocket server does not receive a pong frame back from the connection within a 10 minute period, the connection will be disconnected. Unsolicited pong frames are allowed.
- WebSocket connections have a limit of 5 incoming messages per second. A message is considered:
- A PING frame
- A PONG frame
- A JSON controlled message (e.g. subscribe, unsubscribe)
- A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned.
- A single connection can listen to a maximum of 1024 streams.
Live Subscribing/Unsubscribing to streams
- The following data can be sent through the websocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below.
- The id used in the JSON payloads is an unsigned INT used as an identifier to uniquely identify the messages going back and forth.
- In the response, if the result received is null this means the request sent was a success for non-query requests (e.g. Subscribing/Unsubscribing).
Subscribe to a stream
Unsubscribe to a stream
Currently, the only property can be set is to set whether combined stream payloads are enabled or not. The combined property is set to false when connecting using /ws/ («raw streams») and true when connecting using /stream/ .
Error Message | Description |
---|---|
Parameter used in the SET_PROPERTY or GET_PROPERTY was invalid | |
Value should only be true or false | |
Property name provided was invalid | |
Parameter id had to be provided or the value provided in the id parameter is an unsupported type | |
Possible typo in the provided method or provided method was neither of the expected values | |
Unnecessary parameters provided in the data | |
Property name was not provided | |
method was not provided in the data | |
JSON data sent has incorrect syntax. |
Detailed Stream information
Aggregate Trade Streams
The Aggregate Trade Streams push trade information that is aggregated for a single taker order.
Stream Name: @aggTrade
Update Speed: Real-time
Payload:
The Trade Streams push raw trade information; each trade has a unique buyer and seller.
Stream Name: @trade
Update Speed: Real-time
Payload:
The Kline/Candlestick Stream push updates to the current klines/candlestick every second.
Kline/Candlestick chart intervals:
m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
Stream Name: @kline_
Update Speed: 2000ms
Payload:
Individual Symbol Mini Ticker Stream
24hr rolling window mini-ticker statistics. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
Stream Name: @miniTicker
Update Speed: 1000ms
Payload:
All Market Mini Tickers Stream
24hr rolling window mini-ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array.
Stream Name: !miniTicker@arr
Update Speed: 1000ms
Payload:
Individual Symbol Ticker Streams
24hr rolling window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
Stream Name: @ticker
Update Speed: 1000ms
Payload:
All Market Tickers Stream
24hr rolling window ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array.
Stream Name: !ticker@arr
Update Speed: 1000ms
Payload:
Individual Symbol Book Ticker Streams
Pushes any update to the best bid or ask’s price or quantity in real-time for a specified symbol.
Stream Name: @bookTicker
Update Speed: Real-time
Payload:
All Book Tickers Stream
Pushes any update to the best bid or ask’s price or quantity in real-time for all symbols.
Stream Name: !bookTicker
Update Speed: Real-time
Payload:
Partial Book Depth Streams
Top bids and asks, pushed every second. Valid are 5, 10, or 20.
Stream Names: @depth OR @depth @100ms
Update Speed: 1000ms or 100ms
Payload:
Diff. Depth Stream
Order book price and quantity depth updates used to locally manage an order book.
Stream Name: @depth OR @depth@100ms
Update Speed: 1000ms or 100ms
Payload:
How to manage a local order book correctly
Источник
Как использовать Websocket на примере простого Express API?
Краткое описание технологии
Websocket — это протокол связи поверх TCP-соединения, предназначенный для обмена сообщениями между браузером и веб-сервером в режиме реального времени.
Для установления соединения WebSocket клиент и сервер используют протокол, похожий на HTTP. Клиент формирует особый HTTP-запрос, на который сервер отвечает определенным образом.
Несмотря на «похожесть» новых запросов и ответов на запросы и ответы протокола HTTP, они таковыми не являются. Например, в запросе есть тело, но в заголовках поле «Content-Length» отсутствует (что нарушает соглашения HTTP). Подробнее об этом можно прочитать в Википедии.
Одним из главных преимуществ технологии — это ее простота. На клиенте и сервере есть всего 4 события для обработки:
Почему Websocket?
Кроме ws существуют еще два способа непрерывной передачи данных: Server-Sent Events (SSE) и Long Polling.
Приведем сравнения механизмов непрерывной связи сервера и клиента, а также сделаем выводы, почему стоит (или не стоит) использовать вебсокет.
Websocket | sse | long pooling | |
---|---|---|---|
протокол | websocket (ws, или wss) | HTTP(S) | HTTP(S) |
скорость | высокая | низкая | низкая |
направленность потоков данных | двунаправленная | однонаправленная | двунаправленная |
дополнительно | передача бинарных данных, отсутствует поддержка некоторых старых браузеров | автоматическое переподключение при обрыве соединения |
Одним из главных преимуществ технологии ws — это скорость передачи данных. SSE и LP используют протокол HTTP(S) и работают примерно так:
- Делаем запрос на изменения;
- Если изменения на сервере появились, то сервер их отправляет;
- Когда клиент получает изменения, клиент делает новый запрос.
Выводы:
- Вебсокет не требует от клиента постоянно запрашивать изменения и именно поэтому он быстрее.
- Вебсокет позволяет передавать бинарные данные, что не позволяет протокол HTTP(S).
- Вебсокет не нужно использовать, если проект требует совместимость со старыми версиями браузеров. Читать о совместимости с браузерами
Пример работы простейшего api.
Что здесь происходит?
Чтобы создать сервер поддерживающий ws, мы создаем обычный http сервер, а потом привязываем к нему при создании websocket сервер.
Функция “on” помогает управлять событиями websocket. Самым примечательным является событие message, так что рассмотрим его подробнее.
Здесь функция получает параметр m — сообщение, то есть то, что отправил пользователь. Таким образом мы можем отправить с клиента строку и обработать ее на сервере. В данном случае сервер просто пересылает это сообщение всем, кто подключен к серверу websocket. Массив clients объекта webSocketServer содержит все подключения к серверу. Объект ws в то же время хранит данные только об одном подключении.
Не стоит использовать такой подход в реальном приложении. Если описать api таким образом, то сервер не может отличить один запрос от другого. О том, как можно построить api на основе websocket будет написано далее.
Взаимодействие с сервером на клиенте будет выглядеть так:
API на основе Websocket
В отличие от REST API, где запросы распределены по разным url, Websocket API имеет только один url. Для того, чтобы построить полноценное API на основе вебсокетов, необходимо научить систему отличать один запрос от другого. Это можно реализовать следующим образом:
1) С клиента мы будем передавать запросы в виде строки-json, которую распарсим на сервере:
2) На сервере мы распарсим строку и выделем в ней поле event — тип запроса. Пропишем для каждого типа соответствующий ответ:
Таким образом мы можем отправлять разные запросы на сервер и обрабатывать ответ в зависимости от запроса.
Источник