Skip to main content

Binance REST API python implementation

Project description

Updated 11th May 2021

https://img.shields.io/pypi/v/python-binance.svg https://img.shields.io/pypi/l/python-binance.svg https://img.shields.io/travis/sammchardy/python-binance.svg https://img.shields.io/coveralls/sammchardy/python-binance.svg https://img.shields.io/pypi/wheel/python-binance.svg https://img.shields.io/pypi/pyversions/python-binance.svg

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 including async

https://sammchardy.github.io

Make sure you update often and check the Changelog for new features and bug fixes.

Features

  • Implementation of all General, Market Data and Account endpoints.

  • Asyncio implementation

  • Testnet support for Spot, Futures and Vanilla Options

  • 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

  • Vanilla Options

  • Support other domains (.us, .jp, etc)

Upgrading to v1.0.0+

The breaking changes include the migration from wapi to sapi endpoints which related to the wallet endpoints detailed in the Binance Docs

The other breaking change is for websocket streams and the Depth Cache Manager which have been converted to use Asynchronous Context Managers. See examples in the Async section below or view the websockets and depth cache docs.

Quick Start

Register an account with Binance.

Generate an API Key and assign relevant permissions.

If you are using an exchange from the US, Japan or other TLD then make sure pass tld=’us’ when creating the client.

To use the Spot or Vanilla Options Testnet, pass testnet=True when creating the client.

pip install python-binance
from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
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
try:
    result = client.withdraw(
        asset='ETH',
        address='<eth_address>',
        amount=100)
except BinanceAPIException as e:
    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(coin='ETH')

# get a deposit address for BTC
address = client.get_deposit_address(coin='BTC')

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

# socket manager using threads
twm = ThreadedWebsocketManager()
twm.start()

# depth cache manager using threads
dcm = ThreadedDepthCacheManager()
dcm.start()

def handle_socket_message(msg):
    print(f"message type: {msg['e']}")
    print(msg)

def handle_dcm_message(depth_cache):
    print(f"symbol {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))

twm.start_kline_socket(callback=handle_socket_message, symbol='BNBBTC')

dcm.start_depth_cache(callback=handle_dcm_message, symbol='ETHBTC')

# replace with a current options symbol
options_symbol = 'BTC-210430-36000-C'
dcm.start_options_depth_cache(callback=handle_dcm_message, symbol=options_symbol)

# join the threaded managers to the main thread
twm.join()
dcm.join()

For more check out the documentation.

Async Example

Read Async basics for Binance for more information.

import asyncio
import json

from binance import AsyncClient, DepthCacheManager, BinanceSocketManager

async def main():

    # initialise the client
    client = await AsyncClient.create()

    # run some simple requests
    print(json.dumps(await client.get_exchange_info(), indent=2))

    print(json.dumps(await client.get_symbol_ticker(symbol="BTCUSDT"), indent=2))

    # initialise websocket factory manager
    bsm = BinanceSocketManager(client)

    # create listener using async with
    # this will exit and close the connection after 5 messages
    async with bsm.trade_socket('ETHBTC') as ts:
        for _ in range(5):
            res = await ts.recv()
            print(f'recv {res}')

    # 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", AsyncClient.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")

    # use generator to fetch 1 minute klines for the last day up until now
    async for kline in await client.get_historical_klines_generator("BNBBTC", AsyncClient.KLINE_INTERVAL_1MINUTE, "1 day ago UTC"):
        print(kline)

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

    # setup an async context the Depth Cache and exit after 5 messages
    async with DepthCacheManager(client, symbol='ETHBTC') as dcm_socket:
        for _ in range(5):
            depth_cache = await dcm_socket.recv()
            print(f"symbol {depth_cache.symbol} updated:{depth_cache.update_time}")
            print("Top 5 asks:")
            print(depth_cache.get_asks()[:5])
            print("Top 5 bids:")
            print(depth_cache.get_bids()[:5])

    # Vanilla options Depth Cache works the same, update the symbol to a current one
    options_symbol = 'BTC-210430-36000-C'
    async with OptionsDepthCacheManager(client, symbol=options_symbol) as dcm_socket:
        for _ in range(5):
            depth_cache = await dcm_socket.recv()
            count += 1
            print(f"symbol {depth_cache.symbol} updated:{depth_cache.update_time}")
            print("Top 5 asks:")
            print(depth_cache.get_asks()[:5])
            print("Top 5 bids:")
            print(depth_cache.get_bids()[:5])

    await client.close_connection()

if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

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.

https://ga-beacon.appspot.com/UA-111417213-1/github/python-binance?pixel&useReferer

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python-binance-1.0.13.tar.gz (63.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

python_binance-1.0.13-py2.py3-none-any.whl (63.1 kB view details)

Uploaded Python 2Python 3

File details

Details for the file python-binance-1.0.13.tar.gz.

File metadata

  • Download URL: python-binance-1.0.13.tar.gz
  • Upload date:
  • Size: 63.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.6

File hashes

Hashes for python-binance-1.0.13.tar.gz
Algorithm Hash digest
SHA256 6eae2991a046d6be622b5d5cd3fe523ea46de0a1d20a5542103e3e34650ff4e5
MD5 150532f322ff8b68cf8838ee367b21a7
BLAKE2b-256 245662d27c21205a4d58ba04b7a3507794ae62817c18b2d86262e7c616178c84

See more details on using hashes here.

File details

Details for the file python_binance-1.0.13-py2.py3-none-any.whl.

File metadata

  • Download URL: python_binance-1.0.13-py2.py3-none-any.whl
  • Upload date:
  • Size: 63.1 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.6

File hashes

Hashes for python_binance-1.0.13-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 21a4cf1e3dc770db971a24c104d9691fb95e6609ee5f5d39cc94361f10d29d5a
MD5 e09e13c9607712b72c18bd061f1f4dbb
BLAKE2b-256 e96eeb3e7402efa0796a07007bf146a08fd786a779fcb32dc1663e614a22c6cb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page