Python Binance PDF
Python Binance PDF
Release 0.2.0
Sam McHardy
1 Features 3
2 Quick Start 5
3 Donate 7
4 Other Exchanges 9
4.1 Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.2 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
i
ii
python-binance Documentation, Release 0.2.0
This is an unofficial Python wrapper for the Binance exchange REST API v1/3. I am in no way affiliated with Binance,
use at your own risk.
If you came here looking for the Binance exchange to purchase cryptocurrencies, then go here. If you want to automate
interactions with Binance stick around.
Source code https://github.com/sammchardy/python-binance
Documentation https://python-binance.readthedocs.io/en/latest/
Binance API Telegram https://t.me/binance_api_english
Blog with examples https://sammchardy.github.io
Make sure you update often and check the Changelog for new features and bug fixes.
Contents 1
python-binance Documentation, Release 0.2.0
2 Contents
CHAPTER 1
Features
3
python-binance Documentation, Release 0.2.0
4 Chapter 1. Features
CHAPTER 2
Quick Start
# place a test market buy order, to place an actual order use the create_order
˓→function
order = client.create_test_order(
symbol='BNBBTC',
side=Client.SIDE_BUY,
type=Client.ORDER_TYPE_MARKET,
quantity=100)
5
python-binance Documentation, Release 0.2.0
else:
print("Success")
Donate
7
python-binance Documentation, Release 0.2.0
8 Chapter 3. Donate
CHAPTER 4
Other Exchanges
4.1 Contents
Installation
Windows
If you see errors building Twisted indication Microsoft Visual C++ is required you may need to install the Visual C++
Build Tools refer to the Python Wiki on Widows Compilers for your relevant version.
Register on Binance
To use signed account methods you are required to create an API Key.
9
python-binance Documentation, Release 0.2.0
Every method supports the passing of arbitrary parameters via keyword matching those in the‘Binance API doc-
umentation <https://github.com/binance-exchange/binance-official-api-docs>‘_. 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.
The Binance API documentation references 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, ask them if you require more.
Requests Settings
You may also pass custom requests parameters through any API call to override default settings or the above set-
tingsspecify new ones like the example below.
# this would result in verify: False and timeout: 5 for the get_all_orders call
client = Client("api-key", "api-secret", {"verify": False, "timeout": 20})
client.get_all_orders(symbol='BNBBTC', requests_params={'timeout': 5})
# or on an individual call
client.get_all_orders(symbol='BNBBTC', requests_params={'proxies': proxies})
Or set an environment variable for your proxy if required to work across all requests.
An example for Linux environments from the requests Proxies documentation is as follows.
$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"
Binance requires specific string constants for Order Types, Order Side, Time in Force, Order response and Kline
intervals these are found on binance.client.Client.
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_3MINUTE = '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'
4.1. Contents 11
python-binance Documentation, Release 0.2.0
KLINE_INTERVAL_1MONTH = '1M'
SIDE_BUY = 'BUY'
SIDE_SELL = 'SELL'
ORDER_TYPE_LIMIT = 'LIMIT'
ORDER_TYPE_MARKET = 'MARKET'
ORDER_TYPE_STOP_LOSS = 'STOP_LOSS'
ORDER_TYPE_STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT'
ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT'
ORDER_TYPE_TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT'
ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER'
TIME_IN_FORCE_GTC = 'GTC'
TIME_IN_FORCE_IOC = 'IOC'
TIME_IN_FORCE_FOK = 'FOK'
ORDER_RESP_TYPE_ACK = 'ACK'
ORDER_RESP_TYPE_RESULT = 'RESULT'
ORDER_RESP_TYPE_FULL = 'FULL'
WEBSOCKET_DEPTH_5 = '5'
WEBSOCKET_DEPTH_10 = '10'
WEBSOCKET_DEPTH_20 = '20'
side = Client.SIDE_BUY
client.ping()
time_res = client.get_server_time()
info = client.get_exchange_info()
info = client.get_symbol_info('BNBBTC')
products = client.get_products()
depth = client.get_order_book(symbol='BNBBTC')
trades = client.get_recent_trades(symbol='BNBBTC')
trades = client.get_historical_trades(symbol='BNBBTC')
trades = client.get_aggregate_trades(symbol='BNBBTC')
Iterate over aggregate trades for a symbol from a given date or a given order id.
4.1. Contents 13
python-binance Documentation, Release 0.2.0
Get Kline/Candlesticks
tickers = client.get_ticker()
prices = client.get_all_tickers()
Get first bid and ask entry in the order book for all markets.
tickers = client.get_orderbook_tickers()
Orders
Order Validation
Binance has a number of rules around symbol pair orders with validation on minimum price, quantity and total order
value.
Read more about their specifics in the Filters section of the official API.
It can be helpful to format the output using the following snippet
amount = 0.000234234
precision = 5
amt_str = "{:0.0{}f}".format(amount, precision)
Place an order
Place an order
Use the create_order function to have full control over creating an order
order = client.order_limit_buy(
symbol='BNBBTC',
quantity=100,
price='0.00001')
order = client.order_limit_sell(
symbol='BNBBTC',
quantity=100,
price='0.00001')
4.1. Contents 15
python-binance Documentation, Release 0.2.0
order = client.order_market_buy(
symbol='BNBBTC',
quantity=100)
order = client.order_market_sell(
symbol='BNBBTC',
quantity=100)
Creates and validates a new order but does not send it into the exchange.
order = client.get_order(
symbol='BNBBTC',
orderId='orderId')
Cancel an order
result = client.cancel_order(
symbol='BNBBTC',
orderId='orderId')
orders = client.get_open_orders(symbol='BNBBTC')
orders = client.get_all_orders(symbol='BNBBTC')
Account
info = client.get_account()
balance = client.get_asset_balance(asset='BTC')
status = client.get_account_status()
Get trades
trades = client.get_my_trades(symbol='BNBBTC')
4.1.6 Websockets
Websocket Usage
4.1. Contents 17
python-binance Documentation, Release 0.2.0
def process_message(msg):
print("message type: {}".format(msg['e']))
print(msg)
# do something
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
{
'e': 'error',
'm': 'Max reconnect retries reached'
}
Multiplex Socket
def process_m_message(msg):
print("stream: {} data: {}".format(msg['stream'], msg['data']))
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.
Trade Socket
Ticker Socket
conn_key = bm.start_ticker_socket(process_message)
User Socket
4.1. Contents 19
python-binance Documentation, Release 0.2.0
bm.start_user_socket(process_message)
Close a Socket
To close an individual socket call the stop_socket function. This takes a conn_key parameter which is returned when
starting the socket.
bm.stop_socket(conn_key)
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()
Websockets utilise a reactor loop from the Twisted library. Using the close method above will close the websocket
connections but it won’t stop the reactor loop so your code may not exit when you expect.
If you do want to exit then use the stop method from reactor like below.
To follow the depth cache updates for a symbol use the DepthCacheManager
Create the manager like so, passing the api client, symbol and an optional callback function.
The callback function receives the current DepthCache object which allows access to a pre-sorted list of bids or asks
able to be filtered as required.
Access the symbol value from the depth_cache object in case you have multiple caches using the same callback.
By default the depth cache will fetch the order book via REST request every 30 minutes. This duration can be changed
by using the refresh_interval parameter. To disable the refresh pass 0 or None. The socket connection will stay open
receiving updates to be replayed once the full order book is received.
Websocket Errors
If the underlying websocket is disconnected and is unable to reconnect None is returned for the depth_cache parameter.
Examples
# disable refreshing
dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth, refresh_interval=0)
def process_depth(depth_cache):
if depth_cache is not None:
print("symbol {}".format(depth_cache.symbol))
print("top 5 bids")
print(depth_cache.get_bids()[:5])
print("top 5 asks")
print(depth_cache.get_asks()[:5])
else:
# depth cache had an error and needs to be restarted
At any time the current DepthCache object can be retrieved from the DepthCacheManager
depth_cache = dcm.get_depth_cache()
if depth_cache is not None:
print("symbol {}".format(depth_cache.symbol))
print("top 5 bids")
print(depth_cache.get_bids()[:5])
print("top 5 asks")
print(depth_cache.get_asks()[:5])
else:
# depth cache had an error and needs to be restarted
To stop the DepthCacheManager from returning messages use the close method. This will close the internal websocket
and this instance of the DepthCacheManager will not be able to be used again.
dcm.close()
Place a withdrawal
Make sure you enable Withdrawal permissions for your API Key to use this call.
You must have withdrawn to the address through the website and approved the withdrawal via email before you can
withdraw using the API.
Raises a BinanceWithdrawException if the withdraw fails.
4.1. Contents 21
python-binance Documentation, Release 0.2.0
except BinanceWithdrawException as e:
print(e)
else:
print("Success")
# if the coin requires a extra tag or name such as XRP or XMR then pass an
˓→`addressTag` parameter.
result = client.withdraw(
asset='XRP',
address='<xrp_address>',
addressTag='<xrp_address_tag>',
amount=10000)
deposits = client.get_deposit_history()
btc_deposits = client.get_deposit_history(asset='BTC')
withdraws = client.get_withdraw_history()
btc_withdraws = client.get_withdraw_history(asset='BTC')
address = client.get_deposit_address(asset='BTC')
binance.helpers
alias of binance.helpers
4.1.10 Exceptions
BinanceResponseException
BinanceAPIException
try:
client.get_all_orders()
except BinanceAPIException as e:
print e.status_code
print e.message
BinanceOrderException
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
BinanceOrderTotalPriceException
BinanceOrderUnknownSymbolException
BinanceOrderInactiveSymbolException
BinanceWithdrawException
4.1. Contents 23
python-binance Documentation, Release 0.2.0
4.1.11 FAQ
4.1.12 Changelog
v0.6.3 - 2018-01-29
Added
• mini ticker socket function start_miniticker_socket
• aggregate trade iterator aggregate_trade_iter
Fixes
• clean up interval_to_milliseconds logic
• general doc and file cleanups
v0.6.2 - 2018-01-12
Fixes
• fixed handling Binance errors that aren’t JSON objects
v0.6.1 - 2018-01-10
Fixes
• added missing dateparser dependency to setup.py
• documentation fixes
v0.6.0 - 2018-01-09
v0.5.17 - 2018-01-08
Added
• check for name parameter in withdraw, set to asset parameter if not passed
Update
• Windows install error documentation
Removed
• reference to disable_validation in documentation
v0.5.16 - 2018-01-06
Added
• addressTag documentation to withdraw function
• documentation about requests proxy environment variables
Update
• FAQ for signature error with solution to regenerate API key
• change create_order to create_test_order in example
Fixed
• reference to BinanceAPIException in documentation
v0.5.15 - 2018-01-03
Fixed
• removed all references to WEBSOCKET_DEPTH_1 enum
4.1. Contents 25
python-binance Documentation, Release 0.2.0
v0.5.14 - 2018-01-02
Added
• Wait for depth cache socket to start
• check for sequential depth cache messages
Updated
• documentation around depth websocket and diff and partial responses
Removed
• Removed unused WEBSOCKET_DEPTH_1 enum
• removed unused libraries and imports
v0.5.13 - 2018-01-01
Fixed
• Signature invalid error
v0.5.12 - 2017-12-29
Added
• get_asset_balance helper function to fetch an individual asset’s balance
Fixed
• added timeout to requests call to prevent hanging
• changed variable type to str for price parameter when creating an order
• documentation fixes
v0.5.11 - 2017-12-28
Added
• refresh interval parameter to depth cache to keep it fresh, set default at 30 minutes
Fixed
• watch depth cache socket before fetching order book to replay any messages
v0.5.10 - 2017-12-28
Updated
• updated dependencies certifi and cryptography to help resolve signature error
v0.5.9 - 2017-12-26
Fixed
• fixed websocket reconnecting, was no distinction between manual close or network error
v0.5.8 - 2017-12-25
Changed
• change symbol parameter to optional for get_open_orders function
• added listenKey parameter to stream_close function
Added
• get_account_status function that was missed
v0.5.7 - 2017-12-24
Changed
• change depth cache callback parameter to optional
Added
• note about stopping Twisted reactor loop to exit program
v0.5.6 - 2017-12-20
Added
• get_symbol_info function to simplify getting info about a particular symbol
v0.5.5 - 2017-12-19
Changed
• Increased default limit for order book on depth cache from 10 to 500
v0.5.4 - 2017-12-14
Added
• symbol property made public on DepthCache class
Changed
• Enums now also accessible from binance.client.Client and binance.websockets.BinanceSocketManager
v0.5.3 - 2017-12-09
Changed
• User stream refresh timeout from 50 minutes to 30 minutes
• User stream socket listen key change check simplified
v0.5.2 - 2017-12-08
Added
• start_multiplex_socket function to BinanceSocketManager to create multiplexed streams
4.1. Contents 27
python-binance Documentation, Release 0.2.0
v0.5.1 - 2017-12-06
Added
• Close method for DepthCacheManager
Fixes
• Fixed modifying array error message when closing the BinanceSocketManager
v0.5.0 - 2017-12-05
v0.4.3 - 2017-12-04
Fixes
• Fixed stopping sockets where they were reconnecting
• Fixed websockets unable to be restarted after close
• Exception in parsing non-JSON websocket message
v0.4.2 - 2017-11-30
Removed
• Removed websocket update time as 0ms option is not available
v0.4.1 - 2017-11-24
Added
• Reconnecting websockets, automatic retry on disconnect
v0.4.0 - 2017-11-19
Added
• Get deposit address endpoint
• Upgraded withdraw endpoints to v3
• New exchange info endpoint with rate limits and full symbol info
Removed
• Order validation to return at a later date
v0.3.8 - 2017-11-17
Fixes
• Fix order validation for market orders
• WEBSOCKET_DEPTH_20 value, 20 instead of 5
• General tidy up
v0.3.7 - 2017-11-16
Fixes
• Fix multiple depth caches sharing a cache by initialising bid and ask objects each time
v0.3.6 - 2017-11-15
Fixes
• check if Reactor is already running
v0.3.5 - 2017-11-06
Added
• support for BNB market
Fixes
• fixed error if new market type is created that we don’t know about
v0.3.4 - 2017-10-31
Added
• depth parameter to depth socket
• interval parameter to kline socket
• update time parameter for compatible sockets
• new enums for socket depth and update time values
• better websocket documentation
Changed
• Depth Cache Manager uses 0ms socket update time
• connection key returned when creating socket, this key is then used to stop it
Fixes
• General fixes
4.1. Contents 29
python-binance Documentation, Release 0.2.0
v0.3.3 - 2017-10-31
Fixes
• Fixes for broken tests
v0.3.2 - 2017-10-30
Added
• More test coverage of requests
Fixes
• Order quantity validation fix
v0.3.1 - 2017-10-29
Added
• Withdraw exception handler with translation of obscure error
Fixes
• Validation fixes
v0.3.0 - 2017-10-29
Added
• Withdraw endpoints
• Order helper functions
v0.2.0 - 2017-10-27
Added
• Symbol Depth Cache
v0.1.6 - 2017-10-25
Changes
• Upgrade to v3 signed endpoints
• Update function documentation
v0.1.5 - 2017-09-12
Changes
• Added get_all_tickers call
• Added get_orderbook_tickers call
• Added some FAQs
Fixes
• Fix error in enum value
v0.1.4 - 2017-09-06
Changes
• Added parameter to disable client side order validation
v0.1.3 - 2017-08-26
Changes
• Updated documentation
Fixes
• Small bugfix
v0.1.2 - 2017-08-25
Added
• Travis.CI and Coveralls support
Changes
• Validation for pairs using public endpoint
v0.1.1 - 2017-08-17
Added
• Validation for HSR/BTC pair
v0.1.0 - 2017-08-16
Websocket release
Added
• Websocket manager
• Order parameter validation
• Order and Symbol enums
• API Endpoints for Data Streams
v0.0.2 - 2017-08-14
Initial version
Added
• General, Market Data and Account endpoints
4.1. Contents 31
python-binance Documentation, Release 0.2.0
client module
ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL'
ORDER_STATUS_REJECTED = 'REJECTED'
ORDER_TYPE_LIMIT = 'LIMIT'
ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER'
ORDER_TYPE_MARKET = 'MARKET'
ORDER_TYPE_STOP_LOSS = 'STOP_LOSS'
ORDER_TYPE_STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT'
ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT'
ORDER_TYPE_TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT'
PRIVATE_API_VERSION = 'v3'
PUBLIC_API_VERSION = 'v1'
SIDE_BUY = 'BUY'
SIDE_SELL = 'SELL'
SYMBOL_TYPE_SPOT = 'SPOT'
TIME_IN_FORCE_FOK = 'FOK'
TIME_IN_FORCE_GTC = 'GTC'
TIME_IN_FORCE_IOC = 'IOC'
WEBSITE_URL = 'https://www.binance.com'
WITHDRAW_API_URL = 'https://api.binance.com/wapi'
WITHDRAW_API_VERSION = 'v3'
__init__(api_key, api_secret, requests_params=None)
Binance API Client constructor
Parameters
• api_key (str.) – Api Key
• api_secret (str.) – Api Secret
• requests_params (dict.) – optional - Dictionary of requests params to use for all
calls
aggregate_trade_iter(symbol, start_str=None, last_id=None)
Iterate over aggregate trade data from (start_time or last_id) to the end of the history so far.
If start_time is specified, start with the first trade after start_time. Meant to initialise a local cache of trade
data.
If last_id is specified, start with the trade after it. This is meant for updating a pre-existing local trade data
cache.
Only allows start_str or last_id—not both. Not guaranteed to work right if you’re running more than one
of these simultaneously. You will probably hit your rate limit.
See dateparser docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add “UTC” to date string e.g. “now UTC”, “11 hours ago UTC”
Parameters
4.1. Contents 33
python-binance Documentation, Release 0.2.0
cancel_order(**params)
Cancel an active order. Either orderId or origClientOrderId must be sent.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
cancel-order-trade
Parameters
• symbol (str) – required
• orderId (int) – The unique order id
• origClientOrderId (str) – optional
• newClientOrderId (str) – Used to uniquely identify this cancel. Automatically
generated by default.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
{
"symbol": "LTCBTC",
"origClientOrderId": "myOrder1",
"orderId": 1,
"clientOrderId": "cancelMyOrder1"
}
create_order(**params)
Send in a new order
Any order with an icebergQty MUST have timeInForce set to GTC.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#new-order–trade
Parameters
• symbol (str) – required
• side (str) – required
• type (str) – required
• timeInForce (str) – required if limit order
• quantity (decimal) – required
• price (str) – required
{
"symbol":"LTCBTC",
"orderId": 1,
"clientOrderId": "myOrder1" # Will be newClientOrderId
"transactTime": 1499827319559
}
Response RESULT:
{
"symbol": "BTCUSDT",
"orderId": 28,
"clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
"transactTime": 1507725176595,
"price": "0.00000000",
"origQty": "10.00000000",
"executedQty": "10.00000000",
"status": "FILLED",
"timeInForce": "GTC",
"type": "MARKET",
"side": "SELL"
}
Response FULL:
{
"symbol": "BTCUSDT",
"orderId": 28,
"clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
"transactTime": 1507725176595,
"price": "0.00000000",
"origQty": "10.00000000",
"executedQty": "10.00000000",
"status": "FILLED",
"timeInForce": "GTC",
"type": "MARKET",
"side": "SELL",
"fills": [
{
"price": "4000.00000000",
"qty": "1.00000000",
"commission": "4.00000000",
"commissionAsset": "USDT"
},
{
4.1. Contents 35
python-binance Documentation, Release 0.2.0
"price": "3999.00000000",
"qty": "5.00000000",
"commission": "19.99500000",
"commissionAsset": "USDT"
},
{
"price": "3998.00000000",
"qty": "2.00000000",
"commission": "7.99600000",
"commissionAsset": "USDT"
},
{
"price": "3997.00000000",
"qty": "1.00000000",
"commission": "3.99700000",
"commissionAsset": "USDT"
},
{
"price": "3995.00000000",
"qty": "1.00000000",
"commission": "3.99500000",
"commissionAsset": "USDT"
}
]
}
create_test_order(**params)
Test new order creation and signature/recvWindow long. Creates and validates a new order but does not
send it into the matching engine.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
test-new-order-trade
Parameters
• symbol (str) – required
• side (str) – required
• type (str) – required
• timeInForce (str) – required if limit order
• quantity (decimal) – required
• price (str) – required
• newClientOrderId (str) – A unique id for the order. Automatically generated if not
sent.
• icebergQty (decimal) – Used with iceberg orders
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; de-
fault: RESULT.
• recvWindow (int) – The number of milliseconds the request is valid for
{}
get_account(**params)
Get current account information.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
account-information-user_data
Parameters recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
{
"makerCommission": 15,
"takerCommission": 15,
"buyerCommission": 0,
"sellerCommission": 0,
"canTrade": true,
"canWithdraw": true,
"canDeposit": true,
"balances": [
{
"asset": "BTC",
"free": "4723846.89208129",
"locked": "0.00000000"
},
{
"asset": "LTC",
"free": "4763368.68006011",
"locked": "0.00000000"
}
]
}
get_account_status(**params)
Get account status detail.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#
account-status-user_data
Parameters recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
{
"msg": "Order failed:Low Order fill rate! Will be reactivated after 5
˓→ minutes.",
"success": true,
"objs": [
"5"
4.1. Contents 37
python-binance Documentation, Release 0.2.0
]
}
Raises BinanceWithdrawException
get_aggregate_trades(**params)
Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price
will have the quantity aggregated.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
compressedaggregate-trades-list
Parameters
• symbol (str) – required
• fromId (str) – ID to get aggregate trades from INCLUSIVE.
• startTime (int) – Timestamp in ms to get aggregate trades from INCLUSIVE.
• endTime (int) – Timestamp in ms to get aggregate trades until INCLUSIVE.
• limit (int) – Default 500; max 500.
Returns API response
[
{
"a": 26129, # Aggregate tradeId
"p": "0.01633102", # Price
"q": "4.70443515", # Quantity
"f": 27781, # First tradeId
"l": 27781, # Last tradeId
"T": 1498793709153, # Timestamp
"m": true, # Was the buyer the maker?
"M": true # Was the trade the best price match?
}
]
get_all_orders(**params)
Get all account orders; active, canceled, or filled.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#all-orders-user_
data
Parameters
• symbol (str) – required
• orderId (int) – The unique order id
• limit (int) – Default 500; max 500.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
[
{
"symbol": "LTCBTC",
"orderId": 1,
"clientOrderId": "myOrder1",
"price": "0.1",
"origQty": "1.0",
"executedQty": "0.0",
"status": "NEW",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "BUY",
"stopPrice": "0.0",
"icebergQty": "0.0",
"time": 1499827319559
}
]
get_all_tickers()
Latest price for all symbols.
https://www.binance.com/restapipub.html#symbols-price-ticker
Returns List of market tickers
[
{
"symbol": "LTCBTC",
"price": "4.00000200"
},
{
"symbol": "ETHBTC",
"price": "0.07946600"
}
]
get_asset_balance(asset, **params)
Get current asset balance.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
account-information-user_data
Parameters
• asset (str) – required
• recvWindow (int) – the number of milliseconds the request is valid for
Returns dictionary or None if not found
{
"asset": "BTC",
"free": "4723846.89208129",
"locked": "0.00000000"
}
4.1. Contents 39
python-binance Documentation, Release 0.2.0
get_deposit_address(**params)
Fetch a deposit address for a symbol
https://www.binance.com/restapipub.html
Parameters
• asset (str) – required
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
{
"address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
"success": true,
"addressTag": "1231212",
"asset": "BNB"
}
get_deposit_history(**params)
Fetch deposit history.
https://www.binance.com/restapipub.html
Parameters
• asset (str) – optional
• startTime (long) – optional
• endTime (long) – optional
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
{
"depositList": [
{
"insertTime": 1508198532000,
"amount": 0.04670582,
"asset": "ETH",
"status": 1
}
],
"success": true
}
get_exchange_info()
Return rate limits and list of symbols
Returns list - List of product dictionaries
{
"timezone": "UTC",
"serverTime": 1508631584636,
"rateLimits": [
{
"rateLimitType": "REQUESTS",
"interval": "MINUTE",
"limit": 1200
},
{
"rateLimitType": "ORDERS",
"interval": "SECOND",
"limit": 10
},
{
"rateLimitType": "ORDERS",
"interval": "DAY",
"limit": 100000
}
],
"exchangeFilters": [],
"symbols": [
{
"symbol": "ETHBTC",
"status": "TRADING",
"baseAsset": "ETH",
"baseAssetPrecision": 8,
"quoteAsset": "BTC",
"quotePrecision": 8,
"orderTypes": ["LIMIT", "MARKET"],
"icebergAllowed": false,
"filters": [
{
"filterType": "PRICE_FILTER",
"minPrice": "0.00000100",
"maxPrice": "100000.00000000",
"tickSize": "0.00000100"
}, {
"filterType": "LOT_SIZE",
"minQty": "0.00100000",
"maxQty": "100000.00000000",
"stepSize": "0.00100000"
}, {
"filterType": "MIN_NOTIONAL",
"minNotional": "0.00100000"
}
]
}
]
}
4.1. Contents 41
python-binance Documentation, Release 0.2.0
If using offset strings for dates add “UTC” to date string e.g. “now UTC”, “11 hours ago UTC”
Parameters
• symbol (str) – Name of symbol pair e.g BNBBTC
• interval (str) – Biannce Kline interval
• start_str (str) – Start date string in UTC format
• end_str (str) – optional - end date string in UTC format
Returns list of OHLCV values
get_historical_trades(**params)
Get older trades.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
recent-trades-list
Parameters
• symbol (str) – required
• limit (int) – Default 500; max 500.
• fromId (str) – TradeId to fetch from. Default gets most recent trades.
Returns API response
[
{
"id": 28457,
"price": "4.00000100",
"qty": "12.00000000",
"time": 1499865549590,
"isBuyerMaker": true,
"isBestMatch": true
}
]
get_klines(**params)
Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
klinecandlestick-data
Parameters
• symbol (str) – required
• interval (str) –
–
• limit (int) –
– Default 500; max 500.
• startTime (int) –
• endTime (int) –
Returns API response
[
[
1499040000000, # Open time
"0.01634790", # Open
"0.80000000", # High
"0.01575800", # Low
"0.01577100", # Close
"148976.11427815", # Volume
1499644799999, # Close time
"2434.19055334", # Quote asset volume
308, # Number of trades
"1756.87402397", # Taker buy base asset volume
"28.46694368", # Taker buy quote asset volume
"17928899.62484339" # Can be ignored
]
]
get_my_trades(**params)
Get trades for a specific symbol.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
account-trade-list-user_data
Parameters
• symbol (str) – required
• limit (int) – Default 500; max 500.
• fromId (int) – TradeId to fetch from. Default gets most recent trades.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
[
{
"id": 28457,
"price": "4.00000100",
"qty": "12.00000000",
"commission": "10.10000000",
"commissionAsset": "BNB",
"time": 1499865549590,
"isBuyer": true,
"isMaker": false,
"isBestMatch": true
}
]
get_open_orders(**params)
Get all open orders on a symbol.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
current-open-orders-user_data
4.1. Contents 43
python-binance Documentation, Release 0.2.0
Parameters
• symbol (str) – optional
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
[
{
"symbol": "LTCBTC",
"orderId": 1,
"clientOrderId": "myOrder1",
"price": "0.1",
"origQty": "1.0",
"executedQty": "0.0",
"status": "NEW",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "BUY",
"stopPrice": "0.0",
"icebergQty": "0.0",
"time": 1499827319559
}
]
get_order(**params)
Check an order’s status. Either orderId or origClientOrderId must be sent.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
query-order-user_data
Parameters
• symbol (str) – required
• orderId (int) – The unique order id
• origClientOrderId (str) – optional
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
{
"symbol": "LTCBTC",
"orderId": 1,
"clientOrderId": "myOrder1",
"price": "0.1",
"origQty": "1.0",
"executedQty": "0.0",
"status": "NEW",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "BUY",
"stopPrice": "0.0",
"icebergQty": "0.0",
"time": 1499827319559
}
get_order_book(**params)
Get the Order Book for the market
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#order-book
Parameters
• symbol (str) – required
• limit (int) – Default 100; max 100
Returns API response
{
"lastUpdateId": 1027024,
"bids": [
[
"4.00000000", # PRICE
"431.00000000", # QTY
[] # Can be ignored
]
],
"asks": [
[
"4.00000200",
"12.00000000",
[]
]
]
}
get_orderbook_ticker(**params)
Latest price for a symbol or symbols.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
symbol-order-book-ticker
Parameters symbol (str) –
Returns API response
{
"symbol": "LTCBTC",
"bidPrice": "4.00000000",
"bidQty": "431.00000000",
"askPrice": "4.00000200",
"askQty": "9.00000000"
}
OR
[
{
"symbol": "LTCBTC",
"bidPrice": "4.00000000",
"bidQty": "431.00000000",
4.1. Contents 45
python-binance Documentation, Release 0.2.0
"askPrice": "4.00000200",
"askQty": "9.00000000"
},
{
"symbol": "ETHBTC",
"bidPrice": "0.07946700",
"bidQty": "9.00000000",
"askPrice": "100000.00000000",
"askQty": "1000.00000000"
}
]
get_orderbook_tickers()
Best price/qty on the order book for all symbols.
https://www.binance.com/restapipub.html#symbols-order-book-ticker
Returns List of order book market entries
[
{
"symbol": "LTCBTC",
"bidPrice": "4.00000000",
"bidQty": "431.00000000",
"askPrice": "4.00000200",
"askQty": "9.00000000"
},
{
"symbol": "ETHBTC",
"bidPrice": "0.07946700",
"bidQty": "9.00000000",
"askPrice": "100000.00000000",
"askQty": "1000.00000000"
}
]
get_products()
Return list of products currently listed on Binance
Use get_exchange_info() call instead
Returns list - List of product dictionaries
Raises BinanceResponseException, BinanceAPIException
get_recent_trades(**params)
Get recent trades (up to last 500).
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
recent-trades-list
Parameters
• symbol (str) – required
• limit (int) – Default 500; max 500.
[
{
"id": 28457,
"price": "4.00000100",
"qty": "12.00000000",
"time": 1499865549590,
"isBuyerMaker": true,
"isBestMatch": true
}
]
get_server_time()
Test connectivity to the Rest API and get the current server time.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
check-server-time
Returns Current server time
{
"serverTime": 1499827319559
}
get_symbol_info(symbol)
Return information about a symbol
Parameters symbol (str) – required e.g BNBBTC
Returns Dict if found, None if not
{
"symbol": "ETHBTC",
"status": "TRADING",
"baseAsset": "ETH",
"baseAssetPrecision": 8,
"quoteAsset": "BTC",
"quotePrecision": 8,
"orderTypes": ["LIMIT", "MARKET"],
"icebergAllowed": false,
"filters": [
{
"filterType": "PRICE_FILTER",
"minPrice": "0.00000100",
"maxPrice": "100000.00000000",
"tickSize": "0.00000100"
}, {
"filterType": "LOT_SIZE",
"minQty": "0.00100000",
"maxQty": "100000.00000000",
"stepSize": "0.00100000"
}, {
"filterType": "MIN_NOTIONAL",
4.1. Contents 47
python-binance Documentation, Release 0.2.0
"minNotional": "0.00100000"
}
]
}
get_symbol_ticker(**params)
Latest price for a symbol or symbols.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
24hr-ticker-price-change-statistics
Parameters symbol (str) –
Returns API response
{
"symbol": "LTCBTC",
"price": "4.00000200"
}
OR
[
{
"symbol": "LTCBTC",
"price": "4.00000200"
},
{
"symbol": "ETHBTC",
"price": "0.07946600"
}
]
get_ticker(**params)
24 hour price change statistics.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
24hr-ticker-price-change-statistics
Parameters symbol (str) –
Returns API response
{
"priceChange": "-94.99999800",
"priceChangePercent": "-95.960",
"weightedAvgPrice": "0.29628482",
"prevClosePrice": "0.10002000",
"lastPrice": "4.00000200",
"bidPrice": "4.00000000",
"askPrice": "4.00000200",
"openPrice": "99.00000000",
"highPrice": "100.00000000",
"lowPrice": "0.10000000",
"volume": "8913.30000000",
"openTime": 1499783499040,
"closeTime": 1499869899040,
"fristId": 28385, # First tradeId
"lastId": 28460, # Last tradeId
"count": 76 # Trade count
}
OR
[
{
"priceChange": "-94.99999800",
"priceChangePercent": "-95.960",
"weightedAvgPrice": "0.29628482",
"prevClosePrice": "0.10002000",
"lastPrice": "4.00000200",
"bidPrice": "4.00000000",
"askPrice": "4.00000200",
"openPrice": "99.00000000",
"highPrice": "100.00000000",
"lowPrice": "0.10000000",
"volume": "8913.30000000",
"openTime": 1499783499040,
"closeTime": 1499869899040,
"fristId": 28385, # First tradeId
"lastId": 28460, # Last tradeId
"count": 76 # Trade count
}
]
get_withdraw_history(**params)
Fetch withdraw history.
https://www.binance.com/restapipub.html
Parameters
• asset (str) – optional
• startTime (long) – optional
• endTime (long) – optional
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
{
"withdrawList": [
{
"amount": 1,
"address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
"asset": "ETH",
"applyTime": 1508198532000
"status": 4
},
{
4.1. Contents 49
python-binance Documentation, Release 0.2.0
"amount": 0.005,
"address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
"txId":
˓→"0x80aaabed54bdab3f6de5868f89929a2371ad21d666f20f7393d1a3389fad95a1",
"asset": "ETH",
"applyTime": 1508198532000,
"status": 4
}
],
"success": true
}
order_limit(timeInForce=’GTC’, **params)
Send in a new limit order
Any order with an icebergQty MUST have timeInForce set to GTC.
Parameters
• symbol (str) – required
• side (str) – required
• quantity (decimal) – required
• price (str) – required
• timeInForce (str) – default Good till cancelled
• newClientOrderId (str) – A unique id for the order. Automatically generated if not
sent.
• icebergQty (decimal) – Used with LIMIT, STOP_LOSS_LIMIT, and
TAKE_PROFIT_LIMIT to create an iceberg order.
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; de-
fault: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See order endpoint for full response options
Raises BinanceResponseException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalEx-
ception, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_limit_buy(timeInForce=’GTC’, **params)
Send in a new limit buy order
Any order with an icebergQty MUST have timeInForce set to GTC.
Parameters
• symbol (str) – required
• quantity (decimal) – required
• price (str) – required
• timeInForce (str) – default Good till cancelled
4.1. Contents 51
python-binance Documentation, Release 0.2.0
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; de-
fault: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See order endpoint for full response options
Raises BinanceResponseException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalEx-
ception, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_market_buy(**params)
Send in a new market buy order
Parameters
• symbol (str) – required
• quantity (decimal) – required
• newClientOrderId (str) – A unique id for the order. Automatically generated if not
sent.
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; de-
fault: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See order endpoint for full response options
Raises BinanceResponseException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalEx-
ception, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_market_sell(**params)
Send in a new market sell order
Parameters
• symbol (str) – required
• quantity (decimal) – required
• newClientOrderId (str) – A unique id for the order. Automatically generated if not
sent.
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; de-
fault: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See order endpoint for full response options
Raises BinanceResponseException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalEx-
ception, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
ping()
Test connectivity to the Rest API.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#test-connectivity
{}
stream_close(listenKey)
Close out a user data stream.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
close-user-data-stream-user_stream
Parameters listenKey (str) – required
Returns API response
{}
stream_get_listen_key()
Start a new user data stream and return the listen key If a stream already exists it should return the same
key. If the stream becomes invalid a new key is returned.
Can be used to keep the user stream alive.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
start-user-data-stream-user_stream
Returns API response
{
"listenKey":
˓→ "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"
}
stream_keepalive(listenKey)
PING a user data stream to prevent a time out.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#
keepalive-user-data-stream-user_stream
Parameters listenKey (str) – required
Returns API response
{}
withdraw(**params)
Submit a withdraw request.
https://www.binance.com/restapipub.html
Assumptions:
4.1. Contents 53
python-binance Documentation, Release 0.2.0
Parameters
• asset (str) – required
• amount (decimal) – required
• name (str) – optional - Description of the address, default asset value passed will be
used
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
{
"msg": "success",
"success": true,
"id":"7213fea8e94b4a5593d507237e5a555b"
}
depthcache module
class binance.depthcache.DepthCache(symbol)
Bases: object
__init__(symbol)
Intialise the DepthCache
Parameters symbol (string) – Symbol to create depth cache for
add_ask(ask)
Add an ask to the cache
Parameters ask –
Returns
add_bid(bid)
Add a bid to the cache
Parameters bid –
Returns
get_asks()
Get the current asks
Returns list of asks with price and quantity as floats
[
[
0.0001955, # Price
57.0' # Quantity
],
[
0.00019699,
778.0
],
[
0.000197,
64.0
],
[
0.00019709,
1130.0
],
[
0.0001971,
385.0
]
]
get_bids()
Get the current bids
Returns list of bids with price and quantity as floats
[
[
0.0001946, # Price
45.0 # Quantity
],
[
0.00019459,
2384.0
],
[
0.00019158,
5219.0
],
[
0.00019157,
1180.0
],
[
0.00019082,
287.0
]
]
4.1. Contents 55
python-binance Documentation, Release 0.2.0
exceptions module
exception binance.exceptions.BinanceAPIException(response)
Bases: exceptions.Exception
LISTENKEY_NOT_EXIST = '-1125'
__init__(response)
exception binance.exceptions.BinanceOrderException(code, message)
Bases: exceptions.Exception
__init__(code, message)
exception binance.exceptions.BinanceOrderInactiveSymbolException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
exception binance.exceptions.BinanceOrderMinAmountException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
exception binance.exceptions.BinanceOrderMinPriceException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
exception binance.exceptions.BinanceOrderMinTotalException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
exception binance.exceptions.BinanceOrderUnknownSymbolException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
exception binance.exceptions.BinanceRequestException(message)
Bases: exceptions.Exception
__init__(message)
exception binance.exceptions.BinanceWithdrawException(message)
Bases: exceptions.Exception
__init__(message)
helpers module
binance.helpers.date_to_milliseconds(date_str)
Convert UTC date to milliseconds
If using offset strings add “UTC” to date string e.g. “now UTC”, “11 hours ago UTC”
See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/
Parameters date_str (str) – date in readable format, i.e. “January 01, 2018”, “11 hours ago
UTC”, “now UTC”
binance.helpers.interval_to_milliseconds(interval)
Convert a Binance interval string to milliseconds
Parameters interval (str) – Binance interval string, e.g.: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h,
6h, 8h, 12h, 1d, 3d, 1w
Returns int value of interval in milliseconds None if interval prefix is not a decimal integer None if
interval suffix is not one of m, h, d, w
websockets module
4.1. Contents 57
python-binance Documentation, Release 0.2.0
close()
Close all connections
run()
start_aggtrade_socket(symbol, callback)
Start a websocket for symbol trade data
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#
aggregate-trade-streams
Parameters
• symbol (str) – required
• callback (function) – callback function to handle messages
Returns connection key string if successful, False otherwise
Message Format
{
"e": "aggTrade", # event type
"E": 1499405254326, # event time
"s": "ETHBTC", # symbol
"a": 70232, # aggregated tradeid
"p": "0.10281118", # price
"q": "8.15632997", # quantity
"f": 77489, # first breakdown trade id
"l": 77489, # last breakdown trade id
"T": 1499405254324, # trade time
"m": false, # whether buyer is a maker
"M": true # can be ignored
}
{
"lastUpdateId": 160, # Last update ID
"bids": [ # Bids to be updated
[
"0.0024", # price level to be updated
"10", # quantity
[] # ignore
]
],
{
"e": "depthUpdate", # Event type
"E": 123456789, # Event time
"s": "BNBBTC", # Symbol
"U": 157, # First update ID in event
"u": 160, # Final update ID in event
"b": [ # Bids to be updated
[
"0.0024", # price level to be updated
"10", # quantity
[] # ignore
]
],
"a": [ # Asks to be updated
[
"0.0026", # price level to be updated
"100", # quantity
[] # ignore
]
]
}
{
"e": "kline", # event type
"E": 1499404907056, # event time
"s": "ETHBTC", # symbol
"k": {
"t": 1499404860000, # start time of this bar
"T": 1499404919999, # end time of this bar
"s": "ETHBTC", # symbol
"i": "1m", # interval
4.1. Contents 59
python-binance Documentation, Release 0.2.0
start_miniticker_socket(callback, update_time=1000)
Start a miniticker websocket for all trades
This is not in the official Binance api docs, but this is what feeds the right column on a ticker page on
Binance.
Parameters
• callback (function) – callback function to handle messages
• update_time (int) – time between callbacks in milliseconds, must be 1000 or greater
Returns connection key string if successful, False otherwise
Message Format
[
{
'e': '24hrMiniTicker', # Event type
'E': 1515906156273, # Event time
's': 'QTUMETH', # Symbol
'c': '0.03836900', # close
'o': '0.03953500', # open
'h': '0.04400000', # high
'l': '0.03756000', # low
'v': '147435.80000000', # volume
'q': '5903.84338533' # quote volume
}
]
start_multiplex_socket(streams, callback)
Start a multiplexed socket using a list of socket names. User stream sockets can not be included.
Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker
Combined stream events are wrapped as follows: {“stream”:”<streamName>”,”data”:<rawPayload>}
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md
Parameters
• streams (list) – list of stream names in lower case
• callback (function) – callback function to handle messages
{
"e": "24hrTicker", # Event type
"E": 123456789, # Event time
"s": "BNBBTC", # Symbol
"p": "0.0015", # Price change
"P": "250.00", # Price change percent
"w": "0.0018", # Weighted average price
"x": "0.0009", # Previous day's close price
"c": "0.0025", # Current day's close price
"Q": "10", # Close trade's quantity
"b": "0.0024", # Best bid price
"B": "10", # Bid bid quantity
"a": "0.0026", # Best ask price
"A": "100", # Best ask quantity
"o": "0.0010", # Open price
"h": "0.0025", # High price
"l": "0.0010", # Low price
"v": "10000", # Total traded base asset volume
"q": "18", # Total traded quote asset volume
"O": 0, # Statistics open time
"C": 86400000, # Statistics close time
"F": 0, # First trade ID
"L": 18150, # Last trade Id
"n": 18151 # Total number of trades
}
start_ticker_socket(callback)
Start a websocket for all ticker data
By default all markets are included in an array.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#
all-market-tickers-stream
Parameters callback (function) – callback function to handle messages
Returns connection key string if successful, False otherwise
Message Format
[
{
'F': 278610,
4.1. Contents 61
python-binance Documentation, Release 0.2.0
'o': '0.07393000',
's': 'BCCBTC',
'C': 1509622420916,
'b': '0.07800800',
'l': '0.07160300',
'h': '0.08199900',
'L': 287722,
'P': '6.694',
'Q': '0.10000000',
'q': '1202.67106335',
'p': '0.00494900',
'O': 1509536020916,
'a': '0.07887800',
'n': 9113,
'B': '1.00000000',
'c': '0.07887900',
'x': '0.07399600',
'w': '0.07639068',
'A': '2.41900000',
'v': '15743.68900000'
}
]
start_trade_socket(symbol, callback)
Start a websocket for symbol trade data
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#
trade-streams
Parameters
• symbol (str) – required
• callback (function) – callback function to handle messages
Returns connection key string if successful, False otherwise
Message Format
{
"e": "trade", # Event type
"E": 123456789, # Event time
"s": "BNBBTC", # Symbol
"t": 12345, # Trade ID
"p": "0.001", # Price
"q": "100", # Quantity
"b": 88, # Buyer order Id
"a": 50, # Seller order Id
"T": 123456785, # Trade time
"m": true, # Is the buyer the market maker?
"M": true # Ignore.
}
start_user_socket(callback)
Start a websocket for user data
https://www.binance.com/restapipub.html#user-wss-endpoint
Parameters callback (function) – callback function to handle messages
Returns connection key string if successful, False otherwise
4.2 Index
• genindex
4.2. Index 63
python-binance Documentation, Release 0.2.0
b
binance.client, 32
binance.depthcache, 54
binance.exceptions, 56
binance.helpers, 57
binance.websockets, 57
65
python-binance Documentation, Release 0.2.0
A C
add_ask() (binance.depthcache.DepthCache method), 54 cancel_order() (binance.client.Client method), 34
add_bid() (binance.depthcache.DepthCache method), 54 Client (class in binance.client), 32
AGG_BEST_MATCH (binance.client.Client attribute), clientConnectionFailed() (bi-
32 nance.websockets.BinanceClientFactory
AGG_BUYER_MAKES (binance.client.Client attribute), method), 57
32 clientConnectionLost() (bi-
AGG_FIRST_TRADE_ID (binance.client.Client at- nance.websockets.BinanceClientFactory
tribute), 32 method), 57
AGG_ID (binance.client.Client attribute), 32 close() (binance.depthcache.DepthCacheManager
AGG_LAST_TRADE_ID (binance.client.Client at- method), 56
tribute), 32 close() (binance.websockets.BinanceSocketManager
AGG_PRICE (binance.client.Client attribute), 32 method), 58
67
python-binance Documentation, Release 0.2.0
68 Index
python-binance Documentation, Release 0.2.0
Index 69
python-binance Documentation, Release 0.2.0
70 Index