View python-binance on Snyk Open Source Advisor (2024)

Updated 11th Aug 2023

View python-binance on Snyk Open Source Advisor (1)

View python-binance on Snyk Open Source Advisor (2)

View python-binance on Snyk Open Source Advisor (3)

View python-binance on Snyk Open Source Advisor (4)

View python-binance on Snyk Open Source Advisor (5)

View python-binance on Snyk Open Source Advisor (6)

This is an unofficial Python wrapper for the Binance exchange REST APIv3. I am in no wayaffiliated with Binance, use at your own risk.

If you came here looking for the Binanceexchange to purchasecryptocurrencies, 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 mypython-binance-chainlibrary

Source code

Documentation

Binance API Telegram

Blog with examples including async

Make sure you update often and check theChangelogfor 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 include RSA keys
  • 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 endpointswhich related to the wallet endpoints detailed in the BinanceDocs

The other breaking change is for websocket streams and the Depth CacheManager which have been converted to use Asynchronous Context Managers.See examples in the Async section below or view thewebsocketsand depthcachedocs.

Quick Start

Register an account withBinance.

Generate an APIKey and assignrelevant permissions.

If you are using an exchange from the US, Japan or other TLD then makesure pass tld='us' when creating theclient.

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

pip install python-binance
from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManagerclient = Client(api_key, api_secret)# get market depthdepth = client.get_order_book(symbol='BNBBTC')# place a test market buy order, to place an actual order use the create_order functionorder = client.create_test_order( symbol='BNBBTC', side=Client.SIDE_BUY, type=Client.ORDER_TYPE_MARKET, quantity=100)# get all symbol pricesprices = client.get_all_tickers()# withdraw 100 ETH# check docs for assumptions around withdrawalsfrom binance.exceptions import BinanceAPIExceptiontry: result = client.withdraw( asset='ETH', address='', amount=100)except BinanceAPIException as e: print(e)else: print("Success")# fetch list of withdrawalswithdraws = client.get_withdraw_history()# fetch list of ETH withdrawalseth_withdraws = client.get_withdraw_history(coin='ETH')# get a deposit address for BTCaddress = client.get_deposit_address(coin='BTC')# get historical kline data from any date range# fetch 1 minute klines for the last day up until nowklines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")# fetch 30 minute klines for the last month of 2017klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018")# fetch weekly klines since it listedklines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan, 2017")# socket manager using threadstwm = ThreadedWebsocketManager()twm.start()# depth cache manager using threadsdcm = 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 symboloptions_symbol = 'BTC-210430-36000-C'dcm.start_options_depth_cache(callback=handle_dcm_message, symbol=options_symbol)# join the threaded managers to the main threadtwm.join()dcm.join()

For more check out thedocumentation.

Async Example

Read Async basics forBinancefor more information.

import asyncioimport jsonfrom binance import AsyncClient, DepthCacheManager, BinanceSocketManagerasync 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 check out mypython-binance-chainlibrary.

If you use Kucoin check out mypython-kucoin library.

If you use IDEX check out mypython-idex library.

View python-binance on Snyk Open Source Advisor (7)

View python-binance on Snyk Open Source Advisor (2024)

FAQs

How to get data from Binance API Python? ›

We start with our imports. We will need the Client class from the python-binance library as well as the os library to retrieve the API keys that we stored as environment variables. Next, we store our API key and secret to local variables. And finally, we initialize our client and pass through the API key and secret.

How to web scrape Binance? ›

To extract information from Binance, simply construct a payload incorporating job parameters and the Binance website URL. Following this, transmit the request to our API and obtain the outcomes in HTML format. See the output example on the right and visit our documentation to find more details.

Is Binance API free? ›

Binance offers a free API that allows developers to interact with the Binance platform and create custom trading applications. However, there are certain usage limits and policies that developers must adhere to, including rate limiting, data caching, and more.

What programming language is Binance built with? ›

The majority of developers at Binance use C++ in order to build our exchange and back-end trading engine. Most of the machine learning we do is written in Python.

How do I get transaction data from Binance? ›

Log into your Binance account. Navigate to wallet. select Spot. Choose the coin and then view the transaction history.

How do I get Binance market data? ›

To get started, visit the Historical Market Data page to browse available data products. You can download our free datasets as a . zip file, or follow the instructions on the page to download programmatically.

How do I enable reading in Binance API? ›

After creating the API key, the default restrictions is Enable Reading . To enable withdrawals via the API, the API key restriction needs to be modified through the Binance UI.

Top Articles
Vanguard VIU ETF Review 2024: Invest Beyond North America
VT Vs. VTI - Which Best Low-Cost ETF Should You Invest In?
Funny Roblox Id Codes 2023
Live Basketball Scores Flashscore
Fat People Falling Gif
Craigslist Cars And Trucks For Sale By Owner Indianapolis
Recent Obituaries Patriot Ledger
Craigslist Furniture Bedroom Set
craigslist: south coast jobs, apartments, for sale, services, community, and events
Smokeland West Warwick
2013 Chevy Cruze Coolant Hose Diagram
Conduent Connect Feps Login
4302024447
Uhcs Patient Wallet
Gmail Psu
Clarksburg Wv Craigslist Personals
D10 Wrestling Facebook
Xomissmandi
Gemita Alvarez Desnuda
Foxy Brown 2025
Dwc Qme Database
The Listings Project New York
Target Minute Clinic Hours
Amelia Chase Bank Murder
Wat is een hickmann?
Cable Cove Whale Watching
Spectrum Outage in Queens, New York
Craigslist Sf Garage Sales
Otis Inmate Locator
Christmas Days Away
Jeep Cherokee For Sale By Owner Craigslist
Sports Clips Flowood Ms
Royal Caribbean Luggage Tags Pending
Http://N14.Ultipro.com
Goodwill Thrift Store & Donation Center Marietta Photos
Why The Boogeyman Is Rated PG-13
Instafeet Login
Philadelphia Inquirer Obituaries This Week
Ksu Sturgis Library
Craigslist Putnam Valley Ny
Engr 2300 Osu
Devon Lannigan Obituary
Joey Gentile Lpsg
Jamesbonchai
Thotsbook Com
Woody Folsom Overflow Inventory
Online-Reservierungen - Booqable Vermietungssoftware
Human Resources / Payroll Information
Accident On 40 East Today
Graduation Requirements
Where Is Darla-Jean Stanton Now
Bones And All Showtimes Near Emagine Canton
Latest Posts
Article information

Author: Horacio Brakus JD

Last Updated:

Views: 6282

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Horacio Brakus JD

Birthday: 1999-08-21

Address: Apt. 524 43384 Minnie Prairie, South Edda, MA 62804

Phone: +5931039998219

Job: Sales Strategist

Hobby: Sculling, Kitesurfing, Orienteering, Painting, Computer programming, Creative writing, Scuba diving

Introduction: My name is Horacio Brakus JD, I am a lively, splendid, jolly, vivacious, vast, cheerful, agreeable person who loves writing and wants to share my knowledge and understanding with you.