0% found this document useful (0 votes)
1K views132 pages

Python Binance Readthedocs Io en Latest

This document provides an overview of the python-binance library for interacting with the Binance cryptocurrency exchange API. It describes how to install the library, register for a Binance account, generate API keys, initialize the client, make API calls, handle rate limits, and configure request settings such as proxies. The library supports all of Binance's general, market data, account, and other endpoints through an object-oriented interface.

Uploaded by

Alexandre Santos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views132 pages

Python Binance Readthedocs Io en Latest

This document provides an overview of the python-binance library for interacting with the Binance cryptocurrency exchange API. It describes how to install the library, register for a Binance account, generate API keys, initialize the client, make API calls, handle rate limits, and configure request settings such as proxies. The library supports all of Binance's general, market data, account, and other endpoints through an object-oriented interface.

Uploaded by

Alexandre Santos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 132

python-binance Documentation

Release 0.2.0

Sam McHardy

Jan 06, 2021


Contents

1 Note 1

2 Features 3

3 Quick Start 5

4 Donate 7

5 Other Exchanges 9
5.1 Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
5.2 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

Python Module Index 121

Index 123

i
ii
CHAPTER 1

Note

this library is not under active development by sammchardy. however, the community has been actively contributing
lots of PRs. If you find missing features please submit a PR. please keep PRs small and non-breaking.

This is an unofficial Python wrapper for the Binance exchange REST API v3. 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.
If you’re interested in Binance’s new DEX Binance Chain see my python-binance-chain library
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.

1
python-binance Documentation, Release 0.2.0

2 Chapter 1. Note
CHAPTER 2

Features

• Implementation of all 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 with reconnection and multiplexed connections
• Symbol Depth Cache
• Historical Kline/Candle fetching function
• Withdraw functionality
• Deposit addresses
• Margin Trading
• Futures Trading
• Support other domains (.us, .jp, etc)

3
python-binance Documentation, Release 0.2.0

4 Chapter 2. Features
CHAPTER 3

Quick Start

Register an account with Binance.


Generate an API Key and assign relevant permissions.

pip install python-binance

from binance.client import Client


client = Client(api_key, api_secret)

# get market depth


depth = client.get_order_book(symbol='BNBBTC')

# 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)

# get all symbol prices


prices = client.get_all_tickers()

# withdraw 100 ETH


# check docs for assumptions around withdrawals
from binance.exceptions import BinanceAPIException, BinanceWithdrawException
try:
result = client.withdraw(
asset='ETH',
address='<eth_address>',
amount=100)
except BinanceAPIException as e:
print(e)
except BinanceWithdrawException as e:
(continues on next page)

5
python-binance Documentation, Release 0.2.0

(continued from previous page)


print(e)
else:
print("Success")

# fetch list of withdrawals


withdraws = client.get_withdraw_history()

# fetch list of ETH withdrawals


eth_withdraws = client.get_withdraw_history(asset='ETH')

# get a deposit address for BTC


address = client.get_deposit_address(asset='BTC')

# start aggregated trade websocket for BNBBTC


def process_message(msg):
print("message type: {}".format(msg['e']))
print(msg)
# do something

from binance.websockets import BinanceSocketManager


bm = BinanceSocketManager(client)
bm.start_aggtrade_socket('BNBBTC', process_message)
bm.start()

# get historical kline data from any date range

# fetch 1 minute klines for the last day up until now


klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day
˓→ago UTC")

# fetch 30 minute klines for the last month of 2017


klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1
˓→Dec, 2017", "1 Jan, 2018")

# fetch weekly klines since it listed


klines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan,
˓→2017")

For more check out the documentation.

6 Chapter 3. Quick Start


CHAPTER 4

Donate

If this library helped you out feel free to donate.


• ETH: 0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70
• LTC: LPC5vw9ajR1YndE1hYVeo3kJ9LdHjcRCUZ
• NEO: AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBo
• BTC: 1Dknp6L6oRZrHDECRedihPzx2sSfmvEBys

7
python-binance Documentation, Release 0.2.0

8 Chapter 4. Donate
CHAPTER 5

Other Exchanges

If you use Binance Chain check out my python-binance-chain library.


If you use Kucoin check out my python-kucoin library.
If you use IDEX check out my python-idex library.

5.1 Contents

5.1.1 Getting Started

Installation

python-binance is available on PYPI. Install with pip:

pip install python-binance

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

Firstly register an account with Binance.

Generate an API Key

To use signed account methods you are required to create an API Key.

9
python-binance Documentation, Release 0.2.0

Initialise the client

Pass your API Key and Secret

from binance.client import Client


client = Client(api_key, api_secret)

Making API Calls

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.

API Rate Limit

Check the get_exchange_info() call for up to date rate limits.


At the current time Binance rate limits are:
• 1200 requests per minute
• 10 orders per second
• 100,000 orders per 24hrs
Some calls have a higher weight than others especially if a call returns information about all symbols. Read the
‘official Binance documentation <https://github.com/binance-exchange/binance-official-api-docs‘_ for specific
information.

Requests Settings

python-binance uses the requests library.


You can set custom requests parameters for all API calls when creating the client.

client = Client("api-key", "api-secret", {"verify": False, "timeout": 20})

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})

Check out the requests documentation for all options.


Proxy Settings
You can use the Requests Settings method above

10 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080'
}

# in the Client instantiation


client = Client("api-key", "api-secret", {'proxies': proxies})

# 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"

For Windows environments


C:\>set HTTP_PROXY=http://10.10.1.10:3128
C:\>set HTTPS_PROXY=http://10.10.1.10:1080

5.1.2 Binance Constants

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'
KLINE_INTERVAL_1MONTH = '1M'

SIDE_BUY = 'BUY'
SIDE_SELL = 'SELL'
(continues on next page)

5.1. Contents 11
python-binance Documentation, Release 0.2.0

(continued from previous page)

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'

# For accessing the data returned by Client.aggregate_trades().


AGG_ID = 'a'
AGG_PRICE = 'p'
AGG_QUANTITY = 'q'
AGG_FIRST_TRADE_ID = 'f'
AGG_LAST_TRADE_ID = 'l'
AGG_TIME = 'T'
AGG_BUYER_MAKES = 'm'
AGG_BEST_MATCH = 'M'

For Websocket Depth these are found on binance.websockets.BinanceSocketManager

WEBSOCKET_DEPTH_5 = '5'
WEBSOCKET_DEPTH_10 = '10'
WEBSOCKET_DEPTH_20 = '20'

To use in your code reference either binance.client.Client or binance.websockets.BinanceSocketManager

from binance.client import Client


from binance.websockets import BinanceSocketManager

side = Client.SIDE_BUY

5.1.3 General Endpoints

Ping the server

client.ping()

Get the server time

time_res = client.get_server_time()

12 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Get system status

status = client.get_system_status()

Returns

{
"status": 0, # 0: normal1system maintenance
"msg": "normal" # normal or System maintenance.
}

Get Exchange Info

info = client.get_exchange_info()

Get Symbol Info

Get the exchange info for a particular symbol

info = client.get_symbol_info('BNBBTC')

Get Current Products

This call is deprecated, use the above Exchange Info call

products = client.get_products()

5.1.4 Market Data Endpoints

Get Market Depth

depth = client.get_order_book(symbol='BNBBTC')

Get Recent Trades

trades = client.get_recent_trades(symbol='BNBBTC')

Get Historical Trades

trades = client.get_historical_trades(symbol='BNBBTC')

Get Aggregate Trades

trades = client.get_aggregate_trades(symbol='BNBBTC')

5.1. Contents 13
python-binance Documentation, Release 0.2.0

Aggregate Trade Iterator

Iterate over aggregate trades for a symbol from a given date or a given order id.

agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', start_str='30 minutes ago


˓→UTC')

# iterate over the trade iterator


for trade in agg_trades:
print(trade)
# do something with the trade data

# convert the iterator to a list


# note: generators can only be iterated over once so we need to call it again
agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', '30 minutes ago UTC')
agg_trade_list = list(agg_trades)

# example using last_id value


agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', last_id=23380478)
agg_trade_list = list(agg_trades)

Get Kline/Candlesticks

candles = client.get_klines(symbol='BNBBTC', interval=Client.KLINE_INTERVAL_30MINUTE)

Get Historical Kline/Candlesticks

Fetch klines for any date range and interval

# fetch 1 minute klines for the last day up until now


klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day
˓→ago UTC")

# fetch 30 minute klines for the last month of 2017


klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1
˓→Dec, 2017", "1 Jan, 2018")

# fetch weekly klines since it listed


klines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan,
˓→2017")

Get Historical Kline/Candlesticks using a generator

Fetch klines using a generator

for kline in client.get_historical_klines_generator("BNBBTC", Client.KLINE_INTERVAL_


˓→1MINUTE, "1 day ago UTC")

print(kline)
# do something with the kline

14 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Get average price for a symbol

avg_price = client.get_avg_price(symbol='BNBBTC')

Get 24hr Ticker

tickers = client.get_ticker()

Get All Prices

Get last price for all markets.

prices = client.get_all_tickers()

Get Orderbook Tickers

Get first bid and ask entry in the order book for all markets.

tickers = client.get_orderbook_tickers()

5.1.5 Account Endpoints

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)

Fetch all orders

orders = client.get_all_orders(symbol='BNBBTC', limit=10)

Place an order

Place an order
Use the create_order function to have full control over creating an order

5.1. Contents 15
python-binance Documentation, Release 0.2.0

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')

Place a limit order


Use the helper functions to easily place a limit buy or sell 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')

Place a market order


Use the helper functions to easily place a market buy or sell order

order = client.order_market_buy(
symbol='BNBBTC',
quantity=100)

order = client.order_market_sell(
symbol='BNBBTC',
quantity=100)

Place an OCO order


Use the create_oco_order function to have full control over creating an OCO order

from binance.enums import *


order = client.create_oco_order(
symbol='BNBBTC',
side=SIDE_SELL,
stopLimitTimeInForce=TIME_IN_FORCE_GTC,
quantity=100,
stopPrice='0.00001'
price='0.00002')

Place a test order

Creates and validates a new order but does not send it into the exchange.

from binance.enums import *


order = client.create_test_order(
symbol='BNBBTC',
side=SIDE_BUY,
(continues on next page)

16 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=100,
price='0.00001')

Check order status

order = client.get_order(
symbol='BNBBTC',
orderId='orderId')

Cancel an order

result = client.cancel_order(
symbol='BNBBTC',
orderId='orderId')

Get all open orders

orders = client.get_open_orders(symbol='BNBBTC')

Get all orders

orders = client.get_all_orders(symbol='BNBBTC')

Account

Get account info

info = client.get_account()

Get asset balance

balance = client.get_asset_balance(asset='BTC')

Get account status

status = client.get_account_status()

5.1. Contents 17
python-binance Documentation, Release 0.2.0

Get trades

trades = client.get_my_trades(symbol='BNBBTC')

Get trade fees

# get fees for all symbols


fees = client.get_trade_fee()

# get fee for one symbol


fees = client.get_trade_fee(symbol='BNBBTC')

Get asset details

details = client.get_asset_details()

Get dust log

log = client.get_dust_log()

Transfer dust

transfer = client.transfer_dust(asset='BNZ')

Get Asset Dividend History

history = client.get_asset_dividend_history()

5.1.6 Sub Account Endpoints

Get Sub Account list

accounts = client.get_sub_account_list()

Get Sub Account Transfer History

history = client.get_sub_account_transfer_history(email='[email protected]')

18 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Create Sub Account Transfer

transfer = client.create_sub_account_transfer(
fromEmail='[email protected]',
toEmail='[email protected]',
asset='BNB',
amount='100'
)

Get Sub Account Assets

assets = client.get_sub_account_assets(email='[email protected]')

5.1.7 Margin Trading Endpoints

Note: Cross-margin vs isolated margin trading


Binance offers both cross-margin trading (where all margin is in one account) and isolated margin trading (where each
pair is a separate margin account). Make sure you are interacting with the right one.
Some of the API endpoints apply to the cross-margin or isolated margin accounts only. Other endpoints, such as
the trade execution endpoints, are used for the cross-margin account trades by default, but you can use your isolated
margin accounts by using the isIsolated or isolatedSymbol parameters. See the documentation below.

Market Data

Get cross-margin asset info

info = client.get_margin_asset(asset='BNB')

Get cross-margin symbol info

info = client.get_margin_symbol(symbol='BTCUSDT')

Get isolated margin symbol info

info = client.get_isolated_margin_symbol(symbol='BTCUSDT')

Get all isolated margin symbols

info = client.get_all_isolated_margin_symbols()

5.1. Contents 19
python-binance Documentation, Release 0.2.0

Get margin price index

info = client.get_margin_price_index(symbol='BTCUSDT')

Orders

Cross-margin vs isolated margin orders

By default, these trade execution endpoints will create an order using the cross-margin account.
To use the isolated margin account for the symbol you have specified, simply add the isIsolated='TRUE'
parameter to the API calls below in this ‘Orders’ section.

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)

Fetch all margin_orders

orders = client.get_all_margin_orders(symbol='BNBBTC', limit=10)

Place a margin order

Use the create_margin_order function to have full control over creating an order

from binance.enums import *


order = client.create_margin_order(
symbol='BNBBTC',
side=SIDE_BUY,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=100,
price='0.00001')

Check order status

order = client.get_margin_order(
symbol='BNBBTC',
orderId='orderId')

20 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Cancel a margin order

result = client.cancel_margin_order(
symbol='BNBBTC',
orderId='orderId')

Get all open margin orders

orders = client.get_open_margin_orders(symbol='BNBBTC')

For isolated margin, add the isIsolated='TRUE' parameter.

Get all margin orders

orders = client.get_all_margin_orders(symbol='BNBBTC')

For isolated margin, add the isIsolated='TRUE' parameter.

Account

Get cross-margin account info

info = client.get_margin_account()

Create isolated margin account

account = client.create_isolated_margin_account(base='BTC', quote='ETH')

Get isolated margin account info

info = client.get_isolated_margin_account()

Transfer spot to cross-margin account

transaction = client.transfer_spot_to_margin(asset='BTC', amount='1.1')

Transfer cross-margin account to spot

transaction = client.transfer_margin_to_spot(asset='BTC', amount='1.1')

5.1. Contents 21
python-binance Documentation, Release 0.2.0

Transfer spot to isolated margin account

transaction = client.transfer_spot_to_isolated_margin(asset='BTC',
symbol='ETHBTC', amount='1.1')

Transfer isolated margin account to spot

transaction = client.transfer_isolated_margin_to_spot(asset='BTC',
symbol='ETHBTC', amount='1.1')

Get max transfer amount

details = client.get_max_margin_transfer(asset='BTC')

This max transfer is for the cross-margin account by default. For isolated margin records, add the
isolatedSymbol=symbol_name parameter.

Trades

Get all margin trades

trades = client.get_margin_trades(symbol='BNBBTC')

For isolated margin trades, add the isIsolated='TRUE' parameter.

Loans

Create loan

transaction = client.create_margin_loan(asset='BTC', amount='1.1')

This for the cross-margin account by default. For isolated margin, add the isIsolated='TRUE' and the
symbol=symbol_name parameters.

Repay loan

transaction = client.repay_margin_loan(asset='BTC', amount='1.1')

This for the cross-margin account by default. For isolated margin, add the isIsolated='TRUE' and the
symbol=symbol_name parameters.

Get loan details

details = client.get_margin_loan_details(asset='BTC', txId='100001')

22 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

This for the cross-margin account by default. For isolated margin records, add the
isolatedSymbol=symbol_name parameter.

Get repay details

details = client.get_margin_repay_details(asset='BTC', txId='100001')

This for the cross-margin account by default. For isolated margin records, add the
isolatedSymbol=symbol_name parameter.

Get max loan amount

details = client.get_max_margin_loan(asset='BTC')

The max loan is for the cross-margin account by default. For isolated margin records, add the
isolatedSymbol=symbol_name parameter.

5.1.8 Websockets

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.
When creating socket connections a callback function is passed which receives the messages.
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.

Websocket Usage

Create the manager like so, passing the API client.

from binance.websockets import BinanceSocketManager


bm = BinanceSocketManager(client)
# start any sockets here, i.e a trade socket
conn_key = bm.start_trade_socket('BNBBTC', process_message)
# then start the socket manager
bm.start()

A callback to process messages would take the format

