=================================
Welcome to python-binance v1.0.16
=================================
Updated 9th Apr 2022
.. image:: https://img.shields.io/pypi/v/python-binance.svg
:target: https://pypi.python.org/pypi/python-binance
.. image:: https://img.shields.io/pypi/l/python-binance.svg
:target: https://pypi.python.org/pypi/python-binance
.. image:: https://img.shields.io/travis/sammchardy/python-binance.svg
:target: https://travis-ci.org/sammchardy/python-binance
.. image:: https://img.shields.io/coveralls/sammchardy/python-binance.svg
:target: https://coveralls.io/github/sammchardy/python-binance
.. image:: https://img.shields.io/pypi/wheel/python-binance.svg
:target: https://pypi.python.org/pypi/python-binance
.. image:: https://img.shields.io/pypi/pyversions/python-binance.svg
:target: https://pypi.python.org/pypi/python-binance
This is an unofficial Python wrapper for the `Binance exchange REST API v3 <https://binance-docs.github.io/apidocs/spot/en>`_. I am in no way affiliated with Binance, use at your own risk.
If you came here looking for the `Binance exchange <https://www.binance.com/?ref=10099792>`_ to purchase cryptocurrencies, then `go here <https://www.binance.com/?ref=10099792>`_.
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 <https://github.com/sammchardy/python-binance-chain>`_
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
- `Async basics for Binance <https://sammchardy.github.io/binance/2021/05/01/async-binance-basics.html>`_
- `Understanding Binance Order Filters <https://sammchardy.github.io/binance/2021/05/03/binance-order-filters.html>`_
Make sure you update often and check the `Changelog <https://python-binance.readthedocs.io/en/latest/changelog.html>`_ 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 <https://binance-docs.github.io/apidocs/spot/en/#wallet-endpoints>`_
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 <https://python-binance.readthedocs.io/en/latest/websockets.html>`_ and
`depth cache <https://python-binance.readthedocs.io/en/latest/depth_cache.html>`_ docs.
Quick Start
-----------
`Register an account with Binance <https://accounts.binance.com/en/register?ref=10099792>`_.
`Generate an API Key <https://www.binance.com/en/my/settings/api-management>`_ 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 <https://testnet.binance.vision/>`_ or `Vanilla Options <https://testnet.binanceops.com/>`_ Testnet,
pass `testnet=True` when creating the client.
.. code:: bash
pip install python-binance
.. code:: python
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 <https://python-binance.readthedocs.io/en/latest/>`_.
Async Example
-------------
Read `Async basics for Binance <https://sammchardy.github.io/binance/2021/05/01/async-binance-basics.html>`_
for more information.
.. code:: python
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())
Donate
------
If this library helped you out feel free to donate.
- ETH: 0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70
- LTC: LPC5vw9ajR1YndE1hYVeo3kJ9LdHjcRCUZ
- NEO: AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBo
- BTC: 1Dknp6L6oRZrHDECRedihPzx2sSfmvEBys
Other Exchanges
---------------
If you use `Binance Chain <https://testnet.binance.org/>`_ check out my `python-binance-chain <https://github.com/sammchardy/python-binance-chain>`_ library.
If you use `Kucoin <https://www.kucoin.com/?rcode=E42cWB>`_ check out my `python-kucoin <https://github.com/sammchardy/python-kucoin>`_ library.
If you use `IDEX <https://idex.market>`_ check out my `python-idex <https://github.com/sammchardy/python-idex>`_ library.
.. image:: https://ga-beacon.appspot.com/UA-111417213-1/github/python-binance?pixel&useReferer
Raw data
{
"_id": null,
"home_page": "https://github.com/Immortalion/python-binance-fixed",
"name": "python-binance-fixed",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "binance exchange rest api bitcoin ethereum btc eth neo",
"author": "Sam McHardy",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/25/50/53a130bfc8592b082154027632a585d936de6168728be473200e22dbd430/python-binance-fixed-1.0.16.tar.gz",
"platform": null,
"description": "=================================\r\nWelcome to python-binance v1.0.16\r\n=================================\r\n\r\nUpdated 9th Apr 2022\r\n\r\n.. image:: https://img.shields.io/pypi/v/python-binance.svg\r\n :target: https://pypi.python.org/pypi/python-binance\r\n\r\n.. image:: https://img.shields.io/pypi/l/python-binance.svg\r\n :target: https://pypi.python.org/pypi/python-binance\r\n\r\n.. image:: https://img.shields.io/travis/sammchardy/python-binance.svg\r\n :target: https://travis-ci.org/sammchardy/python-binance\r\n\r\n.. image:: https://img.shields.io/coveralls/sammchardy/python-binance.svg\r\n :target: https://coveralls.io/github/sammchardy/python-binance\r\n\r\n.. image:: https://img.shields.io/pypi/wheel/python-binance.svg\r\n :target: https://pypi.python.org/pypi/python-binance\r\n\r\n.. image:: https://img.shields.io/pypi/pyversions/python-binance.svg\r\n :target: https://pypi.python.org/pypi/python-binance\r\n\r\nThis is an unofficial Python wrapper for the `Binance exchange REST API v3 <https://binance-docs.github.io/apidocs/spot/en>`_. I am in no way affiliated with Binance, use at your own risk.\r\n\r\nIf you came here looking for the `Binance exchange <https://www.binance.com/?ref=10099792>`_ to purchase cryptocurrencies, then `go here <https://www.binance.com/?ref=10099792>`_.\r\nIf you want to automate interactions with Binance stick around.\r\n\r\nIf you're interested in Binance's new DEX Binance Chain see my `python-binance-chain library <https://github.com/sammchardy/python-binance-chain>`_\r\n\r\nSource code\r\n https://github.com/sammchardy/python-binance\r\n\r\nDocumentation\r\n https://python-binance.readthedocs.io/en/latest/\r\n\r\nBinance API Telegram\r\n https://t.me/binance_api_english\r\n\r\nBlog with examples including async\r\n https://sammchardy.github.io\r\n\r\n- `Async basics for Binance <https://sammchardy.github.io/binance/2021/05/01/async-binance-basics.html>`_\r\n- `Understanding Binance Order Filters <https://sammchardy.github.io/binance/2021/05/03/binance-order-filters.html>`_\r\n\r\nMake sure you update often and check the `Changelog <https://python-binance.readthedocs.io/en/latest/changelog.html>`_ for new features and bug fixes.\r\n\r\nFeatures\r\n--------\r\n\r\n- Implementation of all General, Market Data and Account endpoints.\r\n- Asyncio implementation\r\n- Testnet support for Spot, Futures and Vanilla Options\r\n- Simple handling of authentication\r\n- No need to generate timestamps yourself, the wrapper does it for you\r\n- Response exception handling\r\n- Websocket handling with reconnection and multiplexed connections\r\n- Symbol Depth Cache\r\n- Historical Kline/Candle fetching function\r\n- Withdraw functionality\r\n- Deposit addresses\r\n- Margin Trading\r\n- Futures Trading\r\n- Vanilla Options\r\n- Support other domains (.us, .jp, etc)\r\n\r\nUpgrading to v1.0.0+\r\n--------------------\r\n\r\nThe breaking changes include the migration from wapi to sapi endpoints which related to the\r\nwallet endpoints detailed in the `Binance Docs <https://binance-docs.github.io/apidocs/spot/en/#wallet-endpoints>`_\r\n\r\nThe other breaking change is for websocket streams and the Depth Cache Manager which have been\r\nconverted to use Asynchronous Context Managers. See examples in the Async section below or view the\r\n`websockets <https://python-binance.readthedocs.io/en/latest/websockets.html>`_ and\r\n`depth cache <https://python-binance.readthedocs.io/en/latest/depth_cache.html>`_ docs.\r\n\r\nQuick Start\r\n-----------\r\n\r\n`Register an account with Binance <https://accounts.binance.com/en/register?ref=10099792>`_.\r\n\r\n`Generate an API Key <https://www.binance.com/en/my/settings/api-management>`_ and assign relevant permissions.\r\n\r\nIf you are using an exchange from the US, Japan or other TLD then make sure pass `tld='us'` when creating the\r\nclient.\r\n\r\nTo use the `Spot <https://testnet.binance.vision/>`_ or `Vanilla Options <https://testnet.binanceops.com/>`_ Testnet,\r\npass `testnet=True` when creating the client.\r\n\r\n\r\n.. code:: bash\r\n\r\n pip install python-binance\r\n\r\n\r\n.. code:: python\r\n\r\n from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager\r\n client = Client(api_key, api_secret)\r\n\r\n # get market depth\r\n depth = client.get_order_book(symbol='BNBBTC')\r\n\r\n # place a test market buy order, to place an actual order use the create_order function\r\n order = client.create_test_order(\r\n symbol='BNBBTC',\r\n side=Client.SIDE_BUY,\r\n type=Client.ORDER_TYPE_MARKET,\r\n quantity=100)\r\n\r\n # get all symbol prices\r\n prices = client.get_all_tickers()\r\n\r\n # withdraw 100 ETH\r\n # check docs for assumptions around withdrawals\r\n from binance.exceptions import BinanceAPIException\r\n try:\r\n result = client.withdraw(\r\n asset='ETH',\r\n address='<eth_address>',\r\n amount=100)\r\n except BinanceAPIException as e:\r\n print(e)\r\n else:\r\n print(\"Success\")\r\n\r\n # fetch list of withdrawals\r\n withdraws = client.get_withdraw_history()\r\n\r\n # fetch list of ETH withdrawals\r\n eth_withdraws = client.get_withdraw_history(coin='ETH')\r\n\r\n # get a deposit address for BTC\r\n address = client.get_deposit_address(coin='BTC')\r\n\r\n # get historical kline data from any date range\r\n\r\n # fetch 1 minute klines for the last day up until now\r\n klines = client.get_historical_klines(\"BNBBTC\", Client.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\")\r\n\r\n # fetch 30 minute klines for the last month of 2017\r\n klines = client.get_historical_klines(\"ETHBTC\", Client.KLINE_INTERVAL_30MINUTE, \"1 Dec, 2017\", \"1 Jan, 2018\")\r\n\r\n # fetch weekly klines since it listed\r\n klines = client.get_historical_klines(\"NEOBTC\", Client.KLINE_INTERVAL_1WEEK, \"1 Jan, 2017\")\r\n\r\n # socket manager using threads\r\n twm = ThreadedWebsocketManager()\r\n twm.start()\r\n\r\n # depth cache manager using threads\r\n dcm = ThreadedDepthCacheManager()\r\n dcm.start()\r\n\r\n def handle_socket_message(msg):\r\n print(f\"message type: {msg['e']}\")\r\n print(msg)\r\n\r\n def handle_dcm_message(depth_cache):\r\n print(f\"symbol {depth_cache.symbol}\")\r\n print(\"top 5 bids\")\r\n print(depth_cache.get_bids()[:5])\r\n print(\"top 5 asks\")\r\n print(depth_cache.get_asks()[:5])\r\n print(\"last update time {}\".format(depth_cache.update_time))\r\n\r\n twm.start_kline_socket(callback=handle_socket_message, symbol='BNBBTC')\r\n\r\n dcm.start_depth_cache(callback=handle_dcm_message, symbol='ETHBTC')\r\n\r\n # replace with a current options symbol\r\n options_symbol = 'BTC-210430-36000-C'\r\n dcm.start_options_depth_cache(callback=handle_dcm_message, symbol=options_symbol)\r\n\r\n # join the threaded managers to the main thread\r\n twm.join()\r\n dcm.join()\r\n\r\nFor more `check out the documentation <https://python-binance.readthedocs.io/en/latest/>`_.\r\n\r\nAsync Example\r\n-------------\r\n\r\nRead `Async basics for Binance <https://sammchardy.github.io/binance/2021/05/01/async-binance-basics.html>`_\r\nfor more information.\r\n\r\n.. code:: python\r\n\r\n import asyncio\r\n import json\r\n\r\n from binance import AsyncClient, DepthCacheManager, BinanceSocketManager\r\n\r\n async def main():\r\n\r\n # initialise the client\r\n client = await AsyncClient.create()\r\n\r\n # run some simple requests\r\n print(json.dumps(await client.get_exchange_info(), indent=2))\r\n\r\n print(json.dumps(await client.get_symbol_ticker(symbol=\"BTCUSDT\"), indent=2))\r\n\r\n # initialise websocket factory manager\r\n bsm = BinanceSocketManager(client)\r\n\r\n # create listener using async with\r\n # this will exit and close the connection after 5 messages\r\n async with bsm.trade_socket('ETHBTC') as ts:\r\n for _ in range(5):\r\n res = await ts.recv()\r\n print(f'recv {res}')\r\n\r\n # get historical kline data from any date range\r\n\r\n # fetch 1 minute klines for the last day up until now\r\n klines = client.get_historical_klines(\"BNBBTC\", AsyncClient.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\")\r\n\r\n # use generator to fetch 1 minute klines for the last day up until now\r\n async for kline in await client.get_historical_klines_generator(\"BNBBTC\", AsyncClient.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\"):\r\n print(kline)\r\n\r\n # fetch 30 minute klines for the last month of 2017\r\n klines = client.get_historical_klines(\"ETHBTC\", Client.KLINE_INTERVAL_30MINUTE, \"1 Dec, 2017\", \"1 Jan, 2018\")\r\n\r\n # fetch weekly klines since it listed\r\n klines = client.get_historical_klines(\"NEOBTC\", Client.KLINE_INTERVAL_1WEEK, \"1 Jan, 2017\")\r\n\r\n # setup an async context the Depth Cache and exit after 5 messages\r\n async with DepthCacheManager(client, symbol='ETHBTC') as dcm_socket:\r\n for _ in range(5):\r\n depth_cache = await dcm_socket.recv()\r\n print(f\"symbol {depth_cache.symbol} updated:{depth_cache.update_time}\")\r\n print(\"Top 5 asks:\")\r\n print(depth_cache.get_asks()[:5])\r\n print(\"Top 5 bids:\")\r\n print(depth_cache.get_bids()[:5])\r\n\r\n # Vanilla options Depth Cache works the same, update the symbol to a current one\r\n options_symbol = 'BTC-210430-36000-C'\r\n async with OptionsDepthCacheManager(client, symbol=options_symbol) as dcm_socket:\r\n for _ in range(5):\r\n depth_cache = await dcm_socket.recv()\r\n count += 1\r\n print(f\"symbol {depth_cache.symbol} updated:{depth_cache.update_time}\")\r\n print(\"Top 5 asks:\")\r\n print(depth_cache.get_asks()[:5])\r\n print(\"Top 5 bids:\")\r\n print(depth_cache.get_bids()[:5])\r\n\r\n await client.close_connection()\r\n\r\n if __name__ == \"__main__\":\r\n\r\n loop = asyncio.get_event_loop()\r\n loop.run_until_complete(main())\r\n\r\n\r\nDonate\r\n------\r\n\r\nIf this library helped you out feel free to donate.\r\n\r\n- ETH: 0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70\r\n- LTC: LPC5vw9ajR1YndE1hYVeo3kJ9LdHjcRCUZ\r\n- NEO: AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBo\r\n- BTC: 1Dknp6L6oRZrHDECRedihPzx2sSfmvEBys\r\n\r\nOther Exchanges\r\n---------------\r\n\r\nIf you use `Binance Chain <https://testnet.binance.org/>`_ check out my `python-binance-chain <https://github.com/sammchardy/python-binance-chain>`_ library.\r\n\r\nIf you use `Kucoin <https://www.kucoin.com/?rcode=E42cWB>`_ check out my `python-kucoin <https://github.com/sammchardy/python-kucoin>`_ library.\r\n\r\nIf you use `IDEX <https://idex.market>`_ check out my `python-idex <https://github.com/sammchardy/python-idex>`_ library.\r\n\r\n.. image:: https://ga-beacon.appspot.com/UA-111417213-1/github/python-binance?pixel&useReferer\r\n\r\n\r\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Binance REST API python implementation",
"version": "1.0.16",
"split_keywords": [
"binance",
"exchange",
"rest",
"api",
"bitcoin",
"ethereum",
"btc",
"eth",
"neo"
],
"urls": [
{
"comment_text": "",
"digests": {
"md5": "f91db3d4a50cfa6560900a7d523ad7ce",
"sha256": "f9e7ef8624afc70516dd3c8925ab51e21784f84c61b8130d791b4b19d9d160f6"
},
"downloads": -1,
"filename": "python-binance-fixed-1.0.16.tar.gz",
"has_sig": false,
"md5_digest": "f91db3d4a50cfa6560900a7d523ad7ce",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 66335,
"upload_time": "2022-12-19T13:26:27",
"upload_time_iso_8601": "2022-12-19T13:26:27.503544Z",
"url": "https://files.pythonhosted.org/packages/25/50/53a130bfc8592b082154027632a585d936de6168728be473200e22dbd430/python-binance-fixed-1.0.16.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2022-12-19 13:26:27",
"github": true,
"gitlab": false,
"bitbucket": false,
"github_user": "Immortalion",
"github_project": "python-binance-fixed",
"travis_ci": true,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "aiohttp",
"specs": []
},
{
"name": "dateparser",
"specs": []
},
{
"name": "requests",
"specs": []
},
{
"name": "ujson",
"specs": []
},
{
"name": "websockets",
"specs": []
}
],
"tox": true,
"lcname": "python-binance-fixed"
}