• Stars
    star
    762
  • Rank 59,625 (Top 2 %)
  • Language
    Python
  • License
    MIT License
  • Created about 3 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Binance Futures Public API Connector Python

Python version License: MIT

This is a lightweight library that works as a connector to Binance Futures public API

  • Supported APIs:
    • USDT-M Futures /fapi/*
    • COIN-M Delivery /dapi/*
    • Futures/Delivery Websocket Market Stream
    • Futures/Delivery User Data Stream
  • Inclusion of examples
  • Customizable base URL, request timeout
  • Response metadata can be displayed

Installation

pip install binance-futures-connector

RESTful APIs

Usage examples:

from binance.cm_futures import CMFutures

cm_futures_client = CMFutures()

# get server time
print(cm_futures_client.time())

cm_futures_client = CMFutures(key='<api_key>', secret='<api_secret>')

# Get account information
print(cm_futures_client.account())

# Post a new order
params = {
    'symbol': 'BTCUSDT',
    'side': 'SELL',
    'type': 'LIMIT',
    'timeInForce': 'GTC',
    'quantity': 0.002,
    'price': 59808
}

response = cm_futures_client.new_order(**params)
print(response)

Please find examples folder to check for more endpoints.

Authentication

Binance supports HMAC and RSA API authentication.

# HMAC Authentication
client = Client(api_key, api_secret)
print(client.account())

# RSA Authentication
key = ""
with open("/Users/john/private_key.pem", "r") as f: # Location of private key file
    private_key = f.read()
private_key_passphrase = "" # Optional: only used for encrypted RSA key

client = Client(key=key, private_key=private_key, private_key_passphrase=private_key_passphrase)
print(client.account())

Please see examples/um_futures/trade/get_account.py or examples/cm_futures/trade/get_account.py for more details.

Base URL

For USDT-M Futures, if base_url is not provided, it defaults to fapi.binance.com.
For COIN-M Delivery, if base_url is not provided, it defaults to dapi.binance.com.
It's recommended to pass in the base_url parameter, even in production as Binance provides alternative URLs

Optional parameters

PEP8 suggests lowercase with words separated by underscores, but for this connector, the methods' optional parameters should follow their exact naming as in the API documentation.

# Recognised parameter name
response = client.query_order('BTCUSDT', orderListId=1)

# Unrecognised parameter name
response = client.query_order('BTCUSDT', order_list_id=1)

RecvWindow parameter

Additional parameter recvWindow is available for endpoints requiring signature.
It defaults to 5000 (milliseconds) and can be any value lower than 60000(milliseconds). Anything beyond the limit will result in an error response from Binance server.

from binance.cm_futures import CMFutures

cm_futures_client = CMFutures(key='<api_key>', secret='<api_secret>')
response = cm_futures_client.query_order('BTCUSDT', orderId=11, recvWindow=10000)

Timeout

timeout is available to be assigned with the number of seconds you find most appropriate to wait for a server response.
Please remember the value as it won't be shown in error message no bytes have been received on the underlying socket for timeout seconds.
By default, timeout is None. Hence, requests do not time out.

from binance.cm_futures import CMFutures

client= CMFutures(timeout=1)

Proxy

proxy is supported

from binance.cm_futures import CMFutures

proxies = { 'https': 'http://1.2.3.4:8080' }

client= CMFutures(proxies=proxies)

Response Metadata

The Binance API server provides weight usages in the headers of each response. You can display them by initializing the client with show_limit_usage=True:

from binance.cm_futures import CMFutures

client = CMFutures(show_limit_usage=True)
print(client.time())

returns:

{'limit_usage': {'x-mbx-used-weight-1m': '1'}, 'data': {'serverTime': 1653563092778}}

You can also display full response metadata to help in debugging:

client = Client(show_header=True)
print(client.time())

returns:

{'data': {'serverTime': 1587990847650}, 'header': {'Context-Type': 'application/json;charset=utf-8', ...}}

If ClientError is received, it'll display full response meta information.

Display logs

Setting the log level to DEBUG will log the request URL, payload and response text.

Error

There are 2 types of error returned from the library:

  • binance.error.ClientError
    • This is thrown when server returns 4XX, it's an issue from client side.
    • It has 4 properties:
      • status_code - HTTP status code
      • error_code - Server's error code, e.g. -1102
      • error_message - Server's error message, e.g. Unknown order sent.
      • header - Full response header.
  • binance.error.ServerError
    • This is thrown when server returns 5XX, it's an issue from server side.

Websocket

Connector v4

WebSocket can be established through the following connections:

  • USD-M WebSocket Stream (https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams)
  • COIN-M WebSocket Stream (https://binance-docs.github.io/apidocs/delivery/en/#websocket-market-streams)
# WebSocket Stream Client
import time
from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient

def message_handler(_, message):
    logging.info(message)

my_client = UMFuturesWebsocketClient(on_message=message_handler)

# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()

Request Id

Client can assign a request id to each request. The request id will be returned in the response message. Not mandatory in the library, it generates a uuid format string if not provided.

# id provided by client
my_client.agg_trade(symbol="bnbusdt", id="my_request_id")

# library will generate a random uuid string
my_client.agg_trade(symbol="bnbusdt")

Combined Streams

  • If you set is_combined to True, "/stream/" will be appended to the baseURL to allow for Combining streams.
  • is_combined defaults to False and "/ws/" (raw streams) will be appended to the baseURL.

More websocket examples are available in the examples folder

Websocket < v4

import time
from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient

def message_handler(message):
    print(message)

my_client = UMFuturesWebsocketClient(on_message=message_handler)

# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
print("closing ws connection")
my_client.stop()

Heartbeat

Once connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within a 10 minutes period. This package handles the pong responses automatically.

License

MIT

More Repositories

1

binance-spot-api-docs

Official Documentation for the Binance Spot APIs and Streams
3,842
star
2

binance-connector-python

Simple connector to Binance Public API
Python
1,848
star
3

binance-public-data

Details on how to get Binance public data
Python
1,430
star
4

binance-api-postman

Postman collection for Binance Public API, including spot, margin, futures, etc.
1,307
star
5

binance-connector-node

A simple connector to Binance Public API
JavaScript
543
star
6

binance-connector-java

Java
375
star
7

binance-signature-examples

Examples of generating HMAC and RSA signature for Binance API
Python
238
star
8

binance-connector-dotnet

Lightweight connector for integration with Binance API
C#
204
star
9

binance-websocket-examples

Example code in Nodejs that demonstrate how to subscribe to Binance Websocket server.
JavaScript
151
star
10

binance-connector-go

Go
147
star
11

binance-api-swagger

Swagger for the Binance Public API
HTML
124
star
12

binance-futures-connector-java

Java
116
star
13

zkmerkle-proof-of-solvency

This is proof of solvency tool for Centralized exchanges built by Binance. Please raise bugs and security issues to https://bugcrowd.com/binance
Go
113
star
14

binance-spot-connector-rust

Rust
111
star
15

binance-toolbox-python

Some useful scripts that help users to validate
Python
95
star
16

asymmetric-key-generator

This simple tool can be used to generate an RSA PKCS#8 or Ed25519 key pairs.
JavaScript
75
star
17

binance-connector-php

This is a thin library that working as a connector to the Binance public API.
PHP
65
star
18

desktop

Binance desktop application release channel.
55
star
19

ai-trading-prototype

Free open source crypto AI trading bot prototype.
Python
50
star
20

binance-connector-typescript

TypeScript
47
star
21

binance-connector-ruby

a simple connector to Binance Public API
Ruby
34
star
22

websocket-demo

a live demo site for subscribing to websocket server
JavaScript
22
star
23

ai-trading-prototype-backtester

Headline Sentiment Analysis Backtester. Backtests trading strategy from ai-trading-prototype trading bot.
Python
21
star
24

binance-cli

JavaScript
20
star
25

ai-trading-prototype-headlines

News Headlines Fetcher. Outputs headlines intended for use with the ai-trading-prototype sentiment-based trading bot.
Python
17
star
26

binance-pay-signature-examples

Python
14
star
27

binance-pay-connector-python

A lightweight library that works as a connector to Binance pay public API
Python
14
star
28

binance-sbe-rust-sample-app

Rust
12
star
29

binance-pay-postman-collection

Postman collection for Binance Pay API
11
star
30

binance-toolbox-java

Java
10
star
31

binance-futures-connector-node

JavaScript
9
star
32

binance-mp-demo

JavaScript
9
star
33

binance-toolbox-go

Go
8
star
34

binance-toolbox-php

PHP
6
star
35

binance-sbe-java-sample-app

Sample app that decodes Binance "exchangeInfo" endpoint's SBE response to YAML.
Java
5
star
36

binance-sbe-cpp-sample-app

C++
4
star
37

binance-toolbox-ruby

Ruby
2
star
38

binance-toolbox-nodejs

JavaScript
1
star
39

binance-toolbox-typescript

TypeScript
1
star
40

binance-futures-java-toolbox

Java
1
star