def process_message(msg):
print("message type: {}".format(msg['e']))
print(msg)
# do something

Set a custom timeout for the websocket connection

5.1. Contents 23
python-binance Documentation, Release 0.2.0

# set a timeout of 60 seconds


bm = BinanceSocketManager(client, user_timeout=60)

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'
}

# check for it like so


def process_message(msg):
if msg['e'] == 'error':
# close and restart the socket
else:
# process message normally

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
See the Binance Websocket Streams API documentation for details on socket names.

def process_m_message(msg):
print("stream: {} data: {}".format(msg['stream'], msg['data']))

# pass a list of stream names


conn_key = bm.start_multiplex_socket(['bnbbtc@aggTrade', 'neobtc@ticker'], process_m_
˓→message)

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.

# depth diff response


diff_key = bm.start_depth_socket('BNBBTC', process_message)

# partial book response


partial_key = bm.start_depth_socket('BNBBTC', process_message,
˓→depth=BinanceSocketManager.WEBSOCKET_DEPTH_5)

24 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Kline Socket

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

from binance.enums import *


conn_key = bm.start_kline_socket('BNBBTC', process_message, interval=KLINE_INTERVAL_
˓→30MINUTE)

Aggregated Trade Socket

conn_key = bm.start_aggtrade_socket('BNBBTC', process_message)

Trade Socket

conn_key = bm.start_trade_socket('BNBBTC', process_message)

Symbol Ticker Socket

conn_key = bm.start_symbol_ticker_socket('BNBBTC', process_message)

Ticker Socket

conn_key = bm.start_ticker_socket(process_message)

Mini Ticker Socket

# by default updates every second


conn_key = bm.start_miniticker_socket(process_message)

# this socket can take an update interval parameter


# set as 5000 to receive updates every 5 seconds
conn_key = bm.start_miniticker_socket(process_message, 5000)

User Socket

This watches for 3 different user events


• Account Update Event
• Order Update Event
• Trade Update Event
The Manager handles keeping the socket alive.
There are separate sockets for Spot, Cross-margin and separate Isolated margin accounts.

5.1. Contents 25
python-binance Documentation, Release 0.2.0

Spot trading

bm.start_user_socket(process_message)

Cross-margin

bm.start_margin_socket(process_message)

Isolated margin

bm.start_isolated_margin_socket(symbol, 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()

Close and exit program

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.

from twisted.internet import reactor

# program code here

# when you need to exit


reactor.stop()

5.1.9 Depth Cache

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.

from binance.depthcache import DepthCacheManager


dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth)

26 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

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.

Share a Socket Manager

Here dcm1 and dcm2 share the same instance of BinanceSocketManager

from binance.websockets import BinanceSocketManager


from binance.depthcache import DepthCacheManager
bm = BinanceSocketManager(client)
dcm1 = DepthCacheManager(client, 'BNBBTC', callback=process_depth1, bm=bm)
dcm2 = DepthCacheManager(client, 'ETHBTC', callback=process_depth2, bm=bm)

Because they both share the same BinanceSocketManager calling close can close both message streams.

# close just dcm1 stream


dcm1.close()

# close the underlying socket manager as well


dcm1.close(close_socket=True)

Websocket Errors

If the underlying websocket is disconnected and is unable to reconnect None is returned for the depth_cache parameter.

Examples

# 1 hour interval refresh


dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth, refresh_
˓→interval=60*60)

# 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])
print("last update time {}".format(depth_cache.update_time)
else:
# depth cache had an error and needs to be restarted

At any time the current DepthCache object can be retrieved from the DepthCacheManager

5.1. Contents 27
python-binance Documentation, Release 0.2.0

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])
print("last update time {}".format(depth_cache.update_time)
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()

5.1.10 Withdraw Endpoints

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.

from binance.exceptions import BinanceAPIException, BinanceWithdrawException


try:
# name parameter will be set to the asset value by the client if not passed
result = client.withdraw(
asset='ETH',
address='<eth_address>',
amount=100)
except BinanceAPIException as e:
print(e)
except BinanceWithdrawException as e:
print(e)
else:
print("Success")

# passing a name parameter


result = client.withdraw(
asset='ETH',
address='<eth_address>',
amount=100,
name='Withdraw')

# 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)

28 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Fetch deposit history

deposits = client.get_deposit_history()
btc_deposits = client.get_deposit_history(asset='BTC')

Fetch withdraw history

withdraws = client.get_withdraw_history()
btc_withdraws = client.get_withdraw_history(asset='BTC')

Get deposit address

address = client.get_deposit_address(asset='BTC')

5.1.11 Helper Functions

binance.helpers
alias of binance.helpers

5.1.12 Exceptions

BinanceRequestException

Raised if a non JSON response is returned

BinanceAPIException

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

try:
client.get_all_orders()
except BinanceAPIException as e:
print e.status_code
print e.message

BinanceWithdrawException

Raised if the withdraw fails.

5.1. Contents 29
python-binance Documentation, Release 0.2.0

5.1.13 FAQ

Q: Why do I get “Timestamp for this request is not valid”


A: This occurs in 2 different cases.
The timestamp sent is outside of the serverTime - recvWindow value The timestamp sent is more than 1000ms ahead
of the server time
Check that your system time is in sync. See this issue for some sample code to check the difference between your
local time and the Binance server time.
Q: Why do I get “Signature for this request is not valid”
A1: One of your parameters may not be in the correct format.
Check recvWindow is an integer and not a string.
A2: You may need to regenerate your API Key and Secret
A3: You may be attempting to access the API from a Chinese IP address, these are now restricted by Binance.
Q: Twisted won’t install using pip on Windows
A: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.

5.1.14 Changelog

v0.7.5.dev

Changed - Stock json lib to ujson (https://github.com/sammchardy/python-binance/pull/383)

v0.7.5 - 2020-02-06

Added
• Futures REST endpoints
• Lending REST endpoints
• OCO Orders function create_oco_order, order_oco_buy, order_oco_sell
• Average Price function get_avg_price
• Support for other domains (.us, .jp, etc)
Updated
• dependencies
Fixed
• websocket keepalive callback not found

v0.7.4 - 2019-09-22

Added
• symbol book ticker websocket streams
• margin websocket stream

30 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Updated
• can call Client without any params
• make response a property of the Client class so you can access response properties after a request
Fixed
• issue with None value params causing errors

v0.7.3 - 2019-08-12

Added
• sub account endpoints
• dust transfer endpoint
• asset divident history endpoint
Removed
• deprecated withdraw fee endpoint

v0.7.2 - 2019-08-01

Added
• margin trading endpoints
Fixed
• depth cache clearing bug

v0.7.1 - 2019-01-23

Added
• limit param to DepthCacheManager
• limit param to get_historical_klines
• update_time to DepthCache class
Updated
• test coverage
Fixed
• super init in Websocket class
• removal of request params from signature
• empty set issue in aggregate_trade_iter

5.1. Contents 31
python-binance Documentation, Release 0.2.0

v0.7.0 - 2018-08-08

Added
• get_asset_details endpoint
• get_dust_log endpoint
• get_trade_fee endpoint
• ability for multiple DepthCacheManagers to share a BinanceSocketManager
• get_historial_klines_generator function
• custom socket timeout param for BinanceSocketManager
Updated
• general dependency version
• removed support for python3.3
Fixed
• add a super init on BinanceClientProtocol

v0.6.9 - 2018-04-27

Added
• timestamp in milliseconds to get_historical_klines function
• timestamp in milliseconds to aggregate_trade_iter function
Fixed
• Don’t close user stream listen key on socket close

v0.6.8 - 2018-03-29

Added
• get_withdraw_fee function
Fixed
• Remove unused LISTENKEY_NOT_EXISTS
• Optimise the historical klines function to reduce requests
• Issue with end_time in aggregate trade iterator

v0.6.7 - 2018-03-14

Fixed
• Issue with get_historical_klines when response had exactly 500 results
• Changed BinanceResponseException to BinanceRequestException
• Set default code value in BinanceApiException properly

32 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

v0.6.6 - 2018-02-17

Fixed
• User stream websocket keep alive strategy updated

v0.6.5 - 2018-02-13

Fixed
• get_historical_klines response for month interval

v0.6.4 - 2018-02-09

Added
• system status endpoint get_system_status

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

New version because why not.


Added
• get_historical_klines function to fetch klines for any date range
• ability to override requests parameters globally
• error on websocket disconnect

5.1. Contents 33
python-binance Documentation, Release 0.2.0

• example related to blog post


Fixes
• documentation fixes

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

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

34 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

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

5.1. Contents 35
python-binance Documentation, Release 0.2.0

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

v0.5.1 - 2017-12-06

Added
• Close method for DepthCacheManager
Fixes
• Fixed modifying array error message when closing the BinanceSocketManager

36 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

v0.5.0 - 2017-12-05

Updating to match new API documentation


Added
• Recent trades endpoint
• Historical trades endpoint
• Order response type option
• Check for invalid user stream listen key in socket to keep connected
Fixes
• Fixed exchange info endpoint as it was renamed slightly

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

5.1. Contents 37
python-binance Documentation, Release 0.2.0

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

38 Chapter 5. Other Exchanges


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

5.1. Contents 39
python-binance Documentation, Release 0.2.0

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

40 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

5.1.15 Binance API

client module

class binance.client.Client(api_key=None, api_secret=None, requests_params=None,


tld=’com’)
Bases: object
AGG_BEST_MATCH = 'M'
AGG_BUYER_MAKES = 'm'
AGG_FIRST_TRADE_ID = 'f'
AGG_ID = 'a'
AGG_LAST_TRADE_ID = 'l'
AGG_PRICE = 'p'
AGG_QUANTITY = 'q'
AGG_TIME = 'T'
API_URL = 'https://api.binance.{}/api'
FUTURES_API_VERSION = 'v1'
FUTURES_URL = 'https://fapi.binance.{}/fapi'
KLINE_INTERVAL_12HOUR = '12h'
KLINE_INTERVAL_15MINUTE = '15m'
KLINE_INTERVAL_1DAY = '1d'
KLINE_INTERVAL_1HOUR = '1h'
KLINE_INTERVAL_1MINUTE = '1m'
KLINE_INTERVAL_1MONTH = '1M'
KLINE_INTERVAL_1WEEK = '1w'
KLINE_INTERVAL_2HOUR = '2h'
KLINE_INTERVAL_30MINUTE = '30m'
KLINE_INTERVAL_3DAY = '3d'
KLINE_INTERVAL_3MINUTE = '3m'
KLINE_INTERVAL_4HOUR = '4h'
KLINE_INTERVAL_5MINUTE = '5m'
KLINE_INTERVAL_6HOUR = '6h'
KLINE_INTERVAL_8HOUR = '8h'
MARGIN_API_URL = 'https://api.binance.{}/sapi'
MARGIN_API_VERSION = 'v1'
ORDER_RESP_TYPE_ACK = 'ACK'
ORDER_RESP_TYPE_FULL = 'FULL'
ORDER_RESP_TYPE_RESULT = 'RESULT'

5.1. Contents 41
python-binance Documentation, Release 0.2.0

ORDER_STATUS_CANCELED = 'CANCELED'
ORDER_STATUS_EXPIRED = 'EXPIRED'
ORDER_STATUS_FILLED = 'FILLED'
ORDER_STATUS_NEW = 'NEW'
ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED'
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.{}'
WITHDRAW_API_URL = 'https://api.binance.{}/wapi'
WITHDRAW_API_VERSION = 'v3'
__init__(api_key=None, api_secret=None, requests_params=None, tld=’com’)
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.

42 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

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
• symbol (str) – Symbol string e.g. ETHBTC
• start_str – Start date string in UTC format or timestamp in milliseconds. The iterator
will
return the first trade occurring later than this time. :type start_str: str|int :param last_id: aggregate
trade ID of the last known aggregate trade. Not a regular trade ID. See https://github.com/binance/
binance-spot-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list.
Returns an iterator of JSON objects, one per trade. The format of
each object is identical to Client.aggregate_trades().

cancel_margin_order(**params)
Cancel an active order for margin account.
Either orderId or origClientOrderId must be sent.
https://binance-docs.github.io/apidocs/spot/en/#margin-account-cancel-order-trade
Parameters
• symbol (str) – required
• isIsolated (str) – set to ‘TRUE’ for isolated margin (default ‘FALSE’)
• orderId (str) –
• origClientOrderId (str) –
• 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”, “orderId”: 28, “origClientOrderId”: “myOrder1”, “clien-
tOrderId”: “cancelMyOrder1”, “transactTime”: 1507725176595, “price”: “1.00000000”,
“origQty”: “10.00000000”, “executedQty”: “8.00000000”, “cummulativeQuoteQty”:
“8.00000000”, “status”: “CANCELED”, “timeInForce”: “GTC”, “type”: “LIMIT”,
“side”: “SELL”
}
Raises BinanceRequestException, BinanceAPIException
cancel_order(**params)
Cancel an active order. Either orderId or origClientOrderId must be sent.
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#cancel-order-trade
Parameters
• symbol (str) – required

5.1. Contents 43
python-binance Documentation, Release 0.2.0

• 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"
}

Raises BinanceRequestException, BinanceAPIException

change_fixed_activity_to_daily_position(**params)
Change Fixed/Activity Position to Daily Position
https://binance-docs.github.io/apidocs/spot/en/#change-fixed-activity-position-to-daily-position-user_
data
create_isolated_margin_account(**params)
Create isolated margin account for symbol
https://binance-docs.github.io/apidocs/spot/en/#create-isolated-margin-account-margin
Parameters
• base (str) – Base asset of symbol
• quote (str) – Quote asset of symbol

pair_details = client.create_isolated_margin_account(base='USDT', quote='BTC')

Returns API response

{
"success": true,
"symbol": "BTCUSDT"
}

Raises BinanceRequestException, BinanceAPIException

create_margin_loan(**params)
Apply for a loan in cross-margin or isolated-margin account.
https://binance-docs.github.io/apidocs/spot/en/#margin-account-borrow-margin
Parameters
• asset (str) – name of the asset
• amount (str) – amount to transfer
• isIsolated (str) – set to ‘TRUE’ for isolated margin (default ‘FALSE’)

44 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

• symbol (str) – Isolated margin symbol (default blank for cross-margin)


• recvWindow (int) – the number of milliseconds the request is valid for

transaction = client.margin_create_loan(asset='BTC', amount='1.1')

transaction = client.margin_create_loan(asset='BTC', amount='1.1',


isIsolated='TRUE', symbol='ETHBTC')

Returns API response

{
"tranId": 100000001
}

Raises BinanceRequestException, BinanceAPIException

create_margin_order(**params)
Post a new order for margin account.
https://binance-docs.github.io/apidocs/spot/en/#margin-account-new-order-trade
Parameters
• symbol (str) – required
• isIsolated (str) – set to ‘TRUE’ for isolated margin (default ‘FALSE’)
• side (str) – required
• type (str) – required
• quantity (decimal) – required
• price (str) – required
• stopPrice (str) – Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT,
and TAKE_PROFIT_LIMIT orders.
• timeInForce (str) – required if limit order GTC,IOC,FOK
• newClientOrderId (str) – A unique id for the order. Automatically generated if not
sent.
• icebergQty (str) – 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; MAR-
KET and LIMIT order types default to FULL, all other orders default to ACK.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
Response ACK:

{
"symbol": "BTCUSDT",
"orderId": 28,
"clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
"transactTime": 1507725176595
}

5.1. Contents 45
python-binance Documentation, Release 0.2.0

Response RESULT:

{
"symbol": "BTCUSDT",
"orderId": 28,
"clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
"transactTime": 1507725176595,
"price": "1.00000000",
"origQty": "10.00000000",
"executedQty": "10.00000000",
"cummulativeQuoteQty": "10.00000000",
"status": "FILLED",
"timeInForce": "GTC",
"type": "MARKET",
"side": "SELL"
}

Response FULL:

{
"symbol": "BTCUSDT",
"orderId": 28,
"clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
"transactTime": 1507725176595,
"price": "1.00000000",
"origQty": "10.00000000",
"executedQty": "10.00000000",
"cummulativeQuoteQty": "10.00000000",
"status": "FILLED",
"timeInForce": "GTC",
"type": "MARKET",
"side": "SELL",
"fills": [
{
"price": "4000.00000000",
"qty": "1.00000000",
"commission": "4.00000000",
"commissionAsset": "USDT"
},
{
"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"
},
{
(continues on next page)

46 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


"price": "3995.00000000",
"qty": "1.00000000",
"commission": "3.99500000",
"commissionAsset": "USDT"
}
]
}

Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOr-


derMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalExcep-
tion, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException

create_oco_order(**params)
Send in a new OCO order
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#new-oco-trade
Parameters
• symbol (str) – required
• listClientOrderId (str) – A unique id for the list order. Automatically generated
if not sent.
• side (str) – required
• quantity (decimal) – required
• limitClientOrderId (str) – A unique id for the limit order. Automatically gener-
ated if not sent.
• price (str) – required
• limitIcebergQty (decimal) – Used to make the LIMIT_MAKER leg an iceberg
order.
• stopClientOrderId (str) – A unique id for the stop order. Automatically generated
if not sent.
• stopPrice (str) – required
• stopLimitPrice (str) – If provided, stopLimitTimeInForce is required.
• stopIcebergQty (decimal) – Used with STOP_LOSS_LIMIT leg to make an ice-
berg order.
• stopLimitTimeInForce (str) – Valid values are GTC/FOK/IOC.
• 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
Response ACK:

{
}

Response RESULT:

5.1. Contents 47
python-binance Documentation, Release 0.2.0

{
}

Response FULL:

{
}

Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOr-


derMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalExcep-
tion, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException

create_order(**params)
Send in a new order
Any order with an icebergQty MUST have timeInForce set to GTC.
https://github.com/binance/binance-spot-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
• quoteOrderQty (decimal) – amount the user wants to spend (when buying) or re-
ceive (when selling) of the quote asset, applicable to MARKET orders
• price (str) – required
• 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
Response ACK:

{
"symbol":"LTCBTC",
"orderId": 1,
"clientOrderId": "myOrder1" # Will be newClientOrderId
"transactTime": 1499827319559
}

Response RESULT:

48 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

{
"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"
},
{
"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",
(continues on next page)

5.1. Contents 49
python-binance Documentation, Release 0.2.0

(continued from previous page)


"commissionAsset": "USDT"
}
]
}

Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOr-


derMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalExcep-
tion, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException

create_sub_account_futures_transfer(**params)
Execute sub-account Futures transfer
https://github.com/binance-exchange/binance-official-api-docs/blob/9dbe0e961b80557bb19708a707c7fad08842b28e/
wapi-api.md#sub-account-transferfor-master-account
Parameters
• fromEmail (str) – required - Sender email
• toEmail (str) – required - Recipient email
• futuresType (int) – required
• asset (str) – required
• amount (decimal) – required
• recvWindow (int) – optional
Returns API response

{
"success":true,
"txnId":"2934662589"
}

Raises BinanceRequestException, BinanceAPIException

create_sub_account_transfer(**params)
Execute sub-account transfer
https://binance-docs.github.io/apidocs/spot/en/#sub-account-spot-asset-transfer-for-master-account
Parameters
• fromEmail (str) – required - Sender email
• toEmail (str) – required - Recipient email
• asset (str) – required
• amount (decimal) – required
• recvWindow (int) – optional
Returns API response

{
"success":true,
"txnId":"2966662589"
}

50 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Raises BinanceRequestException, BinanceAPIException

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/binance-spot-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
Returns API response

{}

Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOr-


derMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalExcep-
tion, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException

enable_subaccount_futures(**params)
Enable Futures for Sub-account (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#enable-futures-for-sub-account-for-master-account
Parameters
• email (str) – required - Sub account email
• recvWindow (int) – optional
Returns API response

"email":"[email protected]",

"isFuturesEnabled": true // true or false

Raises BinanceRequestException, BinanceAPIException

5.1. Contents 51
python-binance Documentation, Release 0.2.0

enable_subaccount_margin(**params)
Enable Margin for Sub-account (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#enable-margin-for-sub-account-for-master-account
Parameters
• email (str) – required - Sub account email
• recvWindow (int) – optional
Returns API response

"email":"[email protected]",

"isMarginEnabled": true

Raises BinanceRequestException, BinanceAPIException

futures_account(**params)
Get current account information.
https://binance-docs.github.io/apidocs/futures/en/#account-information-user_data
futures_account_balance(**params)
Get futures account balance
https://binance-docs.github.io/apidocs/futures/en/#future-account-balance-user_data
futures_account_trades(**params)
Get trades for the authenticated account and symbol.
https://binance-docs.github.io/apidocs/futures/en/#account-trade-list-user_data
futures_account_transfer(**params)
Execute transfer between spot account and futures account.
https://binance-docs.github.io/apidocs/futures/en/#new-future-account-transfer
futures_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://binance-docs.github.io/apidocs/futures/en/#compressed-aggregate-trades-list-market_data
futures_cancel_all_open_orders(**params)
Cancel all open futures orders
https://binance-docs.github.io/apidocs/futures/en/#cancel-all-open-orders-trade
futures_cancel_order(**params)
Cancel an active futures order.
https://binance-docs.github.io/apidocs/futures/en/#cancel-order-trade
futures_cancel_orders(**params)
Cancel multiple futures orders
https://binance-docs.github.io/apidocs/futures/en/#cancel-multiple-orders-trade

52 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

futures_change_leverage(**params)
Change user’s initial leverage of specific symbol market
https://binance-docs.github.io/apidocs/futures/en/#change-initial-leverage-trade
futures_change_margin_type(**params)
Change the margin type for a symbol
https://binance-docs.github.io/apidocs/futures/en/#change-margin-type-trade
futures_change_position_margin(**params)
Change the position margin for a symbol
https://binance-docs.github.io/apidocs/futures/en/#modify-isolated-position-margin-trade
futures_change_position_mode(**params)
Change position mode for authenticated account
https://binance-docs.github.io/apidocs/futures/en/#change-position-mode-trade
futures_create_order(**params)
Send in a new order.
https://binance-docs.github.io/apidocs/futures/en/#new-order-trade
futures_exchange_info()
Current exchange trading rules and symbol information
https://binance-docs.github.io/apidocs/futures/en/#exchange-information-market_data
futures_funding_rate(**params)
Get funding rate history
https://binance-docs.github.io/apidocs/futures/en/#get-funding-rate-history-market_data
futures_get_all_orders(**params)
Get all futures account orders; active, canceled, or filled.
https://binance-docs.github.io/apidocs/futures/en/#all-orders-user_data
futures_get_open_orders(**params)
Get all open orders on a symbol.
https://binance-docs.github.io/apidocs/futures/en/#current-open-orders-user_data
futures_get_order(**params)
Check an order’s status.
https://binance-docs.github.io/apidocs/futures/en/#query-order-user_data
futures_get_position_mode(**params)
Get position mode for authenticated account
https://binance-docs.github.io/apidocs/futures/en/#get-current-position-mode-user_data
futures_historical_trades(**params)
Get older market historical trades.
https://binance-docs.github.io/apidocs/futures/en/#old-trades-lookup-market_data
futures_income_history(**params)
Get income history for authenticated account
https://binance-docs.github.io/apidocs/futures/en/#get-income-history-user_data

5.1. Contents 53
python-binance Documentation, Release 0.2.0

futures_klines(**params)
Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
https://binance-docs.github.io/apidocs/futures/en/#kline-candlestick-data-market_data
futures_leverage_bracket(**params)
Notional and Leverage Brackets
https://binance-docs.github.io/apidocs/futures/en/#notional-and-leverage-brackets-market_data
futures_liquidation_orders(**params)
Get all liquidation orders
https://binance-docs.github.io/apidocs/futures/en/#get-all-liquidation-orders-market_data
futures_mark_price(**params)
Get Mark Price and Funding Rate
https://binance-docs.github.io/apidocs/futures/en/#mark-price-market_data
futures_open_interest(**params)
Get present open interest of a specific symbol.
https://binance-docs.github.io/apidocs/futures/en/#open-interest-market_data
futures_order_book(**params)
Get the Order Book for the market
https://binance-docs.github.io/apidocs/futures/en/#order-book-market_data
futures_orderbook_ticker(**params)
Best price/qty on the order book for a symbol or symbols.
https://binance-docs.github.io/apidocs/futures/en/#symbol-order-book-ticker-market_data
futures_ping()
Test connectivity to the Rest API
https://binance-docs.github.io/apidocs/futures/en/#test-connectivity
futures_position_information(**params)
Get position information
https://binance-docs.github.io/apidocs/futures/en/#position-information-user_data
futures_position_margin_history(**params)
Get position margin change history
https://binance-docs.github.io/apidocs/futures/en/#get-postion-margin-change-history-trade
futures_recent_trades(**params)
Get recent trades (up to last 500).
https://binance-docs.github.io/apidocs/futures/en/#recent-trades-list-market_data
futures_symbol_ticker(**params)
Latest price for a symbol or symbols.
https://binance-docs.github.io/apidocs/futures/en/#symbol-price-ticker-market_data
futures_ticker(**params)
24 hour rolling window price change statistics.
https://binance-docs.github.io/apidocs/futures/en/#24hr-ticker-price-change-statistics-market_data

54 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

futures_time()
Test connectivity to the Rest API and get the current server time.
https://binance-docs.github.io/apidocs/futures/en/#check-server-time
get_account(**params)
Get current account information.
https://github.com/binance/binance-spot-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"
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_account_status(**params)
Get account status detail.
https://binance-docs.github.io/apidocs/spot/en/#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"
]
}

Raises BinanceWithdrawException

5.1. Contents 55
python-binance Documentation, Release 0.2.0

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/binance-spot-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?
}
]

Raises BinanceRequestException, BinanceAPIException

get_all_isolated_margin_symbols(**params)
Query isolated margin symbol info for all pairs
https://binance-docs.github.io/apidocs/spot/en/#get-all-isolated-margin-symbol-user_data

pair_details = client.get_all_isolated_margin_symbols()

Returns API response

[
{
"base": "BNB",
"isBuyAllowed": true,
"isMarginTrade": true,
"isSellAllowed": true,
"quote": "BTC",
"symbol": "BNBBTC"
},
{
"base": "TRX",
"isBuyAllowed": true,
"isMarginTrade": true,
"isSellAllowed": true,
(continues on next page)

56 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


"quote": "BTC",
"symbol": "TRXBTC"
}
]

Raises BinanceRequestException, BinanceAPIException

get_all_margin_orders(**params)
Query all margin accounts orders
If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.
For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.
https://binance-docs.github.io/apidocs/spot/en/#query-margin-account-39-s-all-order-user_data
Parameters
• symbol (str) – required
• isIsolated (str) – set to ‘TRUE’ for isolated margin (default ‘FALSE’)
• orderId (str) – optional
• startTime (str) – optional
• endTime (str) – optional
• limit (int) – Default 500; max 1000
• recvWindow (int) – the number of milliseconds the request is valid for
Returns
API response
[
{ “id”: 43123876, “price”: “0.00395740”, “qty”: “4.06000000”, “quoteQty”:
“0.01606704”, “symbol”: “BNBBTC”, “time”: 1556089977693
}, {
”id”: 43123877, “price”: “0.00395740”, “qty”: “0.77000000”, “quoteQty”:
“0.00304719”, “symbol”: “BNBBTC”, “time”: 1556089977693
}, {
”id”: 43253549, “price”: “0.00428930”, “qty”: “23.30000000”, “quoteQty”:
“0.09994069”, “symbol”: “BNBBTC”, “time”: 1556163963504
}
]
Raises BinanceRequestException, BinanceAPIException
get_all_orders(**params)
Get all account orders; active, canceled, or filled.
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#all-orders-user_data
Parameters
• symbol (str) – required

5.1. Contents 57
python-binance Documentation, Release 0.2.0

• 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
}
]

Raises BinanceRequestException, BinanceAPIException

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"
}
]

Raises BinanceRequestException, BinanceAPIException

get_asset_balance(asset, **params)
Get current asset balance.
https://github.com/binance/binance-spot-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

58 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

{
"asset": "BTC",
"free": "4723846.89208129",
"locked": "0.00000000"
}

Raises BinanceRequestException, BinanceAPIException

get_asset_details(**params)
Fetch details on assets.
https://binance-docs.github.io/apidocs/spot/en/#asset-detail-user_data
Parameters recvWindow (int) – the number of milliseconds the request is valid for
Returns API response

{
"success": true,
"assetDetail": {
"CTR": {
"minWithdrawAmount": "70.00000000", //min withdraw amount
"depositStatus": false,//deposit status
"withdrawFee": 35, // withdraw fee
"withdrawStatus": true, //withdraw status
"depositTip": "Delisted, Deposit Suspended" //reason
},
"SKY": {
"minWithdrawAmount": "0.02000000",
"depositStatus": true,
"withdrawFee": 0.01,
"withdrawStatus": true
}
}
}

Raises BinanceWithdrawException

get_asset_dividend_history(**params)
Query asset dividend record.
https://binance-docs.github.io/apidocs/spot/en/#asset-dividend-record-user_data
Parameters
• asset (str) – optional
• startTime (long) – optional
• endTime (long) – optional
• recvWindow (int) – the number of milliseconds the request is valid for

result = client.get_asset_dividend_history()

Returns API response

5.1. Contents 59
python-binance Documentation, Release 0.2.0

{
"rows":[
{
"amount":"10.00000000",
"asset":"BHFT",
"divTime":1563189166000,
"enInfo":"BHFT distribution",
"tranId":2968885920
},
{
"amount":"10.00000000",
"asset":"BHFT",
"divTime":1563189165000,
"enInfo":"BHFT distribution",
"tranId":2968885920
}
],
"total":2
}

Raises BinanceRequestException, BinanceAPIException

get_avg_price(**params)
Current average price for a symbol.
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#current-average-price
Parameters symbol (str) –
Returns API response

{
"mins": 5,
"price": "9.35751834"
}

get_bnb_burn_spot_margin(**params)
Get BNB Burn Status
https://binance-docs.github.io/apidocs/spot/en/#get-bnb-burn-status-user_data

status = client.get_bnb_burn_spot_margin()

Returns API response

{
"spotBNBBurn":true,
"interestBNBBurn": false
}

Raises BinanceRequestException, BinanceAPIException

get_deposit_address(**params)
Fetch a deposit address for a symbol
https://www.binance.com/restapipub.html

60 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

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"
}

Raises BinanceRequestException, BinanceAPIException

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
}

Raises BinanceRequestException, BinanceAPIException

get_dust_log(**params)
Get log of small amounts exchanged for BNB.
https://binance-docs.github.io/apidocs/spot/en/#dustlog-user_data
Parameters recvWindow (int) – the number of milliseconds the request is valid for
Returns API response

{
"success": true,
"results": {
"total": 2, //Total counts of exchange
(continues on next page)

5.1. Contents 61
python-binance Documentation, Release 0.2.0

(continued from previous page)


"rows": [
{
"transfered_total": "0.00132256", # Total transfered BNB
˓→amount for this exchange.

"service_charge_total": "0.00002699", # Total service


˓→charge amount for this exchange.

"tran_id": 4359321,
"logs": [ # Details of this exchange.
{
"tranId": 4359321,
"serviceChargeAmount": "0.000009",
"uid": "10000015",
"amount": "0.0009",
"operateTime": "2018-05-03 17:07:04",
"transferedAmount": "0.000441",
"fromAsset": "USDT"
},
{
"tranId": 4359321,
"serviceChargeAmount": "0.00001799",
"uid": "10000015",
"amount": "0.0009",
"operateTime": "2018-05-03 17:07:04",
"transferedAmount": "0.00088156",
"fromAsset": "ETH"
}
],
"operate_time": "2018-05-03 17:07:04" //The time of this
˓→exchange.

},
{
"transfered_total": "0.00058795",
"service_charge_total": "0.000012",
"tran_id": 4357015,
"logs": [ // Details of this exchange.
{
"tranId": 4357015,
"serviceChargeAmount": "0.00001",
"uid": "10000015",
"amount": "0.001",
"operateTime": "2018-05-02 13:52:24",
"transferedAmount": "0.00049",
"fromAsset": "USDT"
},
{
"tranId": 4357015,
"serviceChargeAmount": "0.000002",
"uid": "10000015",
"amount": "0.0001",
"operateTime": "2018-05-02 13:51:11",
"transferedAmount": "0.00009795",
"fromAsset": "ETH"
}
],
"operate_time": "2018-05-02 13:51:11"
}
]
(continues on next page)

62 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


}
}

Raises BinanceWithdrawException

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"
}
(continues on next page)

5.1. Contents 63
python-binance Documentation, Release 0.2.0

