Binance futures websocket api

WebsocketsВ¶

There are 2 ways to interact with websockets.

ThreadedWebsocketManager does not require asyncio programming, while BinanceSocketManager does.

ThreadedWebsocketManager function begin with start_ , e.g start_ticker_socket while BinanceSocketManager is simple ticker_socket

Multiple socket connections can be made through either manager.

Only one instance of each socket type will be created, i.e. only one BNBBTC Depth socket can be created and there can be both a BNBBTC Depth and a BNBBTC Trade socket open at once.

Messages are received as dictionary objects relating to the message formats defined in the Binance WebSocket API documentation.

Websockets are setup to reconnect with a maximum of 5 retries with an exponential backoff strategy.

ThreadedWebsocketManager Websocket UsageВ¶

Starting sockets on the ThreadedWebsocketManager requires a callback parameter, similar to old implementations of websockets on python-binance

ThreadedWebsocketManager takes similar parameters to the Client class as it creates an AsyncClient internally.

For authenticated streams api_key and api_stream are required.

As these use threads start() is required to be called before starting any sockets.

To keep the ThreadedWebsocketManager running using join() to join it to the main thread.

Stop Individual Stream

When starting a stream, a name for that stream will be returned. This can be used to stop that individual stream

Stop All Streams

Attempting to start a stream after stop is called will not work.

BinanceSocketManager Websocket UsageВ¶

Create the manager like so, passing an AsyncClient.

Set a custom timeout for the websocket connections

Manually enter and exit the Asynchronous context manager

Using a different TLDВ¶

The ThreadedWebsocketManager can take the tld when created if required.

The BinanceSocketManager uses the same tld value as the AsyncClient that is passed in. To use the ‘us’ tld we can do this.

Websocket ErrorsВ¶

If the websocket is disconnected and is unable to reconnect a message is sent to the callback to indicate this. The format is

Multiplex SocketВ¶

Create a socket combining multiple streams.

These streams can include the depth, kline, ticker and trade streams but not the user stream which requires extra authentication.

Symbols in socket name must be lowercase i.e bnbbtc @ aggTrade, neobtc @ ticker

Depth SocketВ¶

Depth sockets have an optional depth parameter to receive partial book rather than a diff response. By default this the diff response is returned. Valid depth values are 5, 10 and 20 and defined as enums.

Kline SocketВ¶

Kline sockets have an optional interval parameter. By default this is set to 1 minute. Valid interval values are defined as enums.

Читайте также:  Zetacoin майнить или нет

Источник

Binance futures websocket api

No definitions found in this file.

  • Go to file T
  • Go to line L
  • Go to definition R
  • Copy path
  • Copy permalink

1 contributor

Users who have contributed to this file

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# File: example_binance_futures.py
#
# Part of ‘UNICORN Binance WebSocket API’
# Project website: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api
# Documentation: https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api
# PyPI: https://pypi.org/project/unicorn-binance-websocket-api/
#
# Author: Oliver Zehentleitner
# https://about.me/oliver-zehentleitner
#
# Copyright (c) 2019-2021, Oliver Zehentleitner
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# «Software»), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from unicorn_binance_websocket_api . unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager
import logging
import time
import threading
import os
# https://docs.python.org/3/library/logging.html#logging-levels
logging . basicConfig ( level = logging . DEBUG ,
filename = os . path . basename ( __file__ ) + ‘.log’ ,
format = » [] : » ,
style = » <" )
def print_stream_data_from_stream_buffer ( binance_websocket_api_manager ):
while True :
if binance_websocket_api_manager . is_manager_stopping ():
exit ( 0 )
oldest_stream_data_from_stream_buffer = binance_websocket_api_manager . pop_stream_data_from_stream_buffer ()
if oldest_stream_data_from_stream_buffer is False :
time . sleep ( 0.01 )
# create instance of BinanceWebSocketApiManager for Binance.com Futures
binance_websocket_api_manager = BinanceWebSocketApiManager ( exchange = «binance.com-futures» )
# set api key and secret for userData stream
binance_je_api_key = «»
binance_je_api_secret = «»
userdata_stream_id = binance_websocket_api_manager . create_stream ([ «arr» ],
[ «!userData» ],
api_key = binance_je_api_key ,
api_secret = binance_je_api_secret )
bookticker_all_stream_id = binance_websocket_api_manager . create_stream ([ «arr» ], [ «!bookTicker» ])
# https://binance-docs.github.io/apidocs/futures/en/#mark-price-stream-for-all-market
binance_websocket_api_manager . create_stream ([ «!markPrice» ], «arr@1s» , stream_label = «!markPrice@arr@1s» )
markets =
binance_websocket_api_manager . create_stream ([ «aggTrade» ], markets )
binance_websocket_api_manager . create_stream ([ «markPrice» ], markets )
binance_websocket_api_manager . create_stream ([ «kline_1m» ], markets )
binance_websocket_api_manager . create_stream ([ «kline_5m» ], markets )
binance_websocket_api_manager . create_stream ([ «kline_15m» ], markets )
binance_websocket_api_manager . create_stream ([ «kline_1h» ], markets )
binance_websocket_api_manager . create_stream ([ «kline_12h» ], markets )
binance_websocket_api_manager . create_stream ([ «kline_1w» ], markets )
binance_websocket_api_manager . create_stream ([ «ticker» ], markets )
binance_websocket_api_manager . create_stream ([ «miniTicker» ], markets )
binance_websocket_api_manager . create_stream ([ «bookTicker» ], markets )
binance_websocket_api_manager . create_stream ([ «depth» ], markets )
binance_websocket_api_manager . create_stream ([ «depth@2500ms» ], markets )
binance_websocket_api_manager . create_stream ([ «depth5» ], markets )
binance_websocket_api_manager . create_stream ([ «depth5@100ms» ], markets )
binance_websocket_api_manager . create_stream ([ «depth10» ], markets )
binance_websocket_api_manager . create_stream ([ «depth20» ], markets )
binance_websocket_api_manager . create_stream ([ «compositeIndex» ], markets , stream_label = «compositeIndex» )
channels = < 'aggTrade' , 'markPrice' 'kline_1m' , 'kline_5m' , 'kline_15m' , 'kline_30m' , 'kline_1h' , 'kline_12h' ,
‘miniTicker’ , ‘depth20@100ms’ , ‘bookTicker’ , ‘forceOrder’ , ‘!forceOrder’ , ‘kline_1w@250ms’ ,
‘compositeIndex’ >
binance_websocket_api_manager . create_stream ( channels , markets )
# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading . Thread ( target = print_stream_data_from_stream_buffer , args = ( binance_websocket_api_manager ,))
worker_thread . start ()
# show an overview
while True :
binance_websocket_api_manager . print_summary ()
time . sleep ( 1 )

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Binance futures websocket api

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

Источник

Читайте также:  Как долго можно майнить эфир
Оцените статью