{"id":3744,"date":"2020-06-30T10:14:32","date_gmt":"2020-06-30T10:14:32","guid":{"rendered":"http:\/\/algotrading101.com\/learn\/?p=3744"},"modified":"2023-04-04T20:29:56","modified_gmt":"2023-04-04T20:29:56","slug":"binance-python-api-guide","status":"publish","type":"post","link":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/","title":{"rendered":"Binance Python API \u2013 A Step-by-Step Guide"},"content":{"rendered":"<div class=\"pvc_clear\"><\/div><p id=\"pvc_stats_3744\" class=\"pvc_stats total_only  \" data-element-id=\"3744\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p><div class=\"pvc_clear\"><\/div>\n<h2 class=\"wp-block-heading\">Table of Contents<\/h2>\n\n\n\n<ol><li><a href=\"#what-is-the-binance-api\">What is the Binance API?<\/a><\/li><li><a href=\"#why-should-i-use-the-binance-api\">Why should I use the Binance API?<\/a><\/li><li><a href=\"#why-should-i-not-use-the-binance-api\">Why shouldn\u2019t I use the Binance API?<\/a><\/li><li><a href=\"#what-are-alternatives-to-binance-api\">What are the alternatives to using the Binance API?<\/a><\/li><li><a href=\"#are-there-python-libraries-binance-api\">Are there any Python libraries available for the Binance API?<\/a><\/li><li><a href=\"#how-do-start-with-binance-api\">How do I get started with the Binance API?<\/a><\/li><li><a href=\"#does-binance-offer-a-demo-account\">Does Binance offer a demo account?<\/a><\/li><li><a href=\"#how-do-i-retrieve-account-balance\">How do I retrieve my account balance using the Binance API?<\/a><\/li><li><a href=\"#how-do-i-get-latest-bitcoin-price\">How can I retrieve the latest price for Bitcoin?<\/a><\/li><li><a href=\"#how-do-i-get-bitcoin-historical-csv-data\">How can I get Bitcoin\u2019s historical price data in CSV format?<\/a><\/li><li><a href=\"#should-i-trade-spot-or-futures\">Should I trade futures or spot? What is the difference?<\/a><\/li><li><a href=\"#technical-indicators-binance-api\">How to access technical indicators such as the 20 SMA<\/a><\/li><li><a href=\"#fire-an-ethereum-order-binance-api\">How to fire an order for Ethereum using the Binance API<\/a><\/li><li><a href=\"#implement-stop-loss-binance-api\">How to implement a stop loss or take profit using the Binance API<\/a><\/li><li><a href=\"#use-bnb-for-discount-trading-fees\">How to use Binance Coin (BNB) for discounted trading commissions<\/a><\/li><li><a href=\"#execute-eth-trade-on-bitcoin-price\">How to execute a trade on ETH when BTC hits a certain price<\/a><\/li><li><a href=\"#execute-eth-trade-on-btc-price-movement\">How to execute an ETH trade when BTC moves 5% in the last 5 minutes<\/a><\/li><li><a href=\"#final-thoughts\">Final Thoughts<\/a><\/li><\/ol>\n\n\n\n<figure class=\"wp-block-image size-large\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1024\" height=\"670\" src=\"http:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api-1024x670.jpg\" alt=\"Create API page on Binance\" class=\"wp-image-3661\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api-1024x670.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api-300x196.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api-768x502.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api.jpg 1297w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-the-binance-api\">What is the Binance API?<\/h2>\n\n\n\n<p>The Binance API is a method that allows you to connect to the Binance servers via Python or several other programming languages. With it, you can automate your trading.<\/p>\n\n\n\n<p>More specifically, Binance has a RESTful API that uses HTTP requests to send and receive data. Further, there is also a WebSocket available that enables the streaming of data such as price quotes and account updates.<\/p>\n\n\n\n<p>Link: <a href=\"https:\/\/www.binance.com\/en\">https:\/\/www.binance.com\/en<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"why-should-i-use-the-binance-api\">Why should I use the Binance API?<\/h2>\n\n\n\n<p>Binance has established itself as a market leader when it comes to cryptocurrency trading. It currently ranks number one for Bitcoin volume according to coinmarketcap.com and ranks well for many other currencies.<\/p>\n\n\n\n<p>Commissions are very competitive and you may be hard-pressed to find another exchange with lower fees.<\/p>\n\n\n\n<p>Lastly, Binance has a good track record of security. There have only been a few instances of Binance getting hacked which is something that all exchanges are susceptible to due to the nature of the business.<\/p>\n\n\n\n<p>The most important part, when Binance got hacked in 2019, and more than $40 million was stolen, Binance covered the users that were impacted.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"why-should-i-not-use-the-binance-api\">Why shouldn\u2019t I use the Binance API?<\/h2>\n\n\n\n<p>While security is a big plus point for Binance when it comes to exchanges, there are better alternatives, depending on your needs.<\/p>\n\n\n\n<p>If your primary interest is trading Bitcoin, you might be better off trading Bitcoin futures with a regulated broker like Interactive Brokers for example.<\/p>\n\n\n\n<p>The benefit of a regulated broker is that they have insurance schemes in place to protect the consumer.<\/p>\n\n\n\n<p>If trading futures is not your thing, there are several regulated brokers that offer CFD trading on cryptocurrencies which can be a good alternative.<\/p>\n\n\n\n<p>It should be noted that these options don&#8217;t have nearly as extensive of an offering as Binance. And in most cases, the trading fees are significantly higher.<\/p>\n\n\n\n<p>Another challenge with API trading at Binance is that API changes occur often.<\/p>\n\n\n\n<p>API changes are generally a good thing. It means the exchange is trying to update and improve their infrastructure (most of the time).<\/p>\n\n\n\n<p>However, this involves keeping a close eye on Binance&#8217;s API announcements and updating our trading algorithms as required. Not all changes will lead to our code breaking, but some of them certainly can.<\/p>\n\n\n\n<p>There are also outages. In late 2020, Binance took its API offline roughly once a month for a few hours each time for planned updates. This requires manual intervention and additional position management for algo traders.<\/p>\n\n\n\n<p>In early 2021, amidst a surge in crypto prices, Binance experienced outages during volatile times due to an influx of new users signing up and a sharp rise in trading volume.<\/p>\n\n\n\n<p>Binance CEO Changpeng Zhao, better known as CZ, has commented several times that outages are normal in a growing industry such as crypto, and that users should expect it could happen again in the future.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-are-alternatives-to-binance-api\">What are the alternatives to using the Binance API?<\/h2>\n\n\n\n<p>Coinmarketcap has more than 300 exchanges listed in its database, and many of them offer an API. So there isn&#8217;t a shortage of alternatives.<\/p>\n\n\n\n<p>Some of the names that stand out from their list as well-established exchanges include Coinbase, Kraken, Bitfinex, Bitstamp, and Bittrex.<\/p>\n\n\n\n<p>Futures traders may also want to take a look at Bitmex which is a popular exchange with competitive commissions. They even pay you for certain order types rather than charging a trading fee.<\/p>\n\n\n\n<div style=\"padding:15px 15px 15px 15px;color: #555555;background-color: #E1FFC1;border: #dddddd 2px solid\"><p>\u00bb Before you run your strategies, you need data to design and backtest them. Quandl provides (mostly) free data that can be useful.\n\n<br><br>\nHere is a guide: <a href=\"https:\/\/algotrading101.com\/learn\/quandl-guide\/\" rel=\"noopener noreferrer\">Quandl: A Step-by-Step Guide<\/a>\n<br><br>(Yes, Quandl has crypto data such as <a href=\"https:\/\/www.quandl.com\/data\/BITFINEX-Bitfinex\" target=\"_blank\" rel=\"noopener noreferrer\">this<\/a> and <a href=\"https:\/\/www.quandl.com\/databases\/BICRS\/data\" target=\"_blank\" rel=\"noopener noreferrer\">this<\/a>)\n<\/p>\n\n<\/div>\n<br>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"are-there-python-libraries-binance-api\">Are there any Python libraries available for the Binance API?<\/h2>\n\n\n\n<p>There are several third-party libraries available, the most popular is&nbsp;<a target=\"_blank\" href=\"https:\/\/github.com\/sammchardy\/python-binance\" rel=\"noreferrer noopener\">python-binance<\/a>.<\/p>\n\n\n\n<p>There is an interesting story on how this library came to be the most popular Python library for Binance.<\/p>\n\n\n\n<p>When Binance launched in 2017, they held a contest to see who can come up with the best library for various different programming languages. The winners were each rewarded 1000 Binance coins (BNB).&nbsp;<\/p>\n\n\n\n<p>At the time of the contest, BNB was trading below $2 but it surged to a high $691 in the first half of 2021!<\/p>\n\n\n\n<p>There were several good submissions for the Python category but python-binance ultimately won.<\/p>\n\n\n\n<p>This was a clever approach to ensure the best developers worked hard to create a good library.&nbsp;<\/p>\n\n\n\n<p>Another popular library is&nbsp;<a target=\"_blank\" href=\"https:\/\/github.com\/ccxt\/ccxt\" rel=\"noreferrer noopener\">CCXT<\/a>. This library supports over a hundred different exchanges and is available in many different programming languages.<\/p>\n\n\n\n<p>A third and perhaps lesser known option is <a href=\"https:\/\/github.com\/binance\/binance-connector-python\">Binance Connector<\/a> which appears like it could be an official library as it is hosted under Binance&#8217;s Github page. There is also a recommendation and link to it in the Binance API documentation.<\/p>\n\n\n\n<p>CCXT is a good option if you plan to trade on multiple exchanges, or want the flexibility of switching to another exchange down the road without having to fully relearn another library.<\/p>\n\n\n\n<p>The advantage to Python Binance is that a lot of people use it so it&#8217;s easy to get support and help from other users.<\/p>\n\n\n\n<p>Lastly, Binance connector seems like it is often updated and a great library all around. The downside, however, is that the learning curve for it might be steep as there isn&#8217;t a lot of documentation or usage examples available for it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-do-start-with-binance-api\">How do I get started with the Binance API?<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Sign up with Binance<\/h3>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1024\" height=\"850\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/register_binance-1024x850.jpg\" alt=\"\" class=\"wp-image-3730\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/register_binance-1024x850.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/register_binance-300x249.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/register_binance-768x637.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/register_binance.jpg 1080w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>The first step is to create an account with Binance. You only need to enter your email and create a password &#8211; <a rel=\"noreferrer noopener\" href=\"https:\/\/accounts.binance.com\/en\/register\" target=\"_blank\">https:\/\/accounts.binance.com\/en\/register<\/a><\/p>\n\n\n\n<p>Optionally, if you&#8217;re interested in using a Referral ID, you can use ZCYOCDMQ to receive a 10% discount off your trading fees.<\/p>\n\n\n\n<p class=\"has-small-font-size\">That&#8217;s my Referral ID, thanks for supporting me! &#8211; Jignesh<\/p>\n\n\n\n<p>You will be asked if you want to enable two-factor authentication for additional security. We highly recommend that you do. If you&#8217;ve never used it before, you will need to <a rel=\"noreferrer noopener\" href=\"https:\/\/support.google.com\/accounts\/answer\/1066447\" target=\"_blank\">install Google Authenticator<\/a>.<\/p>\n\n\n\n<p>There are tutorials on getting started on things like your first deposit and much more on <a rel=\"noreferrer noopener\" href=\"https:\/\/academy.binance.com\/tutorials\" target=\"_blank\">Binance Academy<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Obtaining an API key<\/h3>\n\n\n\n<p>After logging in to your Binance account, click on the profile icon on the top right-hand side of the screen. From there, select API Management.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"343\" height=\"525\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/API_management-1.jpg\" alt=\"\" class=\"wp-image-3663\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/API_management-1.jpg 343w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/API_management-1-196x300.jpg 196w\" sizes=\"(max-width: 343px) 100vw, 343px\" \/><\/figure>\n\n\n\n<p>Next, you will be asked to create a label for the API key. If you plan to create multiple keys, it&#8217;s a good idea to use a descriptive name here so that you can easily distinguish it later on.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"670\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api-1024x670.jpg\" alt=\"\" class=\"wp-image-3661\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api-1024x670.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api-300x196.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api-768x502.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api.jpg 1297w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>If you have two-factor authentication enabled, you will be asked to authenticate once again at this point.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"557\" height=\"646\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/api_verify_email.jpg\" alt=\"\" class=\"wp-image-3664\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/api_verify_email.jpg 557w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/api_verify_email-259x300.jpg 259w\" sizes=\"(max-width: 557px) 100vw, 557px\" \/><\/figure>\n\n\n\n<p>Binance will send you an email to confirm the API key creation. Click on the confirmation link from your confirmation email to proceed.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"947\" height=\"371\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/api_created.jpg\" alt=\"\" class=\"wp-image-3665\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/api_created.jpg 947w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/api_created-300x118.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/api_created-768x301.jpg 768w\" sizes=\"(max-width: 947px) 100vw, 947px\" \/><\/figure>\n\n\n\n<p>Your API key should be created at this point. Note that this is the only time your API secret will be revealed. If you navigate away from this screen, you will not be able to see it again.<\/p>\n\n\n\n<p>In such a scenario, you will need to delete your API key and start over again by creating a new one.<\/p>\n\n\n\n<p>Guard your API details as you would with any password as anyone can get access to your account if they were able to get a hold of this information.<\/p>\n\n\n\n<p>Before moving forward, there are a few settings here that we need to take a look at.<\/p>\n\n\n\n<p>The <strong>Read Only<\/strong> option is selected by default, and you likely won&#8217;t be able to uncheck it.<\/p>\n\n\n\n<p>This permits the API to read your account details and is enabled by default. Perhaps it is a bit misleading since it includes the term <strong>Only<\/strong>, but you can still perform other operations with this option checked.<\/p>\n\n\n\n<p>There is also an option to <strong>Enable Trading<\/strong>, <strong>Enable Withdrawals<\/strong>, and <strong>Enable Future<\/strong>.<\/p>\n\n\n\n<p>If you&#8217;re still testing out the API, it might be a good idea to leave these unchecked. If you&#8217;re ready to start trading, then check off the Enable Trading box and the Enable Future box if you plan to trade futures.<\/p>\n\n\n\n<p>For some people, the Enable Future box won&#8217;t be shown here. That means the account is not set up for trading futures.<\/p>\n\n\n\n<p>Note: if the Enable Futures box is shown, you should still set up your futures account first before attempting to create an API key (if you plan to trade futures). Otherwise, it may lead to API authentication errors.<\/p>\n\n\n\n<p>It is easy to setup Futures trading on your account if it is not already enabled. From the main Binance login page, click on the <strong>Derivatives<\/strong> option in the top menu bar.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"975\" height=\"162\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/derivatives.jpg\" alt=\"\" class=\"wp-image-3666\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/derivatives.jpg 975w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/derivatives-300x50.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/derivatives-768x128.jpg 768w\" sizes=\"(max-width: 975px) 100vw, 975px\" \/><\/figure>\n\n\n\n<p>From there, click on Futures which should take you to the Futures trading screen. There should be an option on that page to open a Futures account.<\/p>\n\n\n\n<p>If you plan to make withdrawals from within your Python trading script, you will need to enable it. To do so, you have to specify the IP address from where the script will be accessing the API. This is for security purposes.<\/p>\n\n\n\n<p>If you intend on running your script from a virtual private server such as AWS, this shouldn&#8217;t be a big problem. However, if you are running the script from your local machine, you could run into issues as most internet service providers do not offer static IP addresses.<\/p>\n\n\n\n<p>There are third-party solutions, such as noip.com that provide a way around not having a static IP.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Installing the python-binance library<\/h3>\n\n\n\n<p>The easiest way to install the python-binance library is to use pip. From the command line, simply type:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>pip install python-binance<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Securing your API keys<\/h3>\n\n\n\n<p>We recommend storing your API keys as environment variables. That way, if you upload your code to GitHub, or send it to someone, you don&#8217;t run at the risk of revealing your credentials.<\/p>\n\n\n\n<p>This can be done via the command prompt. Here is the syntax for Windows users.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>set binance_api=your_api_key_here\nset binance_secret=your_api_secret_here<\/code><\/pre>\n\n\n\n<p>You can verify that the keys are saved right from the command prompt by launching Python. Here is an example:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"784\" height=\"338\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/win_environ-1.jpg\" alt=\"\" class=\"wp-image-3670\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/win_environ-1.jpg 784w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/win_environ-1-300x129.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/win_environ-1-768x331.jpg 768w\" sizes=\"(max-width: 784px) 100vw, 784px\" \/><\/figure>\n\n\n\n<p>And this is how you can store environment variables on a Mac or in a Linux environment using the terminal.<\/p>\n\n\n\n<p>Syntax:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export binance_api=\"your_api_key_here\"\nexport binance_secret=\"your_api_secret_here\"<\/code><\/pre>\n\n\n\n<p>Example:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"981\" height=\"469\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/linux_environ-1.png\" alt=\"\" class=\"wp-image-3669\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/linux_environ-1.png 981w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/linux_environ-1-300x143.png 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/linux_environ-1-768x367.png 768w\" sizes=\"(max-width: 981px) 100vw, 981px\" \/><\/figure>\n\n\n\n<p>We can later retrieve these values from within our Python trading script by using the os library.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"does-binance-offer-a-demo-account\">Does Binance offer a demo account?<\/h2>\n\n\n\n<p>Before jumping into live trading with the Binance API, there is an option to test out your Python trading script on the Binance API testnet.<\/p>\n\n\n\n<p>Start by going to the Binance Spot Test Network website, you can find it here &#8211; <a href=\"https:\/\/testnet.binance.vision\/\">https:\/\/testnet.binance.vision\/<\/a><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"259\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_authenticate-1024x259.jpg\" alt=\"\" class=\"wp-image-3726\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_authenticate-1024x259.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_authenticate-300x76.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_authenticate-768x194.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_authenticate.jpg 1079w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>From there, you will have to create an account, even if  you already have an account with Binance.com. We only saw an option to log on with a GitHub account.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"714\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet-1024x714.jpg\" alt=\"\" class=\"wp-image-3727\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet-1024x714.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet-300x209.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet-768x535.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet.jpg 1080w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>Once you&#8217;re logged on, you will have to create new API keys. These will be separate from the keys created in the previous step and will be used only to access your demo account.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"346\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_apikeys-1024x346.jpg\" alt=\"\" class=\"wp-image-3729\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_apikeys-1024x346.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_apikeys-300x101.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_apikeys-768x260.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_apikeys.jpg 1079w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>Choose the option to generate a HMAC key. In the next step, enter in descriptive name for your key.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"377\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_name_key-1024x377.jpg\" alt=\"\" class=\"wp-image-3728\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_name_key-1024x377.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_name_key-300x111.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_name_key-768x283.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/testnet_name_key.jpg 1080w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>After clicking generate, you will be taken to a screen that displays your key. If you leave this screen, you won&#8217;t be able to access they secret key again, and will have to start over.<\/p>\n\n\n\n<p>Once you&#8217;re setup with the keys, all of the endpoints in the live API will be the same as in the Testnet API. The only difference is that you have to use a different URL to access Testnet.<\/p>\n\n\n\n<p>At the time of writing, the python-binance library, which we&#8217;ve used in all the examples, does not support the Test Network. However, we will discuss a workaround in the next step.<\/p>\n\n\n\n<p>Please note, Test Network accounts get deleted typically at the start of each month. Any open trades will be wiped out. More details about the Spot Test Network can be found on the same page where you go to create your key.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-do-i-retrieve-account-balance\">How do I retrieve my account balance using the Binance API?<\/h2>\n\n\n\n<p>Now that we&#8217;ve installed the library and obtained API keys, it&#8217;s time to test out a connection to the API. We will start up a client and check out four functions that detail different account balances.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\n\nfrom binance.client import Client<\/code><\/pre>\n\n\n\n<p>We start with our imports. We will need the <strong>Client <\/strong>class from the python-binance library as well as the <strong>os <\/strong>library to retrieve the API keys that we stored as environment variables.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># init\napi_key = os.environ.get('binance_api')\napi_secret = os.environ.get('binance_secret')<\/code><\/pre>\n\n\n\n<p>Next, we store our API key and secret to local variables.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>client = Client(api_key, api_secret)<\/code><\/pre>\n\n\n\n<p>And finally, we initialize our client and pass through the API key and secret. We are all set to start accessing the API at t his point.<\/p>\n\n\n\n<p>Unfortunately, the python-binance library does not have support for the demo environment previously discussed. However, we were able to connect by manually changing the API endpoint URL in the library like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>client.API_URL = 'https:\/\/testnet.binance.vision\/api'<\/code><\/pre>\n\n\n\n<p>If you decide to start with the demo API, make sure you are passing through your Test Network API credentials when initializing the Client and not the live API keys.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># get balances for all assets &amp; some account information\nprint(client.get_account())<\/code><\/pre>\n\n\n\n<p>The above code will print out all of our account details for every currency available on the platform. It will also provide some other info such as the current commission rate and if your account is enabled for margin trading.<\/p>\n\n\n\n<p>This might be a bit too much information. If we are only interested in our <strong>BTC <\/strong>balance, we can use another endpoint.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># get balance for a specific asset only (BTC)\nprint(client.get_asset_balance(asset='BTC'))<\/code><\/pre>\n\n\n\n<p>If you&#8217;re after the balance details of another asset, simply switch out <strong>BTC <\/strong>with the asset you are after.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># get balances for futures account\nprint(client.futures_account_balance())<\/code><\/pre>\n\n\n\n<p>Account balances for futures accounts are separate from the main balance and therefore require a different endpoint.<\/p>\n\n\n\n<p>Similarly, margin account details are separated as well. Here is how you can access your margin account. Note that an exception will be raised if you have not activated a margin account.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># get balances for margin account\nprint(client.get_margin_account())<\/code><\/pre>\n\n\n\n<p>If you&#8217;re not familiar with margin trading, you can check out the Binance guide: <a rel=\"noreferrer noopener\" href=\"https:\/\/academy.binance.com\/economics\/what-is-margin-trading\" target=\"_blank\">What is Margin Trading<\/a> for more details and the <a href=\"https:\/\/academy.binance.com\/tutorials\/binance-margin-trading-guide\" target=\"_blank\" rel=\"noreferrer noopener\">Binance Margin Trading Guide<\/a> for setup instructions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-do-i-get-latest-bitcoin-price\">How can I retrieve the latest price for Bitcoin?<\/h2>\n\n\n\n<p>There are several methods to get the latest price for Bitcoin. The simplest one involves using the <code>get_symbol_ticker<\/code> function.<\/p>\n\n\n\n<p>You can pass through any ticker here as opposed to <strong>BTCUSDT<\/strong> if you&#8217;re after another asset.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># get latest price from Binance API\nbtc_price = client.get_symbol_ticker(symbol=\"BTCUSDT\")\n# print full output (dictionary)\nprint(btc_price)<\/code><\/pre>\n\n\n\n<p>The code above will print out a dictionary that contains the symbol and the price. Here is an example output &#8211;&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{'symbol': 'BTCUSDT', 'price': '9678.08000000'}<\/code><\/pre>\n\n\n\n<p>We can access just the price as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(btc_price&#91;\"price\"])<\/code><\/pre>\n\n\n\n<p>In a live Python trading script, we would likely need up to date price information for the asset that we are trading. Fortunately, there is a better solution than constantly making requests to the API. It involves using Binance WebSocket.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using the Binance WebSocket for the latest Bitcoin price<\/h3>\n\n\n\n<p>The Binance WebSocket requires us to only send a command once to open up a stream, and then data will automatically stream over as prices get updated.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from time import sleep\n\nfrom binance import ThreadedWebsocketManager<\/code><\/pre>\n\n\n\n<p>We need to import the ThreadedSocketManager to use this function, along with the sleep function from the time module. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>btc_price = {'error':False}<\/code><\/pre>\n\n\n\n<p>Next we will create a dictionary that will hold our latest price data and also let us known if there is a problem with the websocket.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def btc_trade_history(msg):\n    ''' define how to process incoming WebSocket messages '''\n    if msg&#91;'e'] != 'error':\n\tprint(msg&#91;'c'])\n\tbtc_price&#91;'last'] = msg&#91;'c']\n\tbtc_price&#91;'bid'] = msg&#91;'b']\n\tbtc_price&#91;'last'] = msg&#91;'a']\n\tbtc_price&#91;'error'] = False\n    else:\n        btc_price&#91;'error'] = True<\/code><\/pre>\n\n\n\n<p>Then, we will create a function that will tell the socket manager what to do when it receives new data.<\/p>\n\n\n\n<p>For now, we will just print the last closing price to the screen.<\/p>\n\n\n\n<p>We are also storing a few items to the dictionary file that we created earlier. This allows us to access the data outside the function and this is how you would typically access websocket data from your main trading script.<\/p>\n\n\n\n<p>Aside from the latest price, bid, and ask, we also have error checking built in. This will let us know if there is an error with the Binance WebSocket, in which case we will need to restart it.<\/p>\n\n\n\n<p>A latter example involving the websocket expands on the error checking part.<\/p>\n\n\n\n<p>You may have noticed that Binance doesn&#8217;t use full variable names. IE the close price comes over the websocket in a variable called &#8216;c&#8217; rather than &#8216;close&#8217;. Binance probably did this to keep the overall size of the message minimal in an attempt to boost communication speed.<\/p>\n\n\n\n<p>If you&#8217;re ever trying to program a new websocket connection and are unsure what the variables stand for, check out the <a href=\"https:\/\/binance-docs.github.io\/apidocs\/spot\/en\/\">Binance API documentation<\/a>. They have a detailed explanation of what each component of the websocket message is used for.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># init and start the WebSocket\nbsm = ThreadedWebsocketManager()\nbsm.start()<\/code><\/pre>\n\n\n\n<p>The next step is to initialize the socket manager. When we do that, the library will create a new thread which we&#8217;ve started in the code snippet above.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># subscribe to a stream\nbsm.start_symbol_ticker_socket(callback=btc_trade_history, symbol='BTCUSDT')<\/code><\/pre>\n\n\n\n<p>We will call the <code>start_symbol_ticker_socket<\/code> which has similar output to the <code>get_symbol_ticker<\/code> function of the API that we discussed earlier.<\/p>\n\n\n\n<p>We need to pass through a symbol, which in this case is <strong>BTCUSDT<\/strong>. We also specify it to call our custom <code>btc_trade_history<\/code> function every time a new message comes in.<\/p>\n\n\n\n<p>If you&#8217;re following along, you should see a stream of prices on your screen if you run the above code. It should look similar to the <strong>Trade History<\/strong> box that is on the Binance webpage under the spot trading section.<\/p>\n\n\n\n<p>In a live Python trading script, you will access the data from the dictionary file outside the function as opposed to printing the data to screen from the function.<\/p>\n\n\n\n<p>Binance has several websocket streams and we can easily add more.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bsm.start_symbol_ticker_socket(callback=btc_trade_history, symbol='ETHUSDT')<\/code><\/pre>\n\n\n\n<p>The code snippet above subscribes to the ticker price for ETHUSDT. We kept the callback as <strong>btc_trade_history<\/strong>. That means when a new message arrives for ETHUSDT, it will get handled by the same <strong>btc_trade_history <\/strong>function we created.<\/p>\n\n\n\n<p>This is just for example purposes, to show how you can easily add more streams. You can choose to create a separate function for other streams if need be.<\/p>\n\n\n\n<p>When you&#8217;re done with the WebSocket, use the following syntax to properly terminate it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># stop websocket\nbsm.stop()<\/code><\/pre>\n\n\n\n<p>The WebSocket can deliver various data. To get a full view of what is available, type the following in your Python terminal.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>help(ThreadedWebsocketManager)<\/code><\/pre>\n\n\n\n<p>This will list all the different methods available as well as give some information about the returned data.<\/p>\n\n\n\n<p>Here is an example for the start_symbol_ticker_socket:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"952\" height=\"718\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/websocket_symbol_ticker.jpg\" alt=\"\" class=\"wp-image-3671\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/websocket_symbol_ticker.jpg 952w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/websocket_symbol_ticker-300x226.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/websocket_symbol_ticker-768x579.jpg 768w\" sizes=\"(max-width: 952px) 100vw, 952px\" \/><\/figure>\n\n\n\n<p>As you can see it gives a brief description, a link to the official Binance documentation about that function, and some details about the returned data.<\/p>\n\n\n\n<p>This is another way to figure out that <code>msg['b']<\/code> returns the best bid, besides checking the documentation. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-do-i-get-bitcoin-historical-csv-data\">How can I get Bitcoin&#8217;s historical price data in CSV format?<\/h2>\n\n\n\n<p>We will request historical Bitcoin price data from the Binance API and then outline four options to save that data to a CSV file.<\/p>\n\n\n\n<p>We want data that goes as far back as possible. Fortunately, there is a function within the library that allows us to determine the first available price point.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># valid intervals - 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M\n\n# get timestamp of earliest date data is available\ntimestamp = client._get_earliest_valid_timestamp('BTCUSDT', '1d')\nprint(timestamp)<\/code><\/pre>\n\n\n\n<p>In the code snippet above, we&#8217;ve called the <code>._get_earliest_valid_timestamp<\/code> function and passed in <strong>BTCUSDT <\/strong>as our symbol and <strong>1d <\/strong>as our timeframe. The output is saved to a variable.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># request historical candle (or klines) data\nbars = client.get_historical_klines('BTCUSDT', '1d', timestamp, limit=1000)<\/code><\/pre>\n\n\n\n<p>Next, we make the call for historical data. Once again we need to pass through the symbol and variable. Also, a starting date is required and we&#8217;ve used our timestamp variable for that.<\/p>\n\n\n\n<p>Lastly, this function by default calls the last 500 points of data. The maximum is 1000 so we&#8217;ve increased the limit to the maximum.<\/p>\n\n\n\n<p>In the background, this endpoint will continuously query the API in a loop, collecting 1000 price points at a time, until all data from the start point until today is returned.<\/p>\n\n\n\n<p>In an effort to be &#8216;kind&#8217; to the API, there is a sleep function built-in after every third call. So this could take a while if you&#8217;re looking for say 1-minute data from the very start.<\/p>\n\n\n\n<p>Binance began operations over the summer of 2017, so that will likely be the earliest price point available.<\/p>\n\n\n\n<p>Here is a definition of the data returned as per the Binance API documentation.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"728\" height=\"496\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/historical_kline_return.jpg\" alt=\"\" class=\"wp-image-3672\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/historical_kline_return.jpg 728w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/historical_kline_return-300x204.jpg 300w\" sizes=\"(max-width: 728px) 100vw, 728px\" \/><\/figure>\n\n\n\n<p>Now that we have our date, let&#8217;s go through four different options to save it to a file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># option 1 - save to file using json method\nwith open('btc_bars.json', 'w') as e:\n    json.dump(bars, e)<\/code><\/pre>\n\n\n\n<p>The first involves using the JSON library. This will maintain the structure of the data which is a list of lists. If you want to keep this structure, this is the way to go. Make sure to <code>import json<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># option 2 - save as CSV file using the csv writer library\nwith open('btc_bars.csv', 'w', newline='') as f:\n\twr = csv.writer(f)\n    for line in bars:\n        wr.writerow(line)<\/code><\/pre>\n\n\n\n<p>The second method uses csv writer to save the list as a CSV file. Make sure to <code>import csv<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># option 3 - save as CSV file without using a library. \nwith open('btc_bars2.csv', 'w') as d:\n    for line in bars:\n        d.write(f'{line&#91;0]}, {line&#91;1]}, {line&#91;2]}, {line&#91;3]}, {line&#91;4]}\\n')<\/code><\/pre>\n\n\n\n<p>The third option doesn&#8217;t use any library. We&#8217;ve created an f string which is a native function of Python 3 and above.<\/p>\n\n\n\n<p>There is a bit more flexibility here. We&#8217;ve taken advantage of it and only saved the first five columns: <strong>date<\/strong>, <strong>open<\/strong>, <strong>high<\/strong>, <strong>low<\/strong>, <strong>close<\/strong>.<\/p>\n\n\n\n<p>Alternatively, you can also delete the additional columns, if you don&#8217;t need them, like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># delete unwanted data - just keep date, open, high, low, close\nfor line in bars:\n    del line&#91;5:]<\/code><\/pre>\n\n\n\n<p>The last option is to utilize the export to CSV function of Pandas. It makes sense to use this option if you plan on holding your data in a DataFrame anyway.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># option 4 - create a Pandas DataFrame and export to CSV\nbtc_df = pd.DataFrame(bars, columns=&#91;'date', 'open', 'high', 'low', 'close'])\nbtc_df.set_index('date', inplace=True)\nprint(btc_df.head())<\/code><\/pre>\n\n\n\n<p>We&#8217;ve passed through our data into a DataFrame and defined the columns. Since we&#8217;ve deleted some unwanted columns, there are only five that need to be defined.<\/p>\n\n\n\n<p>This is what our DataFrame looks like at this point &#8211; <\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"370\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_historical_dataframe-1024x370.jpg\" alt=\"\" class=\"wp-image-3674\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_historical_dataframe-1024x370.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_historical_dataframe-300x109.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_historical_dataframe-768x278.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_historical_dataframe.jpg 1277w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>The date column has been set as an index which makes it a time-series indexed DataFrame. This way, it&#8217;s easier to manipulate based on time frames later. It also removes an extra not needed index column when we go to save it as a CSV.<\/p>\n\n\n\n<p>Lastly, we can export the DataFrame as a CSV file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># export DataFrame to csv\nbtc_df.to_csv('btc_bars3.csv')<\/code><\/pre>\n\n\n\n<p><strong>UPDATE August 30, 2021: <\/strong> Binance has launched a new website that hosts historical market data for both the spot and futures markets.<\/p>\n\n\n\n<p>The website can be accessed by clicking on the following URL &#8211; <a href=\"https:\/\/data.binance.vision\/\">Binance Data Collection<\/a><\/p>\n\n\n\n<p>From there, choose the relevant market (spot or futures). And then, you can choose the time frame for the data. I.E. monthly or daily. <\/p>\n\n\n\n<p>At this point, you can pick the type of data you&#8217;re after. The common data types are:<\/p>\n\n\n\n<ul><li><strong>aggTrades <\/strong>&#8211; Tick data aggregated into 10 second blocks<\/li><li><strong>klines <\/strong>&#8211; Also known as candles or bars. This data has the OHLC format (Open, High, Low, Close)<\/li><li> <strong>Trades <\/strong>&#8211; A record of all the trades that took place. Also known as tick data<\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"576\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/08\/data_collection-1024x576.jpg\" alt=\"\" class=\"wp-image-11015\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/08\/data_collection-1024x576.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/08\/data_collection-300x169.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/08\/data_collection-768x432.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/08\/data_collection-1536x864.jpg 1536w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/08\/data_collection-2048x1152.jpg 2048w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption>Market Data downloadable from Binance<\/figcaption><\/figure>\n\n\n\n<p>The data is in ZIP format. Once unzipped, it will be in CSV format.<\/p>\n\n\n\n<p>The website is a good way to download market data in bulk. Binance created it to try and discourage API usage for downloading large amounts of data. This is so that API can be prioritized for other usage such as sending orders.<\/p>\n\n\n\n<p>If you do use the API to download historical data in bulk, you may notice that it takes a long time. This is because Binance throttles these types of API requests.<\/p>\n\n\n\n<p>Further, the python-binance library implements delays in certain market data requests (like tick data) to ensure you don&#8217;t accidentally receive an API ban by overloading the API.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"should-i-trade-spot-or-futures\">Should I trade futures or spot? What is the difference?<\/h2>\n\n\n\n<p>In the futures market, you can enter a contract to buy a cryptocurrency at a later date. This means you don&#8217;t take actual ownership if you enter in a trade to.<\/p>\n\n\n\n<p>In fact, most futures traders never take ownership. Trading futures is mostly for speculative purposes, even though it was designed for other reasons.<\/p>\n\n\n\n<p>The major advantage of trading futures is that you can short assets that you do not own. This can be useful in arbitrage and hedging strategies.<\/p>\n\n\n\n<p>Another aspect of futures trading is that it is done on margin. This means you only need to put up a portion of the trade value, allowing you to employ leverage. <\/p>\n\n\n\n<p>Binance has a separate option to trade spot markets on margin. But there are fairly low limits to how much you can short, and the interest (borrowing costs) are much higher than trading futures.<\/p>\n\n\n\n<p>Because of various carrying costs, the futures price usually differs from the main markets, or otherwise known as the spot price. However, the prices will usually converge by the expiration date of the futures contract.<\/p>\n\n\n\n<p>With Binance, a big advantage of trading futures is that the trading fees are quite a bit lower compared to spot. So there are quite a few reasons to trade the futures markets.<\/p>\n\n\n\n<p>Here are a few reasons you may not want to trade futures:<\/p>\n\n\n\n<ul><li>You plan to trade many different crypto&#8217;s, possibly against each other &#8211; the current futures offering from Binance is currently limited to popular USDT pairs.<\/li><li>You want to own crypto and maybe store it in an offline wallet.<\/li><\/ul>\n\n\n\n<p>The Binance API uses a different endpoint for futures trading. But if you&#8217;re using the python-binance library, these endpoints are already configured in the library.<\/p>\n\n\n\n<p>Further, the futures functions within the library have been appropriately labeled to distinguish them from the spot markets.<\/p>\n\n\n\n<p>As an example, if you&#8217;re trading spot, you would use the following function to access your open orders:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>client.get_open_orders<\/code><\/pre>\n\n\n\n<p>If you&#8217;re trading futures, you would use:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>client.futures_get_open_orders<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"technical-indicators-binance-api\">How to access technical indicators such as the 20 SMA?<\/h2>\n\n\n\n<p>There are several libraries available that ease the process of calculating technical indicators.<\/p>\n\n\n\n<p>We&#8217;ve already discussed how you can export a DataFrame as a CSV file. There&#8217;s a lot more you can do with Pandas and calculating a moving average is one of them.<\/p>\n\n\n\n<p>Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import btalib\nimport pandas as pd\n\n# load DataFrame\nbtc_df = pd.read_csv('btc_bars3.csv', index_col=0)\nbtc_df.set_index('date', inplace=True)\nbtc_df.index = pd.to_datetime(btc_df.index, unit='ms')\n\n# calculate 20 moving average using Pandas\nbtc_df&#91;'20sma'] = btc_df.close.rolling(20).mean()\nprint(btc_df.tail(5))<\/code><\/pre>\n\n\n\n<p>In the above code, we loaded our data from the CSV file we created earlier. Then we use the mean() function to calculate the average on the close column.&nbsp;<\/p>\n\n\n\n<p>The rolling function allows us to set a period for the moving average. This all gets appended to the existing DataFrame. This is what the result looks like.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"778\" height=\"313\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/20sma_dataframe.jpg\" alt=\"\" class=\"wp-image-3673\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/20sma_dataframe.jpg 778w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/20sma_dataframe-300x121.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/20sma_dataframe-768x309.jpg 768w\" sizes=\"(max-width: 778px) 100vw, 778px\" \/><\/figure>\n\n\n\n<p>As you can see, a new column has been created with the 20 moving average.<\/p>\n\n\n\n<p>Let&#8217;s say you only need to know where the moving average is as of right now. Or as of the last price point in the DataFrame.<\/p>\n\n\n\n<p>We can use the same mean() function and just run it on the last 20 rows of the DataFrame like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># calculate just the last value for the 20 moving average\nmean = btc_df.close.tail(20).mean()<\/code><\/pre>\n\n\n\n<p>There is a lot more Pandas can do. We can easily grab the highest price Bitcoin traded this year as follows &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># get the highest closing price in 2020\nmax_val = btc_df.close&#91;'2020'].max()<\/code><\/pre>\n\n\n\n<p>But Pandas isn&#8217;t able to calculate other technical indicators such as RSI, or MACD. The Binance API does not provide this info either.<\/p>\n\n\n\n<p>TA-LIB has been a popular library for some time. We recently got a chance to test out a new library &#8211; bta-lib.<\/p>\n\n\n\n<p>This library was created by the author of Backtrader. He discusses on his blog that TA-LIB has several indicators that were improperly implemented.<\/p>\n\n\n\n<p>Further, TA-LIB wasn&#8217;t designed for Python. There is a wrapper available but there is much less overhead going with a solution designed for Python.<\/p>\n\n\n\n<p>Bta-lib can be installed using PIP as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>pip install bta-lib<\/code><\/pre>\n\n\n\n<p>Let&#8217;s try calculating the same moving average with the library as a comparison &#8211;&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sma = btalib.sma(btc_df.close)\nprint(sma.df)<\/code><\/pre>\n\n\n\n<p>We now have a separate DataFrame that contains the values for the moving average. It looks like this:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"774\" height=\"309\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btalib_20sma.jpg\" alt=\"\" class=\"wp-image-3675\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btalib_20sma.jpg 774w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btalib_20sma-300x120.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btalib_20sma-768x307.jpg 768w\" sizes=\"(max-width: 774px) 100vw, 774px\" \/><\/figure>\n\n\n\n<p>Note that bta-lib will return an object to our sma variable. To access the DataFrame that is contained within it, simply type <code>.df<\/code> after the variable name.<\/p>\n\n\n\n<p>By default, the library uses the 30 period moving average.<\/p>\n\n\n\n<p>We can duplicate the same function we had before and calculate the 20 moving average and attach it as a column to our original DataFrame like this.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># create sma and attach as column to original df\nbtc_df&#91;'sma'] = btalib.sma(btc_df.close, period=20).df\nprint(btc_df.tail())<\/code><\/pre>\n\n\n\n<p>Let&#8217;s create a few more indicators. Here is how we can calculate the RSI using the bta-lib library &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rsi = btalib.rsi(btc_df, period=14)<\/code><\/pre>\n\n\n\n<p>Once again, an object containing a df has been returned. We can access the very last value like this.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(rsi.df.rsi&#91;-1])<\/code><\/pre>\n\n\n\n<p>In a live environment, you might only need the very last value.<\/p>\n\n\n\n<p>Here is how we can calculate the MACD for Bitcoin in bta-lib.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>macd = btalib.macd(btc_df, pfast=20, pslow=50, psignal=13)<\/code><\/pre>\n\n\n\n<p>Finally, we will join our RSI and MACD values to our original Bitcoin price DataFrame<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># join the rsi and macd calculations as columns in original df\nbtc_df = btc_df.join(&#91;rsi.df, macd.df])\nprint(btc_df.tail())<\/code><\/pre>\n\n\n\n<p>And now we have all our calculations easily accessible from one DataFrame &#8211;&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"253\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_df_all_indicators-1024x253.jpg\" alt=\"\" class=\"wp-image-3676\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_df_all_indicators-1024x253.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_df_all_indicators-300x74.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_df_all_indicators-768x190.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/btc_df_all_indicators.jpg 1241w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"fire-an-ethereum-order-binance-api\">How to fire an order for Ethereum using the Binance API?<\/h2>\n\n\n\n<p>The library we are using has a function that allows us to create test orders. Here is an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>buy_order_limit = client.create_test_order(\n    symbol='ETHUSDT',\n    side='BUY',\n    type='LIMIT',\n    timeInForce='GTC',\n    quantity=100,\n    price=200)<\/code><\/pre>\n\n\n\n<p>We can make sure our syntax is correct without having to submit a live order. This is very useful when you are getting to know the API.<\/p>\n\n\n\n<p>If we change the type in the above code to &#8216;MARKET&#8217; for example, it will throw an exception. The reason being is that a <strong>timeInForce <\/strong>and <strong>price <\/strong>parameters are not used for market orders. Instead, a market order would look like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>buy_order = client.create_test_order(symbol='ETHUSDT', side='BUY', type='MARKET', quantity=100)<\/code><\/pre>\n\n\n\n<p>Once your satisfied the syntax is correct, simply swap out the <code>create_test_order function<\/code> for the <code>create_order function<\/code>.<\/p>\n\n\n\n<p>Note: If you&#8217;re following along with the example, you may get an API error when using the above limit order code for ETHUSDT if the price has moved significantly since this was written. Binance will only allow orders that are within a certain percentage distance of the price the coin is currently trading at.<\/p>\n\n\n\n<p>Since there could be an exception, we will wrap our code in a try\/except block and also import some of the defined exceptions from the library.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\n\nfrom binance.client import Client\nfrom binance.enums import *\nfrom binance.exceptions import BinanceAPIException, BinanceOrderException\n\n# init\napi_key = os.environ.get('binance_api')\napi_secret = os.environ.get('binance_secret')\n\nclient = Client(api_key, api_secret)<\/code><\/pre>\n\n\n\n<p>In addition to the client and the custom exceptions, we have imported binance.enums, which we will discuss shortly.<\/p>\n\n\n\n<p>Here is the order code block.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># create a real order if the test orders did not raise an exception\n\ntry:\n    buy_limit = client.create_order(\n        symbol='ETHUSDT',\n        side='BUY',\n        type='LIMIT',\n        timeInForce='GTC',\n        quantity=100,\n        price=200)\n\nexcept BinanceAPIException as e:\n    # error handling goes here\n    print(e)\nexcept BinanceOrderException as e:\n    # error handling goes here\n    print(e)<\/code><\/pre>\n\n\n\n<p>An order confirmation will be sent back from the exchange and stored in our buy_limit variable. This is what it looks like:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"626\" height=\"430\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/buy_eth.jpg\" alt=\"\" class=\"wp-image-3677\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/buy_eth.jpg 626w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/buy_eth-300x206.jpg 300w\" sizes=\"(max-width: 626px) 100vw, 626px\" \/><\/figure>\n\n\n\n<p>It is in a dictionary format. Note that it contains an orderId. We can use this id to cancel the limit order like this &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    # cancel previous orders\n    cancel = client.cancel_order(symbol='ETHUSDT', orderId=buy_limit&#91;'orderId'])<\/code><\/pre>\n\n\n\n<p>Once again, we receive confirmation. We can print out the cancel variable to view it.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"677\" height=\"402\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/cancel_eth_buy.jpg\" alt=\"\" class=\"wp-image-3678\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/cancel_eth_buy.jpg 677w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/cancel_eth_buy-300x178.jpg 300w\" sizes=\"(max-width: 677px) 100vw, 677px\" \/><\/figure>\n\n\n\n<p>The <code>create_order<\/code> function is the main method to place an order. We can pass through several parameters here.&nbsp;<\/p>\n\n\n\n<p>But there are certain orders which are common, and helper functions have been created for them. They shorten the code required to place an order, making things a bit easier. Here are a few examples:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    # same order but with helper function\n    buy_limit = client.order_limit_buy(symbol='ETHUSDT', quantity=100, price=200)\n\n    # market order using a helper function\n    market_order = client.order_market_sell(symbol='ETHUSDT', quantity=100)<\/code><\/pre>\n\n\n\n<p>Here are some of the helper functions you might want to use:<\/p>\n\n\n\n<ul><li><code>order_limit_buy()<\/code><\/li><li><code>order_limit_sell()<\/code><\/li><li><code>order_market_buy()<\/code><\/li><li><code>order_market_sell()<\/code><\/li><li><code>order_oco_buy()<\/code><\/li><li><code>order_ocosell()<\/code><\/li><\/ul>\n\n\n\n<p>The last two are considered advanced order types. <strong>OCO <\/strong>stands for <strong>O<\/strong>ne <strong>C<\/strong>ancels the <strong>O<\/strong>ther.&nbsp;<\/p>\n\n\n\n<p>A good example of this is when you&#8217;re using a stop loss and a take profit target. If one of these order got hit, you would want the other to get canceled.<\/p>\n\n\n\n<p>Some of the order types require string constants such as &#8216;<strong>MARKET<\/strong>&#8216; or &#8216;<strong>BUY<\/strong>&#8216;. Another broker might use &#8216;<strong>MKT<\/strong>&#8216; instead and so there isn&#8217;t always a logical answer as to what you should use.&nbsp;<\/p>\n\n\n\n<p>You can look these up in the documentation if needed. Alternatively, the library has hard coded strings into variables that you can use.<\/p>\n\n\n\n<p>This is especially useful if your coding editor has autocomplete as you can quickly figure which parameters to use without having to pull up the documentation.<\/p>\n\n\n\n<p>Here is an example of an order without using the built-in variables:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>buy_order = client.create_test_order(symbol='ETHUSDT', side='BUY', type='MARKET', quantity=100)<\/code><\/pre>\n\n\n\n<p>And here is the same thing using the built-in variables.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>buy_order = client.create_test_order(symbol='ETHUSDT', side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=100)<\/code><\/pre>\n\n\n\n<p>If you plan to go this route, you will need the enums import discussed earlier.<\/p>\n\n\n\n<p>A full list of all the hard coded strings can be found <a href=\"https:\/\/python-binance.readthedocs.io\/en\/latest\/constants.html#\" target=\"_blank\" rel=\"noreferrer noopener\">here <\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"implement-stop-loss-binance-api\">How to implement a stop loss or take profit using the Binance API?<\/h2>\n\n\n\n<p>The method to place stop losses or take profits differs with cryptocurrencies compared to other markets such as stocks or Forex.<\/p>\n\n\n\n<p>The reason being, with stocks, you have a base currency. This is often in USD. Once you buy a stock, you are in a &#8216;trade&#8217;. At some point, you will want to sell that stock and return to your base USD currency.<\/p>\n\n\n\n<p>With crypto, there really isn&#8217;t a concept of a base currency. When you conduct a trade, you are swapping one currency for another. The system doesn&#8217;t view it as a &#8216;trade&#8217; that you eventually want to get out of.<\/p>\n\n\n\n<p>For this reason, Binance does not allow you to natively attach a stop loss and a take profit to your main order.<\/p>\n\n\n\n<p>But we can still implement one manually.<\/p>\n\n\n\n<p>To do this, we can place an OCO order. The idea is, that if either the stop loss or take profit gets hit, the other order should be canceled.<\/p>\n\n\n\n<p>Going back to our ETH order, here is how we can implement a stop loss and take profit.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try:\n    order = client.create_oco_order(\n        symbol='ETHUSDT',\n        side='SELL',\n        quantity=100,\n        price=250,\n        stopPrice=150,\n        stopLimitPrice=150,\n        stopLimitTimeInForce='GTC')\n\nexcept BinanceAPIException as e:\n    # error handling goes here\n    print(e)\nexcept BinanceOrderException as e:\n    # error handling goes here\n    print(e)<\/code><\/pre>\n\n\n\n<p>Note that we are passing in both a <strong>stopPrice <\/strong>and a <strong>stopLimitPrice<\/strong>. Once the <strong>stopPrice <\/strong>level gets hit, a limit order will be placed using the <strong>stopLimitPrice<\/strong>. In most cases, the prices will be the same for both of these parameters.<\/p>\n\n\n\n<p>While most assets accept stop-loss limit order, not all of them do. Before placing your order, it&#8217;s a good idea to check if it is supported.<\/p>\n\n\n\n<p>You can use the exchange info endpoint for this.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># use exchange info to confirm order types\ninfo = client.get_symbol_info('ETHUSDT')\nprint(info&#91;'orderTypes'])<\/code><\/pre>\n\n\n\n<p>Here is the response &#8211;&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"719\" height=\"1024\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/exchange_info-1-719x1024.jpg\" alt=\"\" class=\"wp-image-3682\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/exchange_info-1-719x1024.jpg 719w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/exchange_info-1-211x300.jpg 211w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/exchange_info-1-768x1094.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/exchange_info-1.jpg 869w\" sizes=\"(max-width: 719px) 100vw, 719px\" \/><\/figure>\n\n\n\n<p>Under <strong>orderTypes<\/strong>, it shows that a stop-loss limit is indeed accepted for this asset.<\/p>\n\n\n\n<p>There is other useful info here, such as whether the asset can be traded on margin or not, the minimum quantity, and the tick size.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"use-bnb-for-discount-trading-fees\">How to use Binance Coin (BNB) for discounted trading commissions?<\/h2>\n\n\n\n<p>Commissions add up quickly, but fortunately, there is a discount scheme.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1011\" height=\"1024\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/fee_schedule-1011x1024.jpg\" alt=\"\" class=\"wp-image-3679\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/fee_schedule-1011x1024.jpg 1011w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/fee_schedule-296x300.jpg 296w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/fee_schedule-768x778.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/fee_schedule.jpg 1080w\" sizes=\"(max-width: 1011px) 100vw, 1011px\" \/><\/figure>\n\n\n\n<p>The image above shows the fee schedule and discounts for trading the spot market. There are discounts for futures trading too.&nbsp;<\/p>\n\n\n\n<p>You can either qualify for a discount depending on your trading volume or the quantity of Binance coin you own.<\/p>\n\n\n\n<p>Binance coin or BNB was created by Binance in 2017. It can be used as a currency although perhaps the more common usage for it is to pay trading fees.<\/p>\n\n\n\n<p>If you&#8217;re not keen on owning BNB, it still makes sense to own just a little bit to pay your trading fees with. After all, any amount of BNB will qualify you for the first tier.<\/p>\n\n\n\n<p>Keep in mind, if you&#8217;re using BNB to pay for trading fees, your balance will reduce over time.<\/p>\n\n\n\n<p>The function below ensures there is a minimum amount of BNB in your account and tops it up if there isn&#8217;t.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def topup_bnb(min_balance: float, topup: float):\n\t''' Top up BNB balance if it drops below minimum specified balance '''\n\tbnb_balance = client.get_asset_balance(asset='BNB')\n\tbnb_balance = float(bnb_balance&#91;'free'])\n\tif bnb_balance &lt; min_balance:\n\t\tqty = round(topup - bnb_balance, 5)\n\t\tprint(qty)\n\t\torder = client.order_market_buy(symbol='BNBUSDT', quantity=qty)\n\t\treturn order\n\treturn False<\/code><\/pre>\n\n\n\n<p>Trading scripts are usually run in a loop, so periodically calling the above function will ensure there is enough BNB in the account to qualify for the minimum discount.<\/p>\n\n\n\n<p>As an example, we can call the above function like this &#8211;&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>min_balance = 1.0\ntopup = 2.5\norder = topup_bnb(min_balance, topup)<\/code><\/pre>\n\n\n\n<p>This would check for a balance of at least 1 BNB. If the amount of BNB has dropped below that, it will top it off to bring the account up to 2.5 BNB.<\/p>\n\n\n\n<p>To use BNB to pay for trading fees and receive a discount, it needs to be enabled. From the main Binance page, click on the profile icon on the top right once logged in.&nbsp;<\/p>\n\n\n\n<p>The first option should be your email address, click on that to get to your dashboard. From there, there will be a section that looks like this &#8211;&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"810\" height=\"228\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/BNB_fees.jpg\" alt=\"\" class=\"wp-image-3680\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/BNB_fees.jpg 810w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/BNB_fees-300x84.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/BNB_fees-768x216.jpg 768w\" sizes=\"(max-width: 810px) 100vw, 810px\" \/><\/figure>\n\n\n\n<p>This is where you can enable and disable the option to pay for trading fees with BNB.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"execute-eth-trade-on-bitcoin-price\">How to execute a trade on ETH when BTC hits a certain price?<\/h2>\n\n\n\n<p>In the next example, we will place a buy order in Ethereum when Bitcoin crosses above the $10,000 price point.<\/p>\n\n\n\n<p>We will use the Binance WebSocket to track the price of Bitcoin.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\nfrom time import sleep\n\nfrom binance.client import Client\nfrom binance import ThreadedWebsocketManager\n\n# init\napi_key = os.environ.get('binance_api')\napi_secret = os.environ.get('binance_secret')\nclient = Client(api_key, api_secret)\nprice = {'BTCUSDT': None, 'error': False}<\/code><\/pre>\n\n\n\n<p>The code above looks very similar to the prior example where we showed how to use the WebSocket. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def btc_pairs_trade(msg):\n    ''' define how to process incoming WebSocket messages '''\n    if msg&#91;'e'] != 'error':\n        price&#91;'BTCUSDT'] = float(msg&#91;'c'])\n    else:\n        price&#91;'error'] = True<\/code><\/pre>\n\n\n\n<p>Next, we have our callback function. This is where all the WebSocket data will flow through. We could have programmed our trading logic here as well.<\/p>\n\n\n\n<p>However, since we need to use a try\/except block for our order entry, it&#8217;s best not to as this could interfere with error checking that takes place on the back end, in the library.<\/p>\n\n\n\n<p>We will start the WebSocket and direct it to the <code>btc_pairs_trade<\/code> function we just created.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bsm = ThreadedWebsocketManager()\nbsm.start()\nbsm.start_symbol_ticker_socket(symbol='BTCUSDT', callback=btc_pairs_trade)<\/code><\/pre>\n\n\n\n<p>Before getting started, a quick check to make sure we have data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>while not price&#91;'BTCUSDT']:\n    # wait for WebSocket to start streaming data\n    sleep(0.1)<\/code><\/pre>\n\n\n\n<p>The above infinite loop will break as soon as soon as the WebSocket populates our price dictionary with a new value.<\/p>\n\n\n\n<p>On to the main trade logic.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>while True:\n    # error check to make sure WebSocket is working\n    if price&#91;'error']:\n        # stop and restart socket\n\tbsm.stop()\n\tsleep(2)\n\tbsm.start()\n        price&#91;'error'] = False\n\n    else:\n        if price&#91;'BTCUSDT'] &gt; 10000:\n            try:\n                order = client.order_market_buy(symbol='ETHUSDT', quantity=100)\n                break\n            except Exception as e:\n                print(e)\n\n    sleep(0.1)<\/code><\/pre>\n\n\n\n<p>Here we are checking to see if the price is above our parameter, $10,000 in this case. If so, we send a market order to buy ETHUSDT.<\/p>\n\n\n\n<p>After a buy order is sent, we break out of the loop and our script completes.&nbsp;<\/p>\n\n\n\n<p>Don&#8217;t forget to terminate the WebSocket properly<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bsm.stop()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"execute-eth-trade-on-btc-price-movement\">How to execute an ETH trade when BTC moves 5% in the last 5 minutes?<\/h2>\n\n\n\n<p>We will once again make a trading decision for Ethereum based on Bitcoin. Although in this example, we are looking for a price move larger than 5% over the past five minutes.<\/p>\n\n\n\n<p>So if Bitcoin rallies more than 5% we buy Ethereum. If it declines by more than 5%, we will sell Ethereum.<\/p>\n\n\n\n<p>Since we could be taking a short position here, we will be trading futures. In the spot market, you can only sell if you already own that cryptocurrency.<\/p>\n\n\n\n<p>Our imports and most of the initial part of our script have not changed. The main difference here is that we are using Pandas as we will store incoming data from the WebSocket into a DataFrame.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\nfrom time import sleep\n\nimport pandas as pd\nfrom binance import ThreadedWebsocketManager\nfrom binance.client import Client\n\n# init\napi_key = os.environ.get('binance_api')\napi_secret = os.environ.get('binance_secret')\nclient = Client(api_key, api_secret)\nprice = {'BTCUSDT': pd.DataFrame(columns=&#91;'date', 'price']), 'error': False}<\/code><\/pre>\n\n\n\n<p>Therefore, we have imported Pandas and created a blank DataFrame in our price dictionary. The DataFrame has two columns, one for the date, or rather time. And the other column will hold the price.<\/p>\n\n\n\n<p>The callback function contains the code to populate the DataFrame from WebSocket data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def btc_pairs_trade(msg):\n\t''' define how to process incoming WebSocket messages '''\n    if msg&#91;'e'] != 'error':\n        price&#91;'BTCUSDT'].loc&#91;len(price&#91;'BTCUSDT'])] = &#91;pd.Timestamp.now(), float(msg&#91;'c'])]\n    else:\n        price&#91;'error'] = True<\/code><\/pre>\n\n\n\n<p>We are using the <code>.loc<\/code> function to append data into the DataFrame via the last index value. We use the length of the DataFrame to determine the index value.<\/p>\n\n\n\n<p>At that point, we are just inserting the current time, obtained by using the Timestamp function from Pandas, and the price from the socket stream.<\/p>\n\n\n\n<p>Now that we have our callback function created, we will start the WebSocket.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># init and start the WebSocket\nbsm = ThreadedWebsocketManager()\nbsm.start()\nbsm.start_symbol_ticker_socket(symbol='BTCUSDT', callback=btc_pairs_trade)<\/code><\/pre>\n\n\n\n<p>Once again, we will do a quick check to make sure data is streaming.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>## main\nwhile len(price&#91;'BTCUSDT']) == 0:\n\t# wait for WebSocket to start streaming data\n\tsleep(0.1)\n\t\nsleep(300)<\/code><\/pre>\n\n\n\n<p>Before starting the main trade logic, we will put the script to sleep for five minutes since we need at least that much data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>while True:\n\t# error check to make sure WebSocket is working\n    if price&#91;'error']:\n        # stop and restart socket\n        bsm.stop()\n\tsleep(2)\n        bsm.start()\n        price&#91;'error'] = False\n    else:\n\t\tdf = price&#91;'BTCUSDT']\n\t\tstart_time = df.date.iloc&#91;-1] - pd.Timedelta(minutes=5)\n\t\tdf = df.loc&#91;df.date &gt;= start_time]\n\t\tmax_price = df.price.max()\n\t\tmin_price = df.price.min()<\/code><\/pre>\n\n\n\n<p>In our main loop, we first grab our DataFrame from the dictionary file and assign it to the variable <strong>df<\/strong>. This step is not necessary but makes the code easier to read for our example.<\/p>\n\n\n\n<p>Next, we determine the time five minutes ago. We can do that by taking the last date value from our DataFrame and subtracting 5 minutes using the Timedelta function built into Pandas. We will assign this value to the variable start_time.<\/p>\n\n\n\n<p>With the <strong>start_time <\/strong>value, we can filter our DataFrame down to contain only the last five minutes of data.<\/p>\n\n\n\n<p>From there, we can use max() and min() functions from Pandas to find the highest and lowest price.&nbsp;<\/p>\n\n\n\n<p>Now all we need to do is determine if there was a larger than 5% movement between the last price and either the maximum or minimum value.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\t\tif df.price.iloc&#91;-1] &lt; max_price * 0.95:\n\t\t\ttry:\n\t\t\t\torder = client.futures_create_order(symbol='ETHUSDT', side='SELL', type='MARKET', quantity=100)\n\t\t\t\tbreak\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\n\t\telif df.price.iloc&#91;-1] &gt; min_price * 1.05:\n\t\t\ttry:\n\t\t\t\torder = client.futures_create_order(symbol='ETHUSDT', side='BUY', type='MARKET', quantity=100)\n\t\t\t\tbreak\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\n\tsleep(0.1)<\/code><\/pre>\n\n\n\n<p>If the latest price is 5% larger than the last value, we know Bitcoin is going up, and we will short Ethereum as part of our mean reversion strategy.&nbsp;<\/p>\n\n\n\n<p>If the last price is 5% lower than the max price in our DataFrame, then we do the opposite.<\/p>\n\n\n\n<p>Note that the library does not have helper functions for orders in the futures market so we are using a method similar to the create_order function used for the spot markets.<\/p>\n\n\n\n<p>Once again, if our order gets filled, we will break out of our main loop and properly terminate the WebSocket.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># properly stop and terminate WebSocket\nbsm.stop()<\/code><\/pre>\n\n\n\n<p>This strategy, however, might be one that could be run indefinitely. If you don&#8217;t plan to break out after placing an order, it is a good idea to put the script to sleep for a period of time.<\/p>\n\n\n\n<p>Otherwise, new orders will be sent on every tick until the 5% divergence gap closes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"final-thoughts\">Final Thoughts<\/h2>\n\n\n\n<p>Our overall view of Binance is that it is a great exchange. It&#8217;s hard to beat their commissions, they have a good reputation, and having access to a WebSocket to stream data makes life a lot easier.<\/p>\n\n\n\n<p>If you plan on using the Binance API, we highly recommend joining their Telegram groups. They have one&nbsp;<a target=\"_blank\" href=\"https:\/\/t.me\/binance_api_announcements\" rel=\"noreferrer noopener\">group for API announcements<\/a>&nbsp;which will keep you up to date on any planned or unplanned outages.<\/p>\n\n\n\n<p>They also have another group for&nbsp;<a target=\"_blank\" href=\"https:\/\/t.me\/binance_api_english\" rel=\"noreferrer noopener\">general API discussions<\/a>. This group is moderated and the admins are usually good at answering any API specific questions.<\/p>\n\n\n\n<p>We recommend that you further investigate error handling. Some people are fine with logging errors to a log file. However, if your trading strategy requires precision and could get negatively impacted on a failed API call, other measures can be taken.<\/p>\n\n\n\n<p>Check out our article on the <a href=\"https:\/\/algotrading101.com\/learn\/interactive-brokers-python-api-native-guide\/\" target=\"_blank\" rel=\"noreferrer noopener\">Interactive Brokers API<\/a> where we discussed using the Telegram API as an alert system. This might be a good method to alert you if there is an error calling the API.<\/p>\n\n\n\n<p>Lastly, if speed is a major factor in your trading script, and you plan on running it on a virtual server, consider using a server based in Asia. <\/p>\n\n\n\n<p>Binance uses AWS servers out of Tokyo so either using the same server or one nearby will yield faster speeds. We were able to cut our API request times down by nearly 200ms by running our scripts from AWS Tokyo compared to US based servers.<\/p>\n\n\n\n<p>If you&#8217;ve never used AWS before, they offer a free server for one year for new customers. The promotion is for a server on the &#8216;micro&#8217; tier which is more than sufficient to run a basic Python script.<\/p>\n\n\n\n<p>All the code examples used here are available for <a href=\"https:\/\/github.com\/PythonForForex\/binance-api-step-by-step-guide\" target=\"_blank\" rel=\"noreferrer noopener\">download on GitHub<\/a>. Please feel free to download them to get a first-hand experience with the API. Just be careful with some of the order scripts so as not to accidentally send a market order to a live account!<\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"pvc_clear\"><\/div>\n<p id=\"pvc_stats_3744\" class=\"pvc_stats total_only  \" data-element-id=\"3744\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p>\n<div class=\"pvc_clear\"><\/div>\n<p>Table of Contents What is the Binance API? Why should I use the Binance API? Why shouldn\u2019t I use the Binance API? What are the alternatives to using the Binance API? Are there any Python libraries available for the Binance API? How do I get started with the Binance API? Does Binance offer a demo [&hellip;]<\/p>\n","protected":false},"author":4,"featured_media":3661,"comment_status":"closed","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"_lmt_disableupdate":"no","_lmt_disable":"no","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[3,2],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Binance Python API \u2013 A Step-by-Step Guide - AlgoTrading101 Blog<\/title>\n<meta name=\"description\" content=\"The Binance API allows you to connect to the Binance servers via Python or several other programming languages. With it, you can automate your trading.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Binance Python API \u2013 A Step-by-Step Guide - AlgoTrading101 Blog\" \/>\n<meta property=\"og:description\" content=\"The Binance API allows you to connect to the Binance servers via Python or several other programming languages. With it, you can automate your trading.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/\" \/>\n<meta property=\"og:site_name\" content=\"Quantitative Trading Ideas and Guides - AlgoTrading101 Blog\" \/>\n<meta property=\"article:published_time\" content=\"2020-06-30T10:14:32+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-04-04T20:29:56+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1297\" \/>\n\t<meta property=\"og:image:height\" content=\"848\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Jignesh Davda\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Jignesh Davda\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"41 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Binance Python API \u2013 A Step-by-Step Guide - AlgoTrading101 Blog","description":"The Binance API allows you to connect to the Binance servers via Python or several other programming languages. With it, you can automate your trading.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/","og_locale":"en_US","og_type":"article","og_title":"Binance Python API \u2013 A Step-by-Step Guide - AlgoTrading101 Blog","og_description":"The Binance API allows you to connect to the Binance servers via Python or several other programming languages. With it, you can automate your trading.","og_url":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/","og_site_name":"Quantitative Trading Ideas and Guides - AlgoTrading101 Blog","article_published_time":"2020-06-30T10:14:32+00:00","article_modified_time":"2023-04-04T20:29:56+00:00","og_image":[{"width":1297,"height":848,"url":"http:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/06\/create_api.jpg","type":"image\/jpeg"}],"author":"Jignesh Davda","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Jignesh Davda","Est. reading time":"41 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/#article","isPartOf":{"@id":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/"},"author":{"name":"Jignesh Davda","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/person\/f8764d9c5a5b73e3d5e235f601774b79"},"headline":"Binance Python API \u2013 A Step-by-Step Guide","datePublished":"2020-06-30T10:14:32+00:00","dateModified":"2023-04-04T20:29:56+00:00","mainEntityOfPage":{"@id":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/"},"wordCount":7082,"publisher":{"@id":"https:\/\/algotrading101.com\/learn\/#organization"},"articleSection":["Programming","Trading"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/","url":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/","name":"Binance Python API \u2013 A Step-by-Step Guide - AlgoTrading101 Blog","isPartOf":{"@id":"https:\/\/algotrading101.com\/learn\/#website"},"datePublished":"2020-06-30T10:14:32+00:00","dateModified":"2023-04-04T20:29:56+00:00","description":"The Binance API allows you to connect to the Binance servers via Python or several other programming languages. With it, you can automate your trading.","breadcrumb":{"@id":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/algotrading101.com\/learn\/"},{"@type":"ListItem","position":2,"name":"Binance Python API \u2013 A Step-by-Step Guide"}]},{"@type":"WebSite","@id":"https:\/\/algotrading101.com\/learn\/#website","url":"https:\/\/algotrading101.com\/learn\/","name":"Quantitative Trading Ideas and Guides - AlgoTrading101 Blog","description":"Authentic Stories about Algorithmic trading, coding and life.","publisher":{"@id":"https:\/\/algotrading101.com\/learn\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/algotrading101.com\/learn\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/algotrading101.com\/learn\/#organization","name":"AlgoTrading101","url":"https:\/\/algotrading101.com\/learn\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/logo\/image\/","url":"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/11\/AlgoTrading101-Lucas-Liew.jpg","contentUrl":"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/11\/AlgoTrading101-Lucas-Liew.jpg","width":1200,"height":627,"caption":"AlgoTrading101"},"image":{"@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/person\/f8764d9c5a5b73e3d5e235f601774b79","name":"Jignesh Davda","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/44f66584169f5f2d9c0b7ffead97a9c9?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/44f66584169f5f2d9c0b7ffead97a9c9?s=96&d=mm&r=g","caption":"Jignesh Davda"},"sameAs":["https:\/\/www.thegoldanalyst.com","https:\/\/www.linkedin.com\/in\/jignesh-davda-880bb02\/"],"url":"https:\/\/algotrading101.com\/learn\/author\/jdavda\/"}]}},"modified_by":"Igor Radovanovic","_links":{"self":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts\/3744"}],"collection":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/comments?post=3744"}],"version-history":[{"count":13,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts\/3744\/revisions"}],"predecessor-version":[{"id":21193,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts\/3744\/revisions\/21193"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/media\/3661"}],"wp:attachment":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/media?parent=3744"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/categories?post=3744"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/tags?post=3744"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}