(continued from previous page)


]
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_fixed_activity_project_list(**params)
Get Fixed and Activity Project List
https://binance-docs.github.io/apidocs/spot/en/#get-fixed-and-activity-project-list-user_data
Parameters asset – optional
Returns API response

[
{
"asset": "USDT",
"displayPriority": 1,
"duration": 90,
"interestPerLot": "1.35810000",
"interestRate": "0.05510000",
"lotSize": "100.00000000",
"lotsLowLimit": 1,
"lotsPurchased": 74155,
"lotsUpLimit": 80000,
"maxLotsPerUser": 2000,
"needKyc": False,
"projectId": "CUSDT90DAYSS001",
"projectName": "USDT",
"status": "PURCHASING",
"type": "CUSTOMIZED_FIXED",
"withAreaLimitation": False
}
]

Raises BinanceRequestException, BinanceAPIException

get_historical_klines(symbol, interval, start_str, end_str=None, limit=500)


Get Historical Klines from Binance
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
• symbol (str) – Name of symbol pair e.g BNBBTC
• interval (str) – Binance Kline interval
• start_str (str|int) – Start date string in UTC format or timestamp in milliseconds
• end_str (str|int) – optional - end date string in UTC format or timestamp in mil-
liseconds (default will fetch everything up to now)
• limit (int) – Default 500; max 1000.
Returns list of OHLCV values

64 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

get_historical_klines_generator(symbol, interval, start_str, end_str=None)


Get Historical Klines from Binance
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
• symbol (str) – Name of symbol pair e.g BNBBTC
• interval (str) – Binance Kline interval
• start_str (str|int) – Start date string in UTC format or timestamp in milliseconds
• end_str (str|int) – optional - end date string in UTC format or timestamp in mil-
liseconds (default will fetch everything up to now)
Returns generator of OHLCV values
get_historical_trades(**params)
Get older trades.
https://github.com/binance/binance-spot-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
}
]

Raises BinanceRequestException, BinanceAPIException

get_isolated_margin_account(**params)
Query isolated margin account details
https://binance-docs.github.io/apidocs/spot/en/#query-isolated-margin-account-info-user_data
Parameters symbols – optional up to 5 margin pairs as a comma separated string

account_info = client.get_isolated_margin_account()
account_info = client.get_isolated_margin_account(symbols="BTCUSDT,ETHUSDT")

Returns API response

5.1. Contents 65
python-binance Documentation, Release 0.2.0

If "symbols" is not sent:

{
"assets":[
{
"baseAsset":
{
"asset": "BTC",
"borrowEnabled": true,
"borrowed": "0.00000000",
"free": "0.00000000",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00000000",
"netAssetOfBtc": "0.00000000",
"repayEnabled": true,
"totalAsset": "0.00000000"
},
"quoteAsset":
{
"asset": "USDT",
"borrowEnabled": true,
"borrowed": "0.00000000",
"free": "0.00000000",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00000000",
"netAssetOfBtc": "0.00000000",
"repayEnabled": true,
"totalAsset": "0.00000000"
},
"symbol": "BTCUSDT"
"isolatedCreated": true,
"marginLevel": "0.00000000",
"marginLevelStatus": "EXCESSIVE", // "EXCESSIVE", "NORMAL",
˓→"MARGIN_CALL", "PRE_LIQUIDATION", "FORCE_LIQUIDATION"

"marginRatio": "0.00000000",
"indexPrice": "10000.00000000"
"liquidatePrice": "1000.00000000",
"liquidateRate": "1.00000000"
"tradeEnabled": true
}
],
"totalAssetOfBtc": "0.00000000",
"totalLiabilityOfBtc": "0.00000000",
"totalNetAssetOfBtc": "0.00000000"
}

If "symbols" is sent:

{
"assets":[
{
"baseAsset":
{
"asset": "BTC",
"borrowEnabled": true,
(continues on next page)

66 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


"borrowed": "0.00000000",
"free": "0.00000000",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00000000",
"netAssetOfBtc": "0.00000000",
"repayEnabled": true,
"totalAsset": "0.00000000"
},
"quoteAsset":
{
"asset": "USDT",
"borrowEnabled": true,
"borrowed": "0.00000000",
"free": "0.00000000",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00000000",
"netAssetOfBtc": "0.00000000",
"repayEnabled": true,
"totalAsset": "0.00000000"
},
"symbol": "BTCUSDT"
"isolatedCreated": true,
"marginLevel": "0.00000000",
"marginLevelStatus": "EXCESSIVE", // "EXCESSIVE", "NORMAL",
˓→"MARGIN_CALL", "PRE_LIQUIDATION", "FORCE_LIQUIDATION"

"marginRatio": "0.00000000",
"indexPrice": "10000.00000000"
"liquidatePrice": "1000.00000000",
"liquidateRate": "1.00000000"
"tradeEnabled": true
}
]
}

get_isolated_margin_symbol(**params)
Query isolated margin symbol info
https://binance-docs.github.io/apidocs/spot/en/#query-isolated-margin-symbol-user_data
Parameters symbol (str) – name of the symbol pair

pair_details = client.get_isolated_margin_symbol(symbol='BTCUSDT')

Returns API response

{
"symbol":"BTCUSDT",
"base":"BTC",
"quote":"USDT",
"isMarginTrade":true,
"isBuyAllowed":true,
"isSellAllowed":true
}

5.1. Contents 67
python-binance Documentation, Release 0.2.0

Raises BinanceRequestException, BinanceAPIException

get_klines(**params)
Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
https://github.com/binance/binance-spot-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
]
]

Raises BinanceRequestException, BinanceAPIException

get_lending_account(**params)
Get Lending Account Details
https://binance-docs.github.io/apidocs/spot/en/#lending-account-user_data
get_lending_daily_quota_left(**params)
Get Left Daily Purchase Quota of Flexible Product.
https://binance-docs.github.io/apidocs/spot/en/#get-left-daily-purchase-quota-of-flexible-product-user_
data
get_lending_daily_redemption_quota(**params)
Get Left Daily Redemption Quota of Flexible Product
https://binance-docs.github.io/apidocs/spot/en/#get-left-daily-redemption-quota-of-flexible-product-user_
data
get_lending_interest_history(**params)
Get Lending Interest History

68 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

https://binance-docs.github.io/apidocs/spot/en/#get-interest-history-user_data-2
get_lending_position(**params)
Get Flexible Product Position
https://binance-docs.github.io/apidocs/spot/en/#get-flexible-product-position-user_data
get_lending_product_list(**params)
Get Lending Product List
https://binance-docs.github.io/apidocs/spot/en/#get-flexible-product-list-user_data
get_lending_purchase_history(**params)
Get Lending Purchase History
https://binance-docs.github.io/apidocs/spot/en/#get-purchase-record-user_data
get_lending_redemption_history(**params)
Get Lending Redemption History
https://binance-docs.github.io/apidocs/spot/en/#get-redemption-record-user_data
get_margin_account(**params)
Query cross-margin account details
https://binance-docs.github.io/apidocs/spot/en/#query-cross-margin-account-details-user_data
Returns API response
{
"borrowEnabled": true,
"marginLevel": "11.64405625",
"totalAssetOfBtc": "6.82728457",
"totalLiabilityOfBtc": "0.58633215",
"totalNetAssetOfBtc": "6.24095242",
"tradeEnabled": true,
"transferEnabled": true,
"userAssets": [
{
"asset": "BTC",
"borrowed": "0.00000000",
"free": "0.00499500",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00499500"
},
{
"asset": "BNB",
"borrowed": "201.66666672",
"free": "2346.50000000",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "2144.83333328"
},
{
"asset": "ETH",
"borrowed": "0.00000000",
"free": "0.00000000",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00000000"
},
(continues on next page)

5.1. Contents 69
python-binance Documentation, Release 0.2.0

(continued from previous page)


{
"asset": "USDT",
"borrowed": "0.00000000",
"free": "0.00000000",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00000000"
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_margin_asset(**params)
Query cross-margin asset
https://binance-docs.github.io/apidocs/spot/en/#query-margin-asset-market_data
Parameters asset (str) – name of the asset

asset_details = client.get_margin_asset(asset='BNB')

Returns API response

{
"assetFullName": "Binance Coin",
"assetName": "BNB",
"isBorrowable": false,
"isMortgageable": true,
"userMinBorrow": "0.00000000",
"userMinRepay": "0.00000000"
}

Raises BinanceRequestException, BinanceAPIException

get_margin_loan_details(**params)
Query loan record
txId or startTime must be sent. txId takes precedence.
https://binance-docs.github.io/apidocs/spot/en/#query-loan-record-user_data
Parameters
• asset (str) – required
• isolatedSymbol (str) – isolated symbol (if querying isolated margin)
• txId (str) – the tranId in of the created loan
• startTime (str) – earliest timestamp to filter transactions
• endTime (str) – Used to uniquely identify this cancel. Automatically generated by
default.
• current (str) – Currently querying page. Start from 1. Default:1
• size (int) – Default:10 Max:100

70 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

• recvWindow (int) – the number of milliseconds the request is valid for


Returns
API response
{
“rows”: [
{ “asset”: “BNB”, “principal”: “0.84624403”, “timestamp”: 1555056425000, //one
of PENDING (pending to execution), CONFIRMED (successfully loaned), FAILED
(execution failed, nothing happened to your account); “status”: “CONFIRMED”
}
], “total”: 1
}
Raises BinanceRequestException, BinanceAPIException
get_margin_order(**params)
Query margin accounts order
Either orderId or origClientOrderId must be sent.
For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this
time.
https://binance-docs.github.io/apidocs/spot/en/#query-margin-account-39-s-order-user_data
Parameters
• symbol (str) – required
• isIsolated (str) – set to ‘TRUE’ for isolated margin (default ‘FALSE’)
• orderId (str) –
• origClientOrderId (str) –
• recvWindow (int) – the number of milliseconds the request is valid for
Returns
API response
{ “clientOrderId”: “ZwfQzuDIGpceVhKW5DvCmO”, “cummulativeQuoteQty”:
“0.00000000”, “executedQty”: “0.00000000”, “icebergQty”: “0.00000000”,
“isWorking”: true, “orderId”: 213205622, “origQty”: “0.30000000”, “price”:
“0.00493630”, “side”: “SELL”, “status”: “NEW”, “stopPrice”: “0.00000000”,
“symbol”: “BNBBTC”, “time”: 1562133008725, “timeInForce”: “GTC”, “type”:
“LIMIT”, “updateTime”: 1562133008725
}
Raises BinanceRequestException, BinanceAPIException
get_margin_price_index(**params)
Query margin priceIndex
https://binance-docs.github.io/apidocs/spot/en/#query-margin-priceindex-market_data
Parameters symbol (str) – name of the symbol pair

5.1. Contents 71
python-binance Documentation, Release 0.2.0

price_index_details = client.get_margin_price_index(symbol='BTCUSDT')

Returns API response

{
"calcTime": 1562046418000,
"price": "0.00333930",
"symbol": "BNBBTC"
}

Raises BinanceRequestException, BinanceAPIException

get_margin_repay_details(**params)
Query repay record
txId or startTime must be sent. txId takes precedence.
https://binance-docs.github.io/apidocs/spot/en/#query-repay-record-user_data
Parameters
• asset (str) – required
• isolatedSymbol (str) – isolated symbol (if querying isolated margin)
• txId (str) – the tranId in of the created loan
• startTime (str) –
• endTime (str) – Used to uniquely identify this cancel. Automatically generated by
default.
• current (str) – Currently querying page. Start from 1. Default:1
• size (int) – Default:10 Max:100
• recvWindow (int) – the number of milliseconds the request is valid for
Returns
API response
{
“rows”: [
{ //Total amount repaid “amount”: “14.00000000”, “asset”: “BNB”, //Interest re-
paid “interest”: “0.01866667”, //Principal repaid “principal”: “13.98133333”,
//one of PENDING (pending to execution), CONFIRMED (successfully loaned),
FAILED (execution failed, nothing happened to your account); “status”: “CON-
FIRMED”, “timestamp”: 1563438204000, “txId”: 2970933056
}
], “total”: 1
}
Raises BinanceRequestException, BinanceAPIException
get_margin_symbol(**params)
Query cross-margin symbol info
https://binance-docs.github.io/apidocs/spot/en/#query-cross-margin-pair-market_data

72 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Parameters symbol (str) – name of the symbol pair

pair_details = client.get_margin_symbol(symbol='BTCUSDT')

Returns API response

{
"id":323355778339572400,
"symbol":"BTCUSDT",
"base":"BTC",
"quote":"USDT",
"isMarginTrade":true,
"isBuyAllowed":true,
"isSellAllowed":true
}

Raises BinanceRequestException, BinanceAPIException

get_margin_trades(**params)
Query margin accounts trades
If fromId is set, it will get orders >= that fromId. Otherwise most recent orders are returned.
https://binance-docs.github.io/apidocs/spot/en/#query-margin-account-39-s-trade-list-user_data
Parameters
• symbol (str) – required
• isIsolated (str) – set to ‘TRUE’ for isolated margin (default ‘FALSE’)
• fromId (str) – optional
• startTime (str) – optional
• endTime (str) – optional
• limit (int) – Default 500; max 1000
• recvWindow (int) – the number of milliseconds the request is valid for
Returns
API response
[
{ “commission”: “0.00006000”, “commissionAsset”: “BTC”, “id”: 34, “is-
BestMatch”: true, “isBuyer”: false, “isMaker”: false, “orderId”: 39324,
“price”: “0.02000000”, “qty”: “3.00000000”, “symbol”: “BNBBTC”, “time”:
1561973357171
}, { “commission”: “0.00002950”, “commissionAsset”: “BTC”, “id”: 32, “is-
BestMatch”: true, “isBuyer”: false, “isMaker”: true, “orderId”: 39319,
“price”: “0.00590000”, “qty”: “5.00000000”, “symbol”: “BNBBTC”, “time”:
1561964645345
}
]
Raises BinanceRequestException, BinanceAPIException

5.1. Contents 73
python-binance Documentation, Release 0.2.0

get_max_margin_loan(**params)
Query max borrow amount for an asset
https://binance-docs.github.io/apidocs/spot/en/#query-max-borrow-user_data
Parameters
• asset (str) – required
• isolatedSymbol (str) – isolated symbol (if querying isolated margin)
• recvWindow (int) – the number of milliseconds the request is valid for
Returns
API response
{ “amount”: “1.69248805”
}
Raises BinanceRequestException, BinanceAPIException
get_max_margin_transfer(**params)
Query max transfer-out amount
https://binance-docs.github.io/apidocs/spot/en/#query-max-transfer-out-amount-user_data
Parameters
• asset (str) – required
• isolatedSymbol (str) – isolated symbol (if querying isolated margin)
• recvWindow (int) – the number of milliseconds the request is valid for
Returns
API response
{ “amount”: “3.59498107”
}
Raises BinanceRequestException, BinanceAPIException
get_my_trades(**params)
Get trades for a specific symbol.
https://github.com/binance/binance-spot-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",
(continues on next page)

74 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


"commission": "10.10000000",
"commissionAsset": "BNB",
"time": 1499865549590,
"isBuyer": true,
"isMaker": false,
"isBestMatch": true
}
]

Raises BinanceRequestException, BinanceAPIException

get_open_margin_orders(**params)
Query margin accounts open orders
If the symbol is not sent, orders for all symbols will be returned in an array (cross-margin only).
If querying isolated margin orders, both the isIsolated=’TRUE’ and symbol=symbol_name must be set.
When all symbols are returned, the number of requests counted against the rate limiter is equal to the
number of symbols currently trading on the exchange.
https://binance-docs.github.io/apidocs/spot/en/#query-margin-account-39-s-open-order-user_data
Parameters
• symbol (str) – optional
• isIsolated (str) – set to ‘TRUE’ for isolated margin (default ‘FALSE’)
• recvWindow (int) – the number of milliseconds the request is valid for
Returns
API response
[
{ “clientOrderId”: “qhcZw71gAkCCTv0t0k8LUK”, “cummulativeQuoteQty”:
“0.00000000”, “executedQty”: “0.00000000”, “icebergQty”: “0.00000000”,
“isWorking”: true, “orderId”: 211842552, “origQty”: “0.30000000”, “price”:
“0.00475010”, “side”: “SELL”, “status”: “NEW”, “stopPrice”: “0.00000000”,
“symbol”: “BNBBTC”, “time”: 1562040170089, “timeInForce”: “GTC”, “type”:
“LIMIT”, “updateTime”: 1562040170089
}
]
Raises BinanceRequestException, BinanceAPIException
get_open_orders(**params)
Get all open orders on a symbol.
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#current-open-orders-user_
data
Parameters
• symbol (str) – optional
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response

5.1. Contents 75
python-binance Documentation, Release 0.2.0

[
{
"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
}
]

Raises BinanceRequestException, BinanceAPIException

get_order(**params)
Check an order’s status. Either orderId or origClientOrderId must be sent.
https://github.com/binance/binance-spot-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
}

