This is an unofficial Python wrapper for the Binance exchange API v1. I am in no way affiliated with Binance, use at your own risk.
- Implementation of General, Market Data and Account endpoints.
- Simple handling of authentication
- No need to generate timestamps yourself, the wrapper does it for you
- Response exception handling
- Websocket handling
- Order parameter validation based on Trade Rules
binance
is available on PYPI.
Install with pip
:
pip install python-binance
Firstly register with Binance.
If you want to use signed methods then create an API Key.
from binance.client import Client
client = Client(api_key, api_secret)
On an API call error a binance.exceptions.BinanceAPIException will be raised. The exception provides access to the - status_code - response status code - response - response object - code - Binance error code - message - Binance error message - request - request object if available
When placing an order parameters are validated to check they fit within the Binance Trading Rules.
The following exceptions extend BinanceOrderException.
BinanceOrderMinAmountException
Raised if the specified amount isn't a multiple of the trade minimum amount.
BinanceOrderMinPriceException
Raised if the price is lower than the trade minimum price.
BinanceOrderTotalPriceException
Raised if the total is lower than the trade minimum total.
Every method supports the passing of arbitrary parameters via keyword. These keyword arguments will be sent directly to the relevant endpoint.
Each API method returns a dictionary of the JSON response as per the Binance API documentation. The docstring of each method in the code references the endpoint it implements.
Some methods require a timestamp parameter, this is generated for you where required.
Some methods have a recvWindow parameter for timing security, see Binance documentation.
API Endpoints are rate limited by Binance at 20 requests per second.
Binance has a number of rules around symbol pair orders with validation on minimum price, quantity and total order value.
These rules are fetched when the client is initialised.
The rules can be refreshed by calling the get_products API endpoint.
We can then validate if pairs are being actively traded on Binance as well.
Binance defines Enumerated Types for Order Types, Order Side, Time in Force and Kline intervals.
SYMBOL_TYPE_SPOT = 'SPOT'
ORDER_STATUS_NEW = 'NEW'
ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED'
ORDER_STATUS_FILLED = 'FILLED'
ORDER_STATUS_CANCELED = 'CANCELED'
ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL'
ORDER_STATUS_REJECTED = 'REJECTED'
ORDER_STATUS_EXPIRED = 'EXPIRED'
KLINE_INTERVAL_1MINUTE = '1m'
KLINE_INTERVAL_2MINUTE = '3m'
KLINE_INTERVAL_5MINUTE = '5m'
KLINE_INTERVAL_15MINUTE = '15m'
KLINE_INTERVAL_30MINUTE = '30m'
KLINE_INTERVAL_1HOUR = '1h'
KLINE_INTERVAL_2HOUR = '2h'
KLINE_INTERVAL_4HOUR = '4h'
KLINE_INTERVAL_6HOUR = '6h'
KLINE_INTERVAL_8HOUR = '8h'
KLINE_INTERVAL_12HOUR = '12h'
KLINE_INTERVAL_1DAY = '1d'
KLINE_INTERVAL_3DAY = '3d'
KLINE_INTERVAL_1WEEK = '1w'
KLINE_INTERVAL_1MONTH = '1M'
SIDE_BUY = 'BUY'
SIDE_SELL = 'SELL'
ORDER_TYPE_LIMIT = 'LIMIT'
ORDER_TYPE_MARKET = 'MARKET'
TIME_IN_FORCE_GTC = 'GTC'
TIME_IN_FORCE_IOC = 'IOC'
Get the server time
time_res = client.get_server_time()
Fetch all orders
orders = client.get_all_orders(symbol='BNBBTC', limit=10)
Create an order
from binance.enums import *
order = client.create_order(
symbol='BNBBTC',
side=SIDE_BUY,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=100,
price='0.00001')
Using Enumerated types
from binance.enums import *
candles = client.get_klines(symbol='BNBBTC', interval=KLINE_INTERVAL_30MINUTE)
Error Handling
try:
client.get_all_orders()
except BinanceAPIException as e:
print e.status_code
print e.message
Sockets are handled through a Socket Manager BinanceSocketManager. Multiple socket connections can be made through the 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.
Socket connections pass a callback function to receive messages. Messages are received are dictionary objects relating to the message formats defined in the Binance API documentation.
Create the manager like so, passing the api client.
bm = BinanceSocketManager(client)
# attach any sockets here then start
bm.start()
A callback to process messages would take the format
def process_message(msg):
print("message type:" + msg[e])
print(msg)
# do something
Depth Socket
bm.start_depth_socket('BNBBTC', process_message)
Kline Socket
bm.start_kline_socket('BNBBTC', process_message)
Aggregated Trade Socket
bm.start_trade_socket('BNBBTC', process_message)
Ticker Socket
bm.start_ticker_socket(process_message)
User Socket
This watches for 3 different events
- Account Update Event
- Order Update Event
- Trade Update Event
The Manager handles keeping the socket alive.
bm.start_user_socket(process_message)
Close Socket
To close an individual socket call the corresponding close function
- stop_depth_socket
- stop_kline_socket
- stop_trade_socket
- stop_ticker_socket
- stop_user_socket
To stop all sockets and end the manager call close after doing this a start call would be required to connect any new sockets.
bm.close()
- Tests
If this library helped you out feel free to donate.
- ETH: 0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70
- NEO: AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBo
- BTC: 1Dknp6L6oRZrHDECRedihPzx2sSfmvEBys
Changes
- Updated documentation
Fixes
- Small bugfix
Added
- Travis.CI and Coveralls support
Changes
- Validation for pairs using public endpoint
Added
- Validation for HSR/BTC pair
Websocket release
Added
- Websocket manager
- Order parameter validation
- Order and Symbol enums
- API Endpoints for Data Streams
Initial version
Added
- General, Market Data and Account endpoints