Raises BinanceRequestException, BinanceAPIException

get_order_book(**params)
Get the Order Book for the market
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#order-book

76 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Parameters
• symbol (str) – required
• limit (int) – Default 100; max 1000
Returns API response

{
"lastUpdateId": 1027024,
"bids": [
[
"4.00000000", # PRICE
"431.00000000", # QTY
[] # Can be ignored
]
],
"asks": [
[
"4.00000200",
"12.00000000",
[]
]
]
}

Raises BinanceRequestException, BinanceAPIException

get_orderbook_ticker(**params)
Latest price for a symbol or symbols.
https://github.com/binance/binance-spot-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",
"askPrice": "4.00000200",
"askQty": "9.00000000"
},
{
"symbol": "ETHBTC",
"bidPrice": "0.07946700",
"bidQty": "9.00000000",
(continues on next page)

5.1. Contents 77
python-binance Documentation, Release 0.2.0

(continued from previous page)


"askPrice": "100000.00000000",
"askQty": "1000.00000000"
}
]

Raises BinanceRequestException, BinanceAPIException

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"
}
]

Raises BinanceRequestException, BinanceAPIException

get_products()
Return list of products currently listed on Binance
Use get_exchange_info() call instead
Returns list - List of product dictionaries
Raises BinanceRequestException, BinanceAPIException
get_recent_trades(**params)
Get recent trades (up to last 500).
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#recent-trades-list
Parameters
• symbol (str) – required
• limit (int) – Default 500; max 500.
Returns API response
[
{
"id": 28457,
"price": "4.00000100",
(continues on next page)

78 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


"qty": "12.00000000",
"time": 1499865549590,
"isBuyerMaker": true,
"isBestMatch": true
}
]

Raises BinanceRequestException, BinanceAPIException

get_server_time()
Test connectivity to the Rest API and get the current server time.
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#check-server-time
Returns Current server time
{
"serverTime": 1499827319559
}

Raises BinanceRequestException, BinanceAPIException

get_sub_account_assets(**params)
Fetch sub-account assets
https://binance-docs.github.io/apidocs/spot/en/#query-sub-account-assets-for-master-account
Parameters
• email (str) – required
• symbol (str) – optional
• recvWindow (int) – optional
Returns API response
{
"success":true,
"balances":[
{
"asset":"ADA",
"free":10000,
"locked":0
},
{
"asset":"BNB",
"free":10003,
"locked":0
},
{
"asset":"BTC",
"free":11467.6399,
"locked":0
},
{
"asset":"ETH",
"free":10004.995,
(continues on next page)

5.1. Contents 79
python-binance Documentation, Release 0.2.0

(continued from previous page)


"locked":0
},
{
"asset":"USDT",
"free":11652.14213,
"locked":0
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_sub_account_futures_transfer_history(**params)
Query Sub-account Futures Transfer History.
https://binance-docs.github.io/apidocs/spot/en/#query-sub-account-futures-asset-transfer-history-for-master-account
Parameters
• email (str) – required
• futuresType (int) – required
• startTime (int) – optional
• endTime (int) – optional
• page (int) – optional
• limit (int) – optional
• recvWindow (int) – optional
Returns API response

{
"success":true,
"futuresType": 2,
"transfers":[
{
"from":"[email protected]",
"to":"[email protected]",
"asset":"BTC",
"qty":"1",
"time":1544433328000
},
{
"from":"[email protected]",
"to":"[email protected]",
"asset":"ETH",
"qty":"2",
"time":1544433328000
}
]
}

Raises BinanceRequestException, BinanceAPIException

80 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

get_sub_account_list(**params)
Query Sub-account List.
https://binance-docs.github.io/apidocs/spot/en/#query-sub-account-list-for-master-account
Parameters
• email (str) – optional
• startTime (int) – optional
• endTime (int) – optional
• page (int) – optional
• limit (int) – optional
• recvWindow (int) – optional
Returns API response

{
"success":true,
"subAccounts":[
{
"email":"[email protected]",
"status":"enabled",
"activated":true,
"mobile":"91605290",
"gAuth":true,
"createTime":1544433328000
},
{
"email":"[email protected]",
"status":"disabled",
"activated":true,
"mobile":"22501238",
"gAuth":true,
"createTime":1544433328000
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_sub_account_transfer_history(**params)
Query Sub-account Transfer History.
https://binance-docs.github.io/apidocs/spot/en/#query-sub-account-spot-asset-transfer-history-for-master-account
Parameters
• email (str) – required
• startTime (int) – optional
• endTime (int) – optional
• page (int) – optional
• limit (int) – optional
• recvWindow (int) – optional

5.1. Contents 81
python-binance Documentation, Release 0.2.0

Returns API response

{
"success":true,
"transfers":[
{
"from":"[email protected]",
"to":"[email protected]",
"asset":"BTC",
"qty":"1",
"time":1544433328000
},
{
"from":"[email protected]",
"to":"[email protected]",
"asset":"ETH",
"qty":"2",
"time":1544433328000
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_subaccount_deposit_address(**params)
Get Sub-account Deposit Address (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#get-sub-account-deposit-address-for-master-account
Parameters
• email (str) – required - Sub account email
• coin (str) – required
• network (str) – optional
• recvWindow (int) – optional
Returns API response

{
"address":"TDunhSa7jkTNuKrusUTU1MUHtqXoBPKETV",
"coin":"USDT",
"tag":"",
"url":"https://tronscan.org/#/address/TDunhSa7jkTNuKrusUTU1MUHtqXoBPKETV
˓→ "
}

Raises BinanceRequestException, BinanceAPIException

get_subaccount_deposit_history(**params)
Get Sub-account Deposit History (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#get-sub-account-deposit-address-for-master-account
Parameters
• email (str) – required - Sub account email
• coin (str) – optional

82 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

• status (int) – optional - (0:pending,6: credited but cannot withdraw, 1:success)


• startTime (int) – optional
• endTime (int) – optional
• limit (int) – optional
• offset (int) – optional - default:0
• recvWindow (int) – optional
Returns API response

[
{
"amount":"0.00999800",
"coin":"PAXG",
"network":"ETH",
"status":1,
"address":"0x788cabe9236ce061e5a892e1a59395a81fc8d62c",
"addressTag":"",
"txId":
˓→"0xaad4654a3234aa6118af9b4b335f5ae81c360b2394721c019b5d1e75328b09f3",

"insertTime":1599621997000,
"transferType":0,
"confirmTimes":"12/12"
},
{
"amount":"0.50000000",
"coin":"IOTA",
"network":"IOTA",
"status":1,
"address":
˓→"SIZ9VLMHWATXKV99LH99CIGFJFUMLEHGWVZVNNZXRJJVWBPHYWPPBOSDORZ9EQSHCZAMPVAPGFYQAUUV9DROOXJLN

˓→",

"addressTag":"",
"txId":
˓→"ESBFVQUTPIWQNJSPXFNHNYHSQNTGKRVKPRABQWTAXCDWOAKDKYWPTVG9BGXNVNKTLEJGESAVXIKIZ9999

˓→",

"insertTime":1599620082000,
"transferType":0,
"confirmTimes":"1/1"
}
]

Raises BinanceRequestException, BinanceAPIException

get_subaccount_futures_details(**params)
Get Detail on Sub-account’s Futures Account (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#get-detail-on-sub-account-39-s-futures-account-for-master-account
Parameters
• email (str) – required - Sub account email
• recvWindow (int) – optional
Returns API response

5.1. Contents 83
python-binance Documentation, Release 0.2.0

{
"email": "[email protected]",
"asset": "USDT",
"assets":[
{
"asset": "USDT",
"initialMargin": "0.00000000",
"maintenanceMargin": "0.00000000",
"marginBalance": "0.88308000",
"maxWithdrawAmount": "0.88308000",
"openOrderInitialMargin": "0.00000000",
"positionInitialMargin": "0.00000000",
"unrealizedProfit": "0.00000000",
"walletBalance": "0.88308000"
}
],
"canDeposit": true,
"canTrade": true,
"canWithdraw": true,
"feeTier": 2,
"maxWithdrawAmount": "0.88308000",
"totalInitialMargin": "0.00000000",
"totalMaintenanceMargin": "0.00000000",
"totalMarginBalance": "0.88308000",
"totalOpenOrderInitialMargin": "0.00000000",
"totalPositionInitialMargin": "0.00000000",
"totalUnrealizedProfit": "0.00000000",
"totalWalletBalance": "0.88308000",
"updateTime": 1576756674610
}

Raises BinanceRequestException, BinanceAPIException

get_subaccount_futures_margin_status(**params)
Get Sub-account’s Status on Margin/Futures (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#get-sub-account-39-s-status-on-margin-futures-for-master-account
Parameters
• email (str) – optional - Sub account email
• recvWindow (int) – optional
Returns API response

[
{
"email":"[email protected]", // user email
"isSubUserEnabled": true, // true or false
"isUserActive": true, // true or false
"insertTime": 1570791523523 // sub account create time
"isMarginEnabled": true, // true or false for margin
"isFutureEnabled": true // true or false for futures.
"mobile": 1570791523523 // user mobile number
}
]

84 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Raises BinanceRequestException, BinanceAPIException

get_subaccount_futures_positionrisk(**params)
Get Futures Position-Risk of Sub-account (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#get-futures-position-risk-of-sub-account-for-master-account
Parameters
• email (str) – required - Sub account email
• recvWindow (int) – optional
Returns API response
[
{
"entryPrice": "9975.12000",
"leverage": "50", // current initial leverage
"maxNotional": "1000000", // notional value limit of current
˓→initial leverage

"liquidationPrice": "7963.54",
"markPrice": "9973.50770517",
"positionAmount": "0.010",
"symbol": "BTCUSDT",
"unrealizedProfit": "-0.01612295"
}
]

Raises BinanceRequestException, BinanceAPIException

get_subaccount_futures_summary(**params)
Get Summary of Sub-account’s Futures Account (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#get-summary-of-sub-account-39-s-futures-account-for-master-account
Parameters recvWindow (int) – optional
Returns API response
{
"totalInitialMargin": "9.83137400",
"totalMaintenanceMargin": "0.41568700",
"totalMarginBalance": "23.03235621",
"totalOpenOrderInitialMargin": "9.00000000",
"totalPositionInitialMargin": "0.83137400",
"totalUnrealizedProfit": "0.03219710",
"totalWalletBalance": "22.15879444",
"asset": "USDT",
"subAccountList":[
{
"email": "[email protected]",
"totalInitialMargin": "9.00000000",
"totalMaintenanceMargin": "0.00000000",
"totalMarginBalance": "22.12659734",
"totalOpenOrderInitialMargin": "9.00000000",
"totalPositionInitialMargin": "0.00000000",
"totalUnrealizedProfit": "0.00000000",
"totalWalletBalance": "22.12659734",
"asset": "USDT"
(continues on next page)

5.1. Contents 85
python-binance Documentation, Release 0.2.0

(continued from previous page)


},
{
"email": "[email protected]",
"totalInitialMargin": "0.83137400",
"totalMaintenanceMargin": "0.41568700",
"totalMarginBalance": "0.90575887",
"totalOpenOrderInitialMargin": "0.00000000",
"totalPositionInitialMargin": "0.83137400",
"totalUnrealizedProfit": "0.03219710",
"totalWalletBalance": "0.87356177",
"asset": "USDT"
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_subaccount_margin_details(**params)
Get Detail on Sub-account’s Margin Account (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#get-detail-on-sub-account-39-s-margin-account-for-master-account
Parameters
• email (str) – required - Sub account email
• recvWindow (int) – optional
Returns API response
{
"email":"[email protected]",
"marginLevel": "11.64405625",
"totalAssetOfBtc": "6.82728457",
"totalLiabilityOfBtc": "0.58633215",
"totalNetAssetOfBtc": "6.24095242",
"marginTradeCoeffVo":
{
"forceLiquidationBar": "1.10000000", // Liquidation margin
˓→ratio

"marginCallBar": "1.50000000", // Margin call margin


˓→ratio

"normalBar": "2.00000000" // Initial margin ratio


},
"marginUserAssetVoList": [
{
"asset": "BTC",
"borrowed": "0.00000000",
"free": "0.00499500",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00499500"
},
{
"asset": "BNB",
"borrowed": "201.66666672",
"free": "2346.50000000",
"interest": "0.00000000",
(continues on next page)

86 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


"locked": "0.00000000",
"netAsset": "2144.83333328"
},
{
"asset": "ETH",
"borrowed": "0.00000000",
"free": "0.00000000",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00000000"
},
{
"asset": "USDT",
"borrowed": "0.00000000",
"free": "0.00000000",
"interest": "0.00000000",
"locked": "0.00000000",
"netAsset": "0.00000000"
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_subaccount_margin_summary(**params)
Get Summary of Sub-account’s Margin Account (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#get-summary-of-sub-account-39-s-margin-account-for-master-account
Parameters recvWindow (int) – optional
Returns API response

{
"totalAssetOfBtc": "4.33333333",
"totalLiabilityOfBtc": "2.11111112",
"totalNetAssetOfBtc": "2.22222221",
"subAccountList":[
{
"email":"[email protected]",
"totalAssetOfBtc": "2.11111111",
"totalLiabilityOfBtc": "1.11111111",
"totalNetAssetOfBtc": "1.00000000"
},
{
"email":"[email protected]",
"totalAssetOfBtc": "2.22222222",
"totalLiabilityOfBtc": "1.00000001",
"totalNetAssetOfBtc": "1.22222221"
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_subaccount_transfer_history(**params)
Sub-account Transfer History (For Sub-account)

5.1. Contents 87
python-binance Documentation, Release 0.2.0

https://binance-docs.github.io/apidocs/spot/en/#transfer-to-master-for-sub-account
Parameters
• asset (str) – required - The asset being transferred, e.g., USDT
• type (int) – optional - 1: transfer in, 2: transfer out
• startTime (int) – optional
• endTime (int) – optional
• limit (int) – optional - Default 500
• recvWindow (int) – optional
Returns API response
[
{
"counterParty":"master",
"email":"[email protected]",
"type":1, // 1 for transfer in, 2 for transfer out
"asset":"BTC",
"qty":"1",
"status":"SUCCESS",
"tranId":11798835829,
"time":1544433325000
},
{
"counterParty":"subAccount",
"email":"[email protected]",
"type":2,
"asset":"ETH",
"qty":"2",
"status":"SUCCESS",
"tranId":11798829519,
"time":1544433326000
}
]

Raises BinanceRequestException, BinanceAPIException

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": [
{
(continues on next page)

88 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


"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"
}
]
}

Raises BinanceRequestException, BinanceAPIException

get_symbol_ticker(**params)
Latest price for a symbol or symbols.
https://github.com/binance/binance-spot-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"
}
]

Raises BinanceRequestException, BinanceAPIException

get_system_status()
Get system status detail.
https://binance-docs.github.io/apidocs/spot/en/#system-status-system
Returns API response

5.1. Contents 89
python-binance Documentation, Release 0.2.0

{
"status": 0, # 0: normal1system maintenance
"msg": "normal" # normal or System maintenance.
}

Raises BinanceAPIException

get_ticker(**params)
24 hour price change statistics.
https://github.com/binance/binance-spot-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
}
]

90 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Raises BinanceRequestException, BinanceAPIException

get_trade_fee(**params)
Get trade fee.
https://binance-docs.github.io/apidocs/spot/en/#trade-fee-user_data
Parameters
• symbol (str) – optional
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response

{
"tradeFee": [
{
"symbol": "ADABNB",
"maker": 0.9000,
"taker": 1.0000
}, {
"symbol": "BNBBTC",
"maker": 0.3000,
"taker": 0.3000
}
],
"success": true
}

Raises BinanceWithdrawException

get_universal_transfer_history(**params)
Universal Transfer (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#query-universal-transfer-history
Parameters
• fromEmail (str) – optional
• toEmail (str) – optional
• startTime (int) – optional
• endTime (int) – optional
• page (int) – optional
• limit (int) – optional
• recvWindow (int) – optional
Returns API response

[
{
"tranId":11945860693,
"fromEmail":"[email protected]",
"toEmail":"[email protected]",
"asset":"BTC",
"amount":"0.1",
(continues on next page)

5.1. Contents 91
python-binance Documentation, Release 0.2.0

(continued from previous page)


"fromAccountType":"SPOT",
"toAccountType":"COIN_FUTURE",
"status":"SUCCESS",
"createTimeStamp":1544433325000
},
{
"tranId":11945857955,
"fromEmail":"[email protected]",
"toEmail":"[email protected]",
"asset":"ETH",
"amount":"0.2",
"fromAccountType":"SPOT",
"toAccountType":"USDT_FUTURE",
"status":"SUCCESS",
"createTimeStamp":1544433326000
}
]

Raises BinanceRequestException, BinanceAPIException

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
},
{
"amount": 0.005,
"address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
"txId":
˓→"0x80aaabed54bdab3f6de5868f89929a2371ad21d666f20f7393d1a3389fad95a1",

"asset": "ETH",
"applyTime": 1508198532000,
"status": 4
}
],
"success": true
}

92 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Raises BinanceRequestException, BinanceAPIException

isolated_margin_stream_close(symbol, listenKey)
Close out an isolated margin data stream.
https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin
Parameters
• symbol (str) – required - symbol for the isolated margin account
• listenKey (str) – required
Returns API response

{}

Raises BinanceRequestException, BinanceAPIException

isolated_margin_stream_get_listen_key(symbol)
Start a new isolated margin 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 stream alive.
https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin
Parameters symbol (str) – required - symbol for the isolated margin account
Returns API response

{
"listenKey":
˓→ "T3ee22BIYuWqmvne0HNq2A2WsFlEtLhvWCtItw6ffhhdmjifQ2tRbuKkTHhr"
}

Raises BinanceRequestException, BinanceAPIException

isolated_margin_stream_keepalive(symbol, listenKey)
PING an isolated margin data stream to prevent a time out.
https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin
Parameters
• symbol (str) – required - symbol for the isolated margin account
• listenKey (str) – required
Returns API response

{}

Raises BinanceRequestException, BinanceAPIException

make_subaccount_futures_transfer(**params)
Futures Transfer for Sub-account (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#futures-transfer-for-sub-account-for-master-account
Parameters

5.1. Contents 93
python-binance Documentation, Release 0.2.0

• email (str) – required - Sub account email


• asset (str) – required - The asset being transferred, e.g., USDT
• amount (float) – required - The amount to be transferred
• type (int) – required - 1: transfer from subaccount’s spot account to its USDT-
margined futures account 2: transfer from subaccount’s USDT-margined futures ac-
count to its spot account 3: transfer from subaccount’s spot account to its COIN-
margined futures account 4: transfer from subaccount’s COIN-margined futures ac-
count to its spot account
Returns API response

{
"txnId":"2966662589"
}

Raises BinanceRequestException, BinanceAPIException

make_subaccount_margin_transfer(**params)
Margin Transfer for Sub-account (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#margin-transfer-for-sub-account-for-master-account
Parameters
• email (str) – required - Sub account email
• asset (str) – required - The asset being transferred, e.g., USDT
• amount (float) – required - The amount to be transferred
• type (int) – required - 1: transfer from subaccount’s spot account to margin ac-
count 2: transfer from subaccount’s margin account to its spot account
Returns API response

{
"txnId":"2966662589"
}

Raises BinanceRequestException, BinanceAPIException

make_subaccount_to_master_transfer(**params)
Transfer to Master (For Sub-account)
https://binance-docs.github.io/apidocs/spot/en/#transfer-to-master-for-sub-account
Parameters
• asset (str) – required - The asset being transferred, e.g., USDT
• amount (float) – required - The amount to be transferred
• recvWindow (int) – optional
Returns API response

{
"txnId":"2966662589"
}

94 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Raises BinanceRequestException, BinanceAPIException

make_subaccount_to_subaccount_transfer(**params)
Transfer to Sub-account of Same Master (For Sub-account)
https://binance-docs.github.io/apidocs/spot/en/#transfer-to-sub-account-of-same-master-for-sub-account
Parameters
• toEmail (str) – required - Sub account email
• asset (str) – required - The asset being transferred, e.g., USDT
• amount (float) – required - The amount to be transferred
• recvWindow (int) – optional
Returns API response

{
"txnId":"2966662589"
}

Raises BinanceRequestException, BinanceAPIException

make_universal_transfer(**params)
Universal Transfer (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#universal-transfer-for-master-account
Parameters
• fromEmail (str) – optional
• toEmail (str) – optional
• fromAccountType (str) – required
• toAccountType (str) – required
• asset (str) – required - The asset being transferred, e.g., USDT
• amount (float) – required
• recvWindow (int) – optional
Returns API response

{
"tranId":11945860693
}

Raises BinanceRequestException, BinanceAPIException

margin_stream_close(listenKey)
Close out a cross-margin data stream.
https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin
Parameters listenKey (str) – required
Returns API response

5.1. Contents 95
python-binance Documentation, Release 0.2.0

{}

Raises BinanceRequestException, BinanceAPIException

margin_stream_get_listen_key()
Start a new cross-margin 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 stream alive.
https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin
Returns API response

{
"listenKey":
˓→ "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"
}

Raises BinanceRequestException, BinanceAPIException

margin_stream_keepalive(listenKey)
PING a cross-margin data stream to prevent a time out.
https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin
Parameters listenKey (str) – required
Returns API response

{}

Raises BinanceRequestException, BinanceAPIException

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;
default: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for

96 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Returns API response


See order endpoint for full response options
Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTo-
talException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbol-
Exception
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
• newClientOrderId (str) – A unique id for the order. Automatically generated
if not sent.
• stopPrice (decimal) – Used with stop orders
• icebergQty (decimal) – Used with iceberg orders
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL;
default: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See order endpoint for full response options
Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTo-
talException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbol-
Exception
order_limit_sell(timeInForce=’GTC’, **params)
Send in a new limit sell order
Parameters
• symbol (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.
• stopPrice (decimal) – Used with stop orders
• icebergQty (decimal) – Used with iceberg orders
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL;
default: RESULT.

5.1. Contents 97
python-binance Documentation, Release 0.2.0

• recvWindow (int) – the number of milliseconds the request is valid for


Returns API response
See order endpoint for full response options
Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTo-
talException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbol-
Exception
order_market(**params)
Send in a new market order
Parameters
• symbol (str) – required
• side (str) – required
• quantity (decimal) – required
• quoteOrderQty (decimal) – amount the user wants to spend (when buying) or
receive (when selling) of the quote asset
• newClientOrderId (str) – A unique id for the order. Automatically generated
if not sent.
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL;
default: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See order endpoint for full response options
Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTo-
talException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbol-
Exception
order_market_buy(**params)
Send in a new market buy order
Parameters
• symbol (str) – required
• quantity (decimal) – required
• quoteOrderQty (decimal) – the amount the user wants to spend of the quote
asset
• newClientOrderId (str) – A unique id for the order. Automatically generated
if not sent.
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL;
default: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See order endpoint for full response options

98 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, Binance-


OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTo-
talException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbol-
Exception
order_market_sell(**params)
Send in a new market sell order
Parameters
• symbol (str) – required
• quantity (decimal) – required
• quoteOrderQty (decimal) – the amount the user wants to receive of the quote
asset
• newClientOrderId (str) – A unique id for the order. Automatically generated
if not sent.
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL;
default: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See order endpoint for full response options
Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTo-
talException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbol-
Exception
order_oco_buy(**params)
Send in a new OCO buy order
Parameters
• symbol (str) – required
• listClientOrderId (str) – A unique id for the list order. Automatically gen-
erated if not sent.
• quantity (decimal) – required
• limitClientOrderId (str) – A unique id for the limit order. Automatically
generated if not sent.
• price (str) – required
• limitIcebergQty (decimal) – Used to make the LIMIT_MAKER leg an ice-
berg order.
• stopClientOrderId (str) – A unique id for the stop order. Automatically gen-
erated if not sent.
• stopPrice (str) – required
• stopLimitPrice (str) – If provided, stopLimitTimeInForce is required.
• stopIcebergQty (decimal) – Used with STOP_LOSS_LIMIT leg to make an
iceberg order.
• stopLimitTimeInForce (str) – Valid values are GTC/FOK/IOC.

5.1. Contents 99
python-binance Documentation, Release 0.2.0

• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL;


default: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See OCO order endpoint for full response options
Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTo-
talException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbol-
Exception
order_oco_sell(**params)
Send in a new OCO sell order
Parameters
• symbol (str) – required
• listClientOrderId (str) – A unique id for the list order. Automatically gen-
erated if not sent.
• quantity (decimal) – required
• limitClientOrderId (str) – A unique id for the limit order. Automatically
generated if not sent.
• price (str) – required
• limitIcebergQty (decimal) – Used to make the LIMIT_MAKER leg an ice-
berg order.
• stopClientOrderId (str) – A unique id for the stop order. Automatically gen-
erated if not sent.
• stopPrice (str) – required
• stopLimitPrice (str) – If provided, stopLimitTimeInForce is required.
• stopIcebergQty (decimal) – Used with STOP_LOSS_LIMIT leg to make an
iceberg order.
• stopLimitTimeInForce (str) – Valid values are GTC/FOK/IOC.
• newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL;
default: RESULT.
• recvWindow (int) – the number of milliseconds the request is valid for
Returns API response
See OCO order endpoint for full response options
Raises BinanceRequestException, BinanceAPIException, BinanceOrderException, Binance-
OrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTo-
talException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbol-
Exception
ping()
Test connectivity to the Rest API.
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#test-connectivity
Returns Empty array

100 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

{}

Raises BinanceRequestException, BinanceAPIException

purchase_lending_product(**params)
Purchase Flexible Product
https://binance-docs.github.io/apidocs/spot/en/#purchase-flexible-product-user_data
query_subaccount_spot_summary(**params)
Query Sub-account Spot Assets Summary (For Master Account)
https://binance-docs.github.io/apidocs/spot/en/#query-sub-account-spot-assets-summary-for-master-account
Parameters
• email (str) – optional - Sub account email
• page (int) – optional - default 1
• size (int) – optional - default 10, max 20
• recvWindow (int) – optional
Returns API response

{
"totalCount":2,
"masterAccountTotalAsset": "0.23231201",
"spotSubUserAssetBtcVoList":[
{
"email":"[email protected]",
"totalAsset":"9999.00000000"
},
{
"email":"[email protected]",
"totalAsset":"0.00000000"
}
]
}

Raises BinanceRequestException, BinanceAPIException

query_universal_transfer_history(**params)
Query User Universal Transfer History
https://binance-docs.github.io/apidocs/spot/en/#query-user-universal-transfer-history
Parameters
• type (str (ENUM )) – required
• startTime (int) – optional
• endTime (int) – optional
• current (int) – optional - Default 1
• size (int) – required - Default 10, Max 100
• recvWindow (int) – the number of milliseconds the request is valid for

5.1. Contents 101


python-binance Documentation, Release 0.2.0

transfer_status = client.query_universal_transfer_history(params)

Returns API response

{
"total":2,
"rows":[
{
"asset":"USDT",
"amount":"1",
"type":"MAIN_UMFUTURE"
"status": "CONFIRMED",
"tranId": 11415955596,
"timestamp":1544433328000
},
{
"asset":"USDT",
"amount":"2",
"type":"MAIN_UMFUTURE",
"status": "CONFIRMED",
"tranId": 11366865406,
"timestamp":1544433328000
}
]
}

Raises BinanceRequestException, BinanceAPIException

redeem_lending_product(**params)
Redeem Flexible Product
https://binance-docs.github.io/apidocs/spot/en/#redeem-flexible-product-user_data
repay_margin_loan(**params)
Repay loan in cross-margin or isolated-margin account.
If amount is more than the amount borrowed, the full loan will be repaid.
https://binance-docs.github.io/apidocs/spot/en/#margin-account-repay-margin
Parameters
• asset (str) – name of the asset
• amount (str) – amount to transfer
• isIsolated (str) – set to ‘TRUE’ for isolated margin (default ‘FALSE’)
• symbol (str) – Isolated margin symbol (default blank for cross-margin)
• recvWindow (int) – the number of milliseconds the request is valid for

transaction = client.margin_repay_loan(asset='BTC', amount='1.1')

transaction = client.margin_repay_loan(asset='BTC', amount='1.1',


isIsolated='TRUE', symbol='ETHBTC')

Returns API response

102 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

{
"tranId": 100000001
}

Raises BinanceRequestException, BinanceAPIException

stream_close(listenKey)
Close out a user data stream.
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#
close-user-data-stream-user_stream
Parameters listenKey (str) – required
Returns API response

{}

Raises BinanceRequestException, BinanceAPIException

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/binance-spot-api-docs/blob/master/rest-api.md#start-user-data-stream-user_
stream
Returns API response

{
"listenKey":
˓→ "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"
}

Raises BinanceRequestException, BinanceAPIException

stream_keepalive(listenKey)
PING a user data stream to prevent a time out.
https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#
keepalive-user-data-stream-user_stream
Parameters listenKey (str) – required
Returns API response

{}

Raises BinanceRequestException, BinanceAPIException

toggle_bnb_burn_spot_margin(**params)
Toggle BNB Burn On Spot Trade And Margin Interest
https://binance-docs.github.io/apidocs/spot/en/#toggle-bnb-burn-on-spot-trade-and-margin-interest-user_
data

5.1. Contents 103


python-binance Documentation, Release 0.2.0

Parameters
• spotBNBBurn (bool) – Determines whether to use BNB to pay for trading fees on
SPOT
• interestBNBBurn (bool) – Determines whether to use BNB to pay for margin
loan’s interest

response = client.toggle_bnb_burn_spot_margin()

Returns API response

{
"spotBNBBurn":true,
"interestBNBBurn": false
}

Raises BinanceRequestException, BinanceAPIException

transfer_dust(**params)
Convert dust assets to BNB.
https://binance-docs.github.io/apidocs/spot/en/#dust-transfer-user_data
Parameters
• asset (str) – The asset being converted. e.g: ‘ONE’
• recvWindow (int) – the number of milliseconds the request is valid for

result = client.transfer_dust(asset='ONE')

Returns API response

{
"totalServiceCharge":"0.02102542",
"totalTransfered":"1.05127099",
"transferResult":[
{
"amount":"0.03000000",
"fromAsset":"ETH",
"operateTime":1563368549307,
"serviceChargeAmount":"0.00500000",
"tranId":2970932918,
"transferedAmount":"0.25000000"
}
]
}

Raises BinanceRequestException, BinanceAPIException

transfer_history(**params)
Get future account transaction history list
https://binance-docs.github.io/apidocs/futures/en/#get-future-account-transaction-history-list-user_data

104 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

transfer_isolated_margin_to_spot(**params)
Execute transfer between isolated margin account and spot account.
https://binance-docs.github.io/apidocs/spot/en/#isolated-margin-account-transfer-margin
Parameters
• asset (str) – name of the asset
• symbol (str) – pair symbol
• amount (str) – amount to transfer
• recvWindow (int) – the number of milliseconds the request is valid for

transfer = client.transfer_isolated_margin_to_spot(asset='BTC',
symbol='ETHBTC', amount=
˓→'1.1')

Returns API response

{
"tranId": 100000001
}

Raises BinanceRequestException, BinanceAPIException

transfer_margin_to_spot(**params)
Execute transfer between cross-margin account and spot account.
https://binance-docs.github.io/apidocs/spot/en/#cross-margin-account-transfer-margin
Parameters
• asset (str) – name of the asset
• amount (str) – amount to transfer
• recvWindow (int) – the number of milliseconds the request is valid for

transfer = client.transfer_margin_to_spot(asset='BTC', amount='1.1')

Returns API response

{
"tranId": 100000001
}

Raises BinanceRequestException, BinanceAPIException

transfer_spot_to_isolated_margin(**params)
Execute transfer between spot account and isolated margin account.
https://binance-docs.github.io/apidocs/spot/en/#isolated-margin-account-transfer-margin
Parameters
• asset (str) – name of the asset
• symbol (str) – pair symbol

5.1. Contents 105


python-binance Documentation, Release 0.2.0

• amount (str) – amount to transfer


• recvWindow (int) – the number of milliseconds the request is valid for

transfer = client.transfer_spot_to_isolated_margin(asset='BTC',
symbol='ETHBTC', amount=
˓→'1.1')

Returns API response

{
"tranId": 100000001
}

Raises BinanceRequestException, BinanceAPIException

transfer_spot_to_margin(**params)
Execute transfer between spot account and cross-margin account.
https://binance-docs.github.io/apidocs/spot/en/#cross-margin-account-transfer-margin
Parameters
• asset (str) – name of the asset
• amount (str) – amount to transfer
• recvWindow (int) – the number of milliseconds the request is valid for

transfer = client.transfer_spot_to_margin(asset='BTC', amount='1.1')

Returns API response

{
"tranId": 100000001
}

Raises BinanceRequestException, BinanceAPIException

withdraw(**params)
Submit a withdraw request.
https://www.binance.com/restapipub.html
Assumptions:
• You must have Withdraw permissions enabled on your API key
• You must have withdrawn to the address specified through the website and approved the transaction
via email

Parameters
• asset (str) – required
• amount (decimal) – required
• name (str) – optional - Description of the address, default asset value passed will
be used

106 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

• recvWindow (int) – the number of milliseconds the request is valid for


Returns API response

{
"msg": "success",
"success": true,
"id":"7213fea8e94b4a5593d507237e5a555b"
}

Raises BinanceRequestException, BinanceAPIException, BinanceWithdrawException

depthcache module

class binance.depthcache.DepthCache(symbol)
Bases: object
__init__(symbol)
Initialise 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
],
[
(continues on next page)

5.1. Contents 107


python-binance Documentation, Release 0.2.0

(continued from previous page)


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
]
]

static sort_depth(vals, reverse=False)


Sort bids or asks by price
class binance.depthcache.DepthCacheManager(client, symbol, callback=None, re-
fresh_interval=1800, bm=None, limit=500,
ws_interval=None)
Bases: object
__init__(client, symbol, callback=None, refresh_interval=1800, bm=None, limit=500,
ws_interval=None)
Initialise the DepthCacheManager
Parameters
• client (binance.Client) – Binance API client
• symbol (string) – Symbol to create depth cache for
• callback (function) – Optional function to receive depth cache updates
• refresh_interval (int) – Optional number of seconds between cache refresh,
use 0 or None to disable
• limit (int) – Optional number of orders to get from orderbook
• ws_interval (int) – Optional interval for updates on websocket, default None.
If not set, updates happen every second. Must be 0, None (1s) or 100 (100ms).

108 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

close(close_socket=False)
Close the open socket for this manager
Returns
get_depth_cache()
Get the current depth cache
Returns DepthCache object
get_symbol()
Get the symbol
Returns symbol

exceptions module

exception binance.exceptions.BinanceAPIException(response)
Bases: exceptions.Exception
__init__(response)
x.__init__(. . . ) initializes x; see help(type(x)) for signature
exception binance.exceptions.BinanceOrderException(code, message)
Bases: exceptions.Exception
__init__(code, message)
x.__init__(. . . ) initializes x; see help(type(x)) for signature
exception binance.exceptions.BinanceOrderInactiveSymbolException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
x.__init__(. . . ) initializes x; see help(type(x)) for signature
exception binance.exceptions.BinanceOrderMinAmountException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
x.__init__(. . . ) initializes x; see help(type(x)) for signature
exception binance.exceptions.BinanceOrderMinPriceException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
x.__init__(. . . ) initializes x; see help(type(x)) for signature
exception binance.exceptions.BinanceOrderMinTotalException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
x.__init__(. . . ) initializes x; see help(type(x)) for signature
exception binance.exceptions.BinanceOrderUnknownSymbolException(value)
Bases: binance.exceptions.BinanceOrderException
__init__(value)
x.__init__(. . . ) initializes x; see help(type(x)) for signature
exception binance.exceptions.BinanceRequestException(message)
Bases: exceptions.Exception

5.1. Contents 109


python-binance Documentation, Release 0.2.0

__init__(message)
x.__init__(. . . ) initializes x; see help(type(x)) for signature
exception binance.exceptions.BinanceWithdrawException(message)
Bases: exceptions.Exception
__init__(message)
x.__init__(. . . ) initializes x; see help(type(x)) for signature

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

class binance.websockets.BinanceClientFactory(*args, **kwargs)


Bases: autobahn.twisted.websocket.WebSocketClientFactory, binance.websockets.
BinanceReconnectingClientFactory
clientConnectionFailed(connector, reason)
Called when a connection has failed to connect.
It may be useful to call connector.connect() - this will reconnect.
@type reason: L{twisted.python.failure.Failure}
clientConnectionLost(connector, reason)
Called when an established connection is lost.
It may be useful to call connector.connect() - this will reconnect.
@type reason: L{twisted.python.failure.Failure}
protocol
alias of BinanceClientProtocol
class binance.websockets.BinanceClientProtocol
Bases: autobahn.twisted.websocket.WebSocketClientProtocol
__init__()
x.__init__(. . . ) initializes x; see help(type(x)) for signature
onConnect(response)
Callback fired directly after WebSocket opening handshake when new WebSocket server connection was
established.

110 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Parameters response (instance of autobahn.websocket.protocol.


ConnectionResponse) – WebSocket connection response information.
onMessage(payload, isBinary)
Implements autobahn.websocket.interfaces.IWebSocketChannel.onMessage()
class binance.websockets.BinanceReconnectingClientFactory
Bases: twisted.internet.protocol.ReconnectingClientFactory
initialDelay = 0.1
maxDelay = 10
maxRetries = 5
class binance.websockets.BinanceSocketManager(client, user_timeout=1800)
Bases: threading.Thread
DEFAULT_USER_TIMEOUT = 1800
FSTREAM_URL = 'wss://fstream.binance.com/'
STREAM_URL = 'wss://stream.binance.com:9443/'
WEBSOCKET_DEPTH_10 = '10'
WEBSOCKET_DEPTH_20 = '20'
WEBSOCKET_DEPTH_5 = '5'
__init__(client, user_timeout=1800)
Initialise the BinanceSocketManager
Parameters
• client (binance.Client) – Binance API client
• user_timeout (int) – Custom websocket timeout
close()
Close all connections
run()
Method representing the thread’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed
to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken
from the args and kwargs arguments, respectively.
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

5.1. Contents 111


python-binance Documentation, Release 0.2.0

{
"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
}

start_all_mark_price_socket(callback, fast=True)
Start a websocket for all futures mark price data By default all symbols are included in an array. https://
binance-docs.github.io/apidocs/futures/en/#mark-price-stream-for-all-market :param callback: callback
function to handle messages :type callback: function :returns: connection key string if successful, False
otherwise Message Format .. code-block:: python
[
{ “e”: “markPriceUpdate”, // Event type “E”: 1562305380000, // Event time “s”: “BT-
CUSDT”, // Symbol “p”: “11185.87786614”, // Mark price “r”: “0.00030000”, //
Funding rate “T”: 1562306400000 // Next funding time
}
]
start_all_ticker_futures_socket(callback)
Start a websocket for all ticker data By default all markets are included in an array. https://binance-docs.
github.io/apidocs/futures/en/#all-book-tickers-stream :param callback: callback function to handle mes-
sages :type callback: function :returns: connection key string if successful, False otherwise Message
Format .. code-block:: python
[
{ “u”:400900217, // order book updateId “s”:”BNBUSDT”, // symbol
“b”:”25.35190000”, // best bid price “B”:”31.21000000”, // best bid qty
“a”:”25.36520000”, // best ask price “A”:”40.66000000” // best ask qty
}
]
start_book_ticker_socket(callback)
Start a websocket for the best bid or ask’s price or quantity for all symbols.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#
all-book-tickers-stream
Parameters callback (function) – callback function to handle messages
Returns connection key string if successful, False otherwise
Message Format

{
// Same as <symbol>@bookTicker payload
}

112 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

start_depth_socket(symbol, callback, depth=None, interval=None)


Start a websocket for symbol market depth returning either a diff or a partial book
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#
partial-book-depth-streams
Parameters
• symbol (str) – required
• callback (function) – callback function to handle messages
• depth (str) – optional Number of depth entries to return, default None. If passed
returns a partial book instead of a diff
• interval (int) – optional interval for updates, default None. If not set, updates
happen every second. Must be 0, None (1s) or 100 (100ms)
Returns connection key string if successful, False otherwise
Partial Message Format

{
"lastUpdateId": 160, # Last update ID
"bids": [ # Bids to be updated
[
"0.0024", # price level to be updated
"10", # quantity
[] # ignore
]
],
"asks": [ # Asks to be updated
[
"0.0026", # price level to be updated
"100", # quantity
[] # ignore
]
]
}

Diff Message Format

{
"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
(continues on next page)

5.1. Contents 113


python-binance Documentation, Release 0.2.0

(continued from previous page)


]
]
}

start_isolated_margin_socket(symbol, callback)
Start a websocket for isolated margin data
https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin
Parameters
• symbol (str) – required - symbol for the isolated margin account
• callback (function) – callback function to handle messages
Returns connection key string if successful, False otherwise
Message Format - see Binance API docs for all types
start_kline_socket(symbol, callback, interval=’1m’)
Start a websocket for symbol kline data
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#
klinecandlestick-streams
Parameters
• symbol (str) – required
• callback (function) – callback function to handle messages
• interval (str) – Kline interval, default KLINE_INTERVAL_1MINUTE
Returns connection key string if successful, False otherwise
Message Format

{
"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
"f": 77462, # first trade id
"L": 77465, # last trade id
"o": "0.10278577", # open
"c": "0.10278645", # close
"h": "0.10278712", # high
"l": "0.10278518", # low
"v": "17.47929838", # volume
"n": 4, # number of
˓→trades

"x": false, # whether this bar is


˓→final

"q": "1.79662878", # quote volume


"V": "2.34879839", # volume of active buy
"Q": "0.24142166", # quote volume of active buy
"B": "13279784.01349473" # can be ignored
(continues on next page)

114 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

(continued from previous page)


}
}

start_margin_socket(callback)
Start a websocket for cross-margin data
https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin
Parameters callback (function) – callback function to handle messages
Returns connection key string if successful, False otherwise
Message Format - see Binance API docs for all types
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
Returns connection key string if successful, False otherwise
Message Format - see Binance API docs for all types

5.1. Contents 115


python-binance Documentation, Release 0.2.0

start_symbol_book_ticker_socket(symbol, callback)
Start a websocket for the best bid or ask’s price or quantity for a specified symbol.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#
individual-symbol-book-ticker-streams
Parameters
• symbol (str) – required
• callback (function) – callback function to handle messages
Returns connection key string if successful, False otherwise
Message Format

{
"u":400900217, // order book updateId
"s":"BNBUSDT", // symbol
"b":"25.35190000", // best bid price
"B":"31.21000000", // best bid qty
"a":"25.36520000", // best ask price
"A":"40.66000000" // best ask qty
}

start_symbol_mark_price_socket(symbol, callback, fast=True)


Start a websocket for a symbol’s futures mark price https://binance-docs.github.io/apidocs/futures/en/
#mark-price-stream :param symbol: required :type symbol: str :param callback: callback function to
handle messages :type callback: function :returns: connection key string if successful, False otherwise
Message Format .. code-block:: python
{ “e”: “markPriceUpdate”, // Event type “E”: 1562305380000, // Event time “s”: “BT-
CUSDT”, // Symbol “p”: “11185.87786614”, // Mark price “r”: “0.00030000”, // Funding
rate “T”: 1562306400000 // Next funding time
}
start_symbol_ticker_futures_socket(symbol, callback)
Start a websocket for a symbol’s ticker data By default all markets are included in an array. https:
//binance-docs.github.io/apidocs/futures/en/#individual-symbol-book-ticker-streams :param symbol: re-
quired :type symbol: str :param callback: callback function to handle messages :type callback: function
:returns: connection key string if successful, False otherwise .. code-block:: python
[
{ “u”:400900217, // order book updateId “s”:”BNBUSDT”, // symbol
“b”:”25.35190000”, // best bid price “B”:”31.21000000”, // best bid qty
“a”:”25.36520000”, // best ask price “A”:”40.66000000” // best ask qty
}
]
start_symbol_ticker_socket(symbol, callback)
Start a websocket for a symbol’s ticker data
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#
individual-symbol-ticker-streams
Parameters
• symbol (str) – required
• callback (function) – callback function to handle messages

116 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

Returns connection key string if successful, False otherwise


Message Format

{
"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,
'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',
(continues on next page)

5.1. Contents 117


python-binance Documentation, Release 0.2.0

(continued from previous page)


'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://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md https://
binance-docs.github.io/apidocs/spot/en/#listen-key-spot
Parameters callback (function) – callback function to handle messages
Returns connection key string if successful, False otherwise
Message Format - see Binance API docs for all types
stop_socket(conn_key)
Stop a websocket given the connection key
Parameters conn_key (string) – Socket connection key
Returns connection key string if successful, False otherwise

118 Chapter 5. Other Exchanges


python-binance Documentation, Release 0.2.0

5.2 Index

• genindex

5.2. Index 119


python-binance Documentation, Release 0.2.0

120 Chapter 5. Other Exchanges


Python Module Index

b
binance.client, 41
binance.depthcache, 107
binance.exceptions, 109
binance.helpers, 110
binance.websockets, 110

121
python-binance Documentation, Release 0.2.0

122 Python Module Index


Index

Symbols AGG_ID (binance.client.Client attribute), 41


__init__() (binance.client.Client method), 42 AGG_LAST_TRADE_ID (binance.client.Client at-
__init__() (binance.depthcache.DepthCache tribute), 41
method), 107 AGG_PRICE (binance.client.Client attribute), 41
__init__() (binance.depthcache.DepthCacheManager AGG_QUANTITY (binance.client.Client attribute), 41
method), 108 AGG_TIME (binance.client.Client attribute), 41
__init__() (binance.exceptions.BinanceAPIException aggregate_trade_iter() (binance.client.Client
method), 109 method), 42
__init__() (binance.exceptions.BinanceOrderExceptionAPI_URL (binance.client.Client attribute), 41
method), 109
B
__init__() (binance.exceptions.BinanceOrderInactiveSymbolException
method), 109 binance.client (module), 41
binance.depthcache (module), 107
__init__() (binance.exceptions.BinanceOrderMinAmountException
method), 109 binance.exceptions (module), 109
binance.helpers (module), 110
__init__() (binance.exceptions.BinanceOrderMinPriceException
method), 109 binance.websockets (module), 110
BinanceAPIException, 109
__init__() (binance.exceptions.BinanceOrderMinTotalException
method), 109 BinanceClientFactory (class in bi-
nance.websockets), 110
__init__() (binance.exceptions.BinanceOrderUnknownSymbolException
method), 109 BinanceClientProtocol (class in bi-
__init__() (binance.exceptions.BinanceRequestException nance.websockets), 110
method), 109 BinanceOrderException, 109
BinanceOrderInactiveSymbolException, 109
__init__() (binance.exceptions.BinanceWithdrawException
method), 110 BinanceOrderMinAmountException, 109
__init__() (binance.websockets.BinanceClientProtocol BinanceOrderMinPriceException, 109
method), 110 BinanceOrderMinTotalException, 109
__init__() (binance.websockets.BinanceSocketManagerBinanceOrderUnknownSymbolException, 109
method), 111 BinanceReconnectingClientFactory (class in
binance.websockets), 111
A BinanceRequestException, 109
add_ask() (binance.depthcache.DepthCache method), BinanceSocketManager (class in bi-
107 nance.websockets), 111
add_bid() (binance.depthcache.DepthCache method), BinanceWithdrawException, 110
107 C
AGG_BEST_MATCH (binance.client.Client attribute), 41
AGG_BUYER_MAKES (binance.client.Client attribute), cancel_margin_order() (binance.client.Client
41 method), 43
AGG_FIRST_TRADE_ID (binance.client.Client at- cancel_order() (binance.client.Client method), 43
tribute), 41 change_fixed_activity_to_daily_position()
(binance.client.Client method), 44

123
python-binance Documentation, Release 0.2.0

Client (class in binance.client), 41 futures_aggregate_trades() (bi-


clientConnectionFailed() (bi- nance.client.Client method), 52
nance.websockets.BinanceClientFactory FUTURES_API_VERSION (binance.client.Client
method), 110 attribute), 41
clientConnectionLost() (bi-
futures_cancel_all_open_orders() (bi-
nance.websockets.BinanceClientFactory nance.client.Client method), 52
method), 110 futures_cancel_order() (binance.client.Client
close() (binance.depthcache.DepthCacheManager method), 52
method), 108 futures_cancel_orders() (binance.client.Client
close() (binance.websockets.BinanceSocketManager method), 52
method), 111 futures_change_leverage() (bi-
create_isolated_margin_account() (bi- nance.client.Client method), 52
nance.client.Client method), 44 futures_change_margin_type() (bi-
create_margin_loan() (binance.client.Client nance.client.Client method), 53
method), 44 futures_change_position_margin() (bi-
create_margin_order() (binance.client.Client nance.client.Client method), 53
method), 45 futures_change_position_mode() (bi-
create_oco_order() (binance.client.Client nance.client.Client method), 53
method), 47 futures_create_order() (binance.client.Client
create_order() (binance.client.Client method), 48 method), 53
create_sub_account_futures_transfer() futures_exchange_info() (binance.client.Client
(binance.client.Client method), 50 method), 53
create_sub_account_transfer() (bi-
futures_funding_rate() (binance.client.Client
nance.client.Client method), 50 method), 53
create_test_order() (binance.client.Client
futures_get_all_orders() (bi-
method), 51 nance.client.Client method), 53
futures_get_open_orders() (bi-
D nance.client.Client method), 53
date_to_milliseconds() (in module bi- futures_get_order() (binance.client.Client
nance.helpers), 110 method), 53
DEFAULT_USER_TIMEOUT (bi- futures_get_position_mode() (bi-
nance.websockets.BinanceSocketManager nance.client.Client method), 53
attribute), 111 futures_historical_trades() (bi-
DepthCache (class in binance.depthcache), 107 nance.client.Client method), 53
DepthCacheManager (class in binance.depthcache), futures_income_history() (bi-
108 nance.client.Client method), 53
futures_klines() (binance.client.Client method),
E 53
enable_subaccount_futures() (bi- futures_leverage_bracket() (bi-
nance.client.Client method), 51 nance.client.Client method), 54
enable_subaccount_margin() (bi- futures_liquidation_orders() (bi-
nance.client.Client method), 51 nance.client.Client method), 54
futures_mark_price() (binance.client.Client
F method), 54
futures_open_interest() (binance.client.Client
FSTREAM_URL (binance.websockets.BinanceSocketManager
attribute), 111 method), 54
futures_account() (binance.client.Client method), futures_order_book() (binance.client.Client
52 method), 54
futures_account_balance() (bi- futures_orderbook_ticker() (bi-
nance.client.Client method), 52 nance.client.Client method), 54
futures_account_trades() (bi- futures_ping() (binance.client.Client method), 54
nance.client.Client method), 52 futures_position_information() (bi-
futures_account_transfer() (bi- nance.client.Client method), 54
nance.client.Client method), 52 futures_position_margin_history() (bi-

124 Index
python-binance Documentation, Release 0.2.0

nance.client.Client method), 54 get_historical_trades() (binance.client.Client


futures_recent_trades() (binance.client.Client method), 65
method), 54 get_isolated_margin_account() (bi-
futures_symbol_ticker() (binance.client.Client nance.client.Client method), 65
method), 54 get_isolated_margin_symbol() (bi-
futures_ticker() (binance.client.Client method), nance.client.Client method), 67
54 get_klines() (binance.client.Client method), 68
futures_time() (binance.client.Client method), 54 get_lending_account() (binance.client.Client
FUTURES_URL (binance.client.Client attribute), 41 method), 68
get_lending_daily_quota_left() (bi-
G nance.client.Client method), 68
get_account() (binance.client.Client method), 55 get_lending_daily_redemption_quota()
get_account_status() (binance.client.Client (binance.client.Client method), 68
method), 55 get_lending_interest_history() (bi-
get_aggregate_trades() (binance.client.Client nance.client.Client method), 68
method), 55 get_lending_position() (binance.client.Client
get_all_isolated_margin_symbols() (bi- method), 69
nance.client.Client method), 56 get_lending_product_list() (bi-
get_all_margin_orders() (binance.client.Client nance.client.Client method), 69
method), 57 get_lending_purchase_history() (bi-
get_all_orders() (binance.client.Client method), nance.client.Client method), 69
57 get_lending_redemption_history() (bi-
get_all_tickers() (binance.client.Client method), nance.client.Client method), 69
58 get_margin_account() (binance.client.Client
get_asks() (binance.depthcache.DepthCache method), 69
method), 107 get_margin_asset() (binance.client.Client
get_asset_balance() (binance.client.Client method), 70
method), 58 get_margin_loan_details() (bi-
get_asset_details() (binance.client.Client nance.client.Client method), 70
method), 59 get_margin_order() (binance.client.Client
get_asset_dividend_history() (bi- method), 71
nance.client.Client method), 59 get_margin_price_index() (bi-
get_avg_price() (binance.client.Client method), 60 nance.client.Client method), 71
get_bids() (binance.depthcache.DepthCache get_margin_repay_details() (bi-
method), 108 nance.client.Client method), 72
get_bnb_burn_spot_margin() (bi- get_margin_symbol() (binance.client.Client
nance.client.Client method), 60 method), 72
get_deposit_address() (binance.client.Client get_margin_trades() (binance.client.Client
method), 60 method), 73
get_deposit_history() (binance.client.Client get_max_margin_loan() (binance.client.Client
method), 61 method), 73
get_depth_cache() (bi- get_max_margin_transfer() (bi-
nance.depthcache.DepthCacheManager nance.client.Client method), 74
method), 109 get_my_trades() (binance.client.Client method), 74
get_dust_log() (binance.client.Client method), 61 get_open_margin_orders() (bi-
get_exchange_info() (binance.client.Client nance.client.Client method), 75
method), 63 get_open_orders() (binance.client.Client method),
get_fixed_activity_project_list() (bi- 75
nance.client.Client method), 64 get_order() (binance.client.Client method), 76
get_historical_klines() (binance.client.Client get_order_book() (binance.client.Client method),
method), 64 76
get_historical_klines_generator() (bi- get_orderbook_ticker() (binance.client.Client
nance.client.Client method), 64 method), 77
get_orderbook_tickers() (binance.client.Client

Index 125
python-binance Documentation, Release 0.2.0

method), 78 isolated_margin_stream_get_listen_key()
get_products() (binance.client.Client method), 78 (binance.client.Client method), 93
get_recent_trades() (binance.client.Client isolated_margin_stream_keepalive()
method), 78 (binance.client.Client method), 93
get_server_time() (binance.client.Client method),
79 K
get_sub_account_assets() (bi- KLINE_INTERVAL_12HOUR (binance.client.Client at-
nance.client.Client method), 79 tribute), 41
get_sub_account_futures_transfer_history() KLINE_INTERVAL_15MINUTE (binance.client.Client
(binance.client.Client method), 80 attribute), 41
get_sub_account_list() (binance.client.Client KLINE_INTERVAL_1DAY (binance.client.Client
method), 80 attribute), 41
get_sub_account_transfer_history() KLINE_INTERVAL_1HOUR (binance.client.Client at-
(binance.client.Client method), 81 tribute), 41
get_subaccount_deposit_address() (bi- KLINE_INTERVAL_1MINUTE (binance.client.Client
nance.client.Client method), 82 attribute), 41
get_subaccount_deposit_history() (bi- KLINE_INTERVAL_1MONTH (binance.client.Client at-
nance.client.Client method), 82 tribute), 41
get_subaccount_futures_details() (bi- KLINE_INTERVAL_1WEEK (binance.client.Client at-
nance.client.Client method), 83 tribute), 41
get_subaccount_futures_margin_status() KLINE_INTERVAL_2HOUR (binance.client.Client at-
(binance.client.Client method), 84 tribute), 41
get_subaccount_futures_positionrisk() KLINE_INTERVAL_30MINUTE (binance.client.Client
(binance.client.Client method), 85 attribute), 41
get_subaccount_futures_summary() (bi- KLINE_INTERVAL_3DAY (binance.client.Client
nance.client.Client method), 85 attribute), 41
get_subaccount_margin_details() (bi- KLINE_INTERVAL_3MINUTE (binance.client.Client
nance.client.Client method), 86 attribute), 41
get_subaccount_margin_summary() (bi- KLINE_INTERVAL_4HOUR (binance.client.Client at-
nance.client.Client method), 87 tribute), 41
get_subaccount_transfer_history() (bi- KLINE_INTERVAL_5MINUTE (binance.client.Client
nance.client.Client method), 87 attribute), 41
get_symbol() (binance.depthcache.DepthCacheManager KLINE_INTERVAL_6HOUR (binance.client.Client at-
method), 109 tribute), 41
get_symbol_info() (binance.client.Client method), KLINE_INTERVAL_8HOUR (binance.client.Client at-
88 tribute), 41
get_symbol_ticker() (binance.client.Client
method), 89 M
get_system_status() (binance.client.Client make_subaccount_futures_transfer()
method), 89 (binance.client.Client method), 93
get_ticker() (binance.client.Client method), 90 make_subaccount_margin_transfer() (bi-
get_trade_fee() (binance.client.Client method), 91 nance.client.Client method), 94
get_universal_transfer_history() (bi- make_subaccount_to_master_transfer()
nance.client.Client method), 91 (binance.client.Client method), 94
get_withdraw_history() (binance.client.Client make_subaccount_to_subaccount_transfer()
method), 92 (binance.client.Client method), 95
make_universal_transfer() (bi-
I nance.client.Client method), 95
initialDelay (binance.websockets.BinanceReconnectingClientFactory
MARGIN_API_URL (binance.client.Client attribute), 41
attribute), 111 MARGIN_API_VERSION (binance.client.Client at-
interval_to_milliseconds() (in module bi- tribute), 41
nance.helpers), 110 margin_stream_close() (binance.client.Client
isolated_margin_stream_close() (bi- method), 95
nance.client.Client method), 93

126 Index
python-binance Documentation, Release 0.2.0

margin_stream_get_listen_key() (bi- ORDER_TYPE_STOP_LOSS (binance.client.Client at-


nance.client.Client method), 96 tribute), 42
margin_stream_keepalive() (bi- ORDER_TYPE_STOP_LOSS_LIMIT (bi-
nance.client.Client method), 96 nance.client.Client attribute), 42
maxDelay (binance.websockets.BinanceReconnectingClientFactory
ORDER_TYPE_TAKE_PROFIT (binance.client.Client
attribute), 111 attribute), 42
maxRetries (binance.websockets.BinanceReconnectingClientFactory
ORDER_TYPE_TAKE_PROFIT_LIMIT (bi-
attribute), 111 nance.client.Client attribute), 42

O P
onConnect() (binance.websockets.BinanceClientProtocolping() (binance.client.Client method), 100
method), 110 PRIVATE_API_VERSION (binance.client.Client
onMessage() (binance.websockets.BinanceClientProtocol attribute), 42
method), 111 protocol (binance.websockets.BinanceClientFactory
order_limit() (binance.client.Client method), 96 attribute), 110
order_limit_buy() (binance.client.Client method), PUBLIC_API_VERSION (binance.client.Client at-
97 tribute), 42
order_limit_sell() (binance.client.Client purchase_lending_product() (bi-
method), 97 nance.client.Client method), 101
order_market() (binance.client.Client method), 98
order_market_buy() (binance.client.Client Q
method), 98 query_subaccount_spot_summary() (bi-
order_market_sell() (binance.client.Client nance.client.Client method), 101
method), 99 query_universal_transfer_history()
order_oco_buy() (binance.client.Client method), 99 (binance.client.Client method), 101
order_oco_sell() (binance.client.Client method),
100 R
ORDER_RESP_TYPE_ACK (binance.client.Client redeem_lending_product() (bi-
attribute), 41 nance.client.Client method), 102
ORDER_RESP_TYPE_FULL (binance.client.Client at- repay_margin_loan() (binance.client.Client
tribute), 41 method), 102
ORDER_RESP_TYPE_RESULT (binance.client.Client run() (binance.websockets.BinanceSocketManager
attribute), 41 method), 111
ORDER_STATUS_CANCELED (binance.client.Client at-
tribute), 41 S
ORDER_STATUS_EXPIRED (binance.client.Client at- SIDE_BUY (binance.client.Client attribute), 42
tribute), 42 SIDE_SELL (binance.client.Client attribute), 42
ORDER_STATUS_FILLED (binance.client.Client sort_depth() (binance.depthcache.DepthCache
attribute), 42 static method), 108
ORDER_STATUS_NEW (binance.client.Client attribute), start_aggtrade_socket() (bi-
42 nance.websockets.BinanceSocketManager
ORDER_STATUS_PARTIALLY_FILLED (bi- method), 111
nance.client.Client attribute), 42 start_all_mark_price_socket() (bi-
ORDER_STATUS_PENDING_CANCEL (bi- nance.websockets.BinanceSocketManager
nance.client.Client attribute), 42 method), 112
ORDER_STATUS_REJECTED (binance.client.Client at- start_all_ticker_futures_socket() (bi-
tribute), 42 nance.websockets.BinanceSocketManager
ORDER_TYPE_LIMIT (binance.client.Client attribute), method), 112
42 start_book_ticker_socket() (bi-
ORDER_TYPE_LIMIT_MAKER (binance.client.Client nance.websockets.BinanceSocketManager
attribute), 42 method), 112
ORDER_TYPE_MARKET (binance.client.Client at- start_depth_socket() (bi-
tribute), 42 nance.websockets.BinanceSocketManager
method), 112

Index 127
python-binance Documentation, Release 0.2.0

start_isolated_margin_socket() (bi- TIME_IN_FORCE_IOC (binance.client.Client at-


nance.websockets.BinanceSocketManager tribute), 42
method), 114 toggle_bnb_burn_spot_margin() (bi-
start_kline_socket() (bi- nance.client.Client method), 103
nance.websockets.BinanceSocketManager transfer_dust() (binance.client.Client method),
method), 114 104
start_margin_socket() (bi- transfer_history() (binance.client.Client
nance.websockets.BinanceSocketManager method), 104
method), 115 transfer_isolated_margin_to_spot()
start_miniticker_socket() (bi- (binance.client.Client method), 104
nance.websockets.BinanceSocketManager transfer_margin_to_spot() (bi-
method), 115 nance.client.Client method), 105
start_multiplex_socket() (bi- transfer_spot_to_isolated_margin()
nance.websockets.BinanceSocketManager (binance.client.Client method), 105
method), 115 transfer_spot_to_margin() (bi-
start_symbol_book_ticker_socket() (bi- nance.client.Client method), 106
nance.websockets.BinanceSocketManager
method), 115 W
start_symbol_mark_price_socket() (bi- WEBSITE_URL (binance.client.Client attribute), 42
nance.websockets.BinanceSocketManager WEBSOCKET_DEPTH_10 (bi-
method), 116 nance.websockets.BinanceSocketManager
start_symbol_ticker_futures_socket() attribute), 111
(binance.websockets.BinanceSocketManager WEBSOCKET_DEPTH_20 (bi-
method), 116 nance.websockets.BinanceSocketManager
start_symbol_ticker_socket() (bi- attribute), 111
nance.websockets.BinanceSocketManager WEBSOCKET_DEPTH_5 (bi-
method), 116 nance.websockets.BinanceSocketManager
start_ticker_socket() (bi- attribute), 111
nance.websockets.BinanceSocketManager withdraw() (binance.client.Client method), 106
method), 117 WITHDRAW_API_URL (binance.client.Client attribute),
start_trade_socket() (bi- 42
nance.websockets.BinanceSocketManager WITHDRAW_API_VERSION (binance.client.Client at-
method), 118 tribute), 42
start_user_socket() (bi-
nance.websockets.BinanceSocketManager
method), 118
stop_socket() (bi-
nance.websockets.BinanceSocketManager
method), 118
stream_close() (binance.client.Client method), 103
stream_get_listen_key() (binance.client.Client
method), 103
stream_keepalive() (binance.client.Client
method), 103
STREAM_URL (binance.websockets.BinanceSocketManager
attribute), 111
SYMBOL_TYPE_SPOT (binance.client.Client attribute),
42

T
TIME_IN_FORCE_FOK (binance.client.Client at-
tribute), 42
TIME_IN_FORCE_GTC (binance.client.Client at-
tribute), 42

128 Index

You might also like