Master Binance API with Python (2023)
Are you tired of struggling to use the Binance API in Python? Do you feel like you’re missing something when using the python-binance library? If so, you’re not alone!
In this tutorial, we’ll take the frustration out of using the Binance API and show you step-by-step how to use the REST APIs, WebSockets, and even place orders. Plus, we’ll provide concrete examples to make it all easy to understand.
This is a long one, so don’t hesitate to use the table of contents to skip directly to what you’re interested in.
Say goodbye to the confusing documentation and hello to confident Binance API usage with us guiding you through it all. You can even follow along with the Binance API Python Tutorial Jupyter Notebook.
What Is Binance?
Binance is an online exchange for cryptocurrency trading. It also provides electronic wallets for storing cryptocurrencies. Binance is the world’s largest cryptocurrency exchange in terms of daily trading volume.
Changpeng Zhao founded Binance in 2017, and it is registered in the Cayman Islands.
Binance.us is a sister company to Binance, built as a separate exchange in 2019 due to a regulatory ban on Binance in the USA. This independent structure of two exchanges allows Binance to access the US market.
What Is the Binance API?
Binance API is a set of REST API calls that let users access Binance endpoints in Python or other programming languages. With the Binance API, you can develop customized trading bots and cryptocurrency applications and thus automate your crypto trading.
Binance Pros and Cons
- Binance provides a wide choice of cryptocurrencies.
- Binance commission rates are low due to high liquidity and trading volumes.
- A proprietary cold wallet ensures the security of your cryptocurrencies.
- Free API lets users automate their trading tasks.
- Binance has a very complex registration procedure that requires identity verification.
- None of the regulators licenses Binance
- The mechanism for calculating the commission is not transparent.
- Users complain about technical issues with Binance servers.
Binance API Pricing Plans
The official Binance API is free to use. Access to various endpoints depends upon your Binance account type. For instance, you can only access margin trading account endpoints if you have a margin trading account.
Binance API allows 1200 request weights per minute, 50 orders per 10 seconds, and 160,000 orders per 24 hours. See the official documentation for API request limits.
How to Get Started with Binance API in Python?
- By creating a live Binance trading account.
- By creating a Binance Spot Test Network account.
Creating A Live Binance Trading Account
The first step is to sign up for a Binance trading account. If you live in the US, you must sign up with Binance.us. 
After registration, you receive a verification email. Click on the verification link to verify your account.
Log in to your Binance API account again and verify your identity. You must provide a valid identity document, e.g., an identity card, passport, or a driving license to verify your identity. In addition, you also have to take a photograph via your computer’s webcam or a mobile camera.
You will need an API key and API secret to access Binance API. To get the API key and secret Key, click on your profile icon from the top-right corner of the Binance dashboard. Click “API Management” from the dropdown list.

Click the “Create API” button.

Enter the label for your API Key, and click the “Next” button.
You must enable two-factor authentication with the Google Authenticator or similar 2FA app, or your phone number.
Once you enable two-factor authentication, you will see your API key, API Secret, and base URL for the REST API. Store these keys in a safe place. Once you refresh the page, you will never be able to see these keys again. You can create multiple API Keys if you want.
The process for generating an API key for Binance US is similar. Log in to your Binance US account. Click your profile icon, select “API Management” from the dropdown list, and follow the same process as you did while generating an API key for Binance.com.

You will only be able to generate an API key if you have a minimum of $15 in your spot wallet. You will see the following message if you need more funds in your spot wallet.
Create a Demo Binance Trading Account
If you want to try the Binance API endpoints before live trading, you can create a Binance Spot Test Network account.

Currently, the only way to access the Binance Spot Test Network is via your GitHub account integration with Spot Test Network. Click the “Log In with GitHub” link in the following screenshot.
Click the “Authorize binance-exchange” button on the following page.

Finally, click the “Generate HMAC_SHA256 Key” link to generate your Spot Test Network API keys.
Simple Example Fetching Data Using Binance API in Python
You can use a third-party Python library or the Python requests module to fetch data from the Binance API.
Binance API Python Library Example
Several third-party libraries are available for the Binance API; the most widely used is python-binance. Binance held a contest in 2017 for the best client libraries for different languages. The python-binance library won that contest.
The following script installs the python-binance library.
The Client class from the binance.client module contains methods that call the Binance API. If you’re not familiar with how to do that, read my tutorial on how to use dotenv files.
Let’s also import Pandas and our API keys from our local environment variables.
The script below imports the Client class. You must create an object of the Client class and pass it your API key and secret.
If you are using the Binance Spot Test Network for testing Binance API calls, you must pass True as the value for the testnet attribute of the Client class. In addition, you need to assign the API URL of the Spot Test Network to the API_URL attribute of the Client class.
US users accessing the Binance.us endpoints must pass us as the value for the tld parameter of the Client class, as shown below:
Once you initialize the Client class object, you can use a class method to call any Binance API endpoint. For instance, in the script below, the `get_all_tickers()` method returns Binance ticker prices.

Convert the Binance API method response to a Pandas dataframe to improve readability:

Binance API Requests Module Example
Use the Python requests module to call Binance API endpoints if you are looking for a speedy response. In addition, third-party libraries do not immediately update with the REST API changes. You can use the Python requests module if a third-party library doesn’t have the functionality you need.
The following script uses the Python requests module to fetch ticker prices from the Python Binance API. Notice the API call to retrieve ticker prices is ‘/api/v3/ticker/price’.

See the official Binance API documentation for other REST API endpoints.
What are Binance API Endpoints?
- General Endpoints
- Market Data Endpoints
- Account Endpoints
- Sub Account Endpoints
- Margin Trading Endpoints
The following sections explain how to call some of the most common functions from these endpoints.
General Endpoint
The general endpoint functions allow users to perform some of the most frequent Binance API tasks, e.g., get server time and status, ticker prices, exchange and symbol information, etc.
Get Binance Server Time and Status
The ping() method from the Client class tells if the Binance server is up and running.
An empty response or no error means the server is running.
To get the Binance API server time, you can use the get_server_time() method.
The Binance API returns a timestamp in UNIX format, as shown in the output below.
The following Python script converts the UNIX time format into ISO standard date time format.
Get All Binance Coins Info
If you are interested in finding out the current trading price of a Binance cryptocurrency symbol, use the get_all_tickers() method:

Get Binance Exchange and Symbol Info
You can get general information about the Binance exchange using the get_exchange_info() method. In the response, you will see the time zone info, server time, symbols, etc.
Use a dictionary key to get information about one of the entities mentioned above. For instance, the script below returns details of all the symbols on the Binance exchange:

You can get detailed information about a symbol using the get_symbol_info() method. The method returns information such as quote precision:

Market Data End Point
Get Market Depth
The market depth of a symbol refers to orders asking and bid prices at a certain point. An order book lists market depth.
With python-binance client, you can retrieve the market depth of a symbol via the get_order_book() method.

We can create a dataframe to visualize this data more easily.

Get Binance Recent Trades
The get_recent_trades() method returns information about a symbol’s recent 500 trades. The method returns information such as the bid price, quantity, time of the trade, etc.

Get Historical Trades on Binance
The get_historical_trades() method returns historical data for a symbol’s trade.
If you do not pass a trade id value to the fromid attribute of the get_historical_trades() method, the method will return the most recent trades.

Get Binance Average Symbol Price
You can get the average price of a symbol using the get_avg_price() method over a period.
Get All Binance Tickers Prices
You can get different types of price information, such as price change, percentage price change, previous closing price, last price, etc., of a symbol using the get_tickers() method.

Account and Sub-Account Endpoints
Using the account and sub-account endpoints, you can get information about your assets, trades, orders, etc.
Account Endpoint
Get Binance Account Info
The get_account() method returns general information about your Binance account, e.g., the type of your account, assets you hold, etc.

Get Binance Asset Details
You can retrieve details of all account assets using the get_asset_details() method. You will see the withdrawal fee, minimum withdrawal amount, withdrawal status, etc., of all your account assets. You’ll get an error if using a test account.

You can get the balance of an account asset using the get_asset_balance() method. The asset symbol is passed as a parameter to the method, as shown in the script below:
Get Asset Dividend History
Finally, to get the dividend history of all your account assets, you can call the get_asset_dividend_history().
Get Binance Trades
You can retrieve information about your trades for a particular symbol using the get_my_trades() method:
Order Endpoint
The order endpoint contains functions to fetch your orders, create a new order, check order status, cancel an order, etc.
Fetch All Binance Orders
To fetch all your Binance selling or buying orders for a symbol, you can use the get_all_orders() method.
Place Binance Order
Placing a new binance order via the Python API can be tricky initially. The python-binance library contains the create_test_order() method that lets you test if your order meets the required criteria for being placed on the Binance exchange. Once you test your order, you can call the create_order() method to place an order.
As an example, the following script places a market-type buying order for the BTCUSD symbol.

Once you execute the above script, you will see the following error.
The error says that the order failed the MIN_NOTIONAL filter. You can only place an order if it passes all the filters. See the details of different types of Binance order filters.
To get symbol values for a specific filter, you can use the get_symbol_info() method.

In the output, you will see various filter values. For instance, in the output below, you can see that the LOT_SIZE for BTCUSD it’s 0.00000100 and the MIN_NOTIONAL is 10.
To get a better view, you can display all filter values in a Pandas dataframe using the following script.

Let’s determine the value of our prior test order.
The price * 0.0005, our previous order amount, is 8.38. This is less than our MIN_NOTIONAL, which is why it failed. If you run into a lot size or any other error when creating orders, the filters will be your guide.
Let’s resolve our issue and buy 0.005 BTCBUSD.
Once you validate your test order, you can place an actual order using the create_order() method, as shown in the following script:
- order_limit_buy()
- order_limit_sell()
- order_market_buy()
- order_market_sell()
- order_oco_buy()
- order_oco_sell()
Check Binance Order Status
You can check the current status of the order you placed using the get_order() method. You must pass your order’s symbol and id as parameter values to the get_order() method.
Cancel Binance Order
Finally, as the following script demonstrates, you can cancel your Binance order using the cancel_order() method.
Get Binance Sub Account List
Binance allows its corporate and VIP individual users to create sub-accounts. With sub-accounts, users can divide responsibilities and manage transactions in a more organized manner.
You can get a list of all your sub-accounts using the get_sub_account_list() method, as shown in the following script:
Margin Trading Endpoints
Binance margin trading endpoints allow you to perform various margin trading tasks. In simplest terms, margin trading refers to buying and selling stocks using borrowed money.
To access Binance margin trading endpoints, you must create a margin trading account with Binance.
You can create a cross-margin trading account or an isolated margin trading account. In cross-margin trading, all your margin accounts share risk. On the contrary, in isolated margin trading, the risk margin is independent for each trading pair.
Binance Margin Trading Accounts Endpoint
Binance margin trading account endpoints allow you to create cross-margin and isolated margin trading accounts and get various information about your margin trading account.
Get Cross-Margin Account
You can create a cross-margin trading account through your Binance dashboard.
Once you create your cross-margin account, you can get general information about the account using the get_margin_account() method.
Create an Isolated Margin Account
You can create an isolated margin trading account using the create_isolated_margin_account() method of the python-binance library. You must pass base and quote asset values for your isolated margin trading account.
Get Isolated Margin Account Info
You can retrieve details of your isolated margin trading account using the get_isolated_margin_account() method.
Binance Margin Trading Market Data Endpoint
Get Cross-Margin Asset Info
The get_margin_asset() method returns details of an asset you can buy or sell via margin trading. Here is an example:
Get Cross-Margin Symbol Info
Similarly, you can use the get_margin_symbol() method to get information about if you can trade a symbol via margin trading. Here is an example:
Binance Margin-Trading Orders Endpoint
The python-binance library also provides functions for placing margin trading orders. By default, these endpoints functions create orders using your cross-margin account. For an isolated margin account, you must pass True as the value for the isolated parameter.
Fetch All Margin Trading Orders
The get_all_margin_orders() method returns all your orders involved in margin trading.
Place a Margin Trading Order
You can place a margin trading order using the create_margin_order() method. The syntax is similar to creating simple Binance orders, as shown below:
Check Margin Trading Order Status
Similarly, you can use the get_margin_order() method to find the status of your margin trading order.
Cancel a Margin Trading Order
Finally, you can cancel your margin trading order using the cancel_margin_order() method.
Binance Loans Endpoint
Binance loans endpoints allow you to borrow and repay Binance margin trading loans.
Create Loan
The create_margin_loan() method allows you to borrow a loan for margin trading. For instance, the following script creates a margin loan of quantity 1.1 for Ethereum.
Repay Loan
To repay a loan, you can use the repay_margin_loan() method, as demonstrated in the following script:
Get Loan Details
Finally, to get details of a borrowed or repaid loan, you can use the get_margin_loan_details() method. You must pass the asset’s name and the transaction id to the get_margin_loan_details() method.
Get Binance All Margin Trades
Finally, you can retrieve information about your margin trades for a particular symbol using the get_margin_trades method, as shown in the following example:
Working with Binance WebSockets
Installing WebSockets Library
The python-binance library contains ThreadedWebSocketManager class, which you can use to retrieve streaming data from the Binance API. I ran into an issue while using the ThreadedWebSocketManager class. After a bit of research, I found that the issue is due to a bug in the API.
You can use the Python WebSockets library to retrieve streaming data from Binance. The websockets library is not specifically designed for Binance API. You can use the websockets library to retrieve streaming data via WebSockets from any API.
You can install the websockets library via the following pip command.
Now let’s import the required libraries.
Retrieving Streaming Data from Binance
- wss://stream.binance.com:9443
- wss://stream.binance.com:443
You must append the URL of the raw stream that you want to retrieve with the base endpoint URL. Your final URL should look like this:
wss://stream.binance.com:9443//ws/<streamName>
If you go to the official documentation, you can see the raw URL for various streams. For example, the raw stream for the latest trade is <symbol>@trade.
The final URL for retrieving the latest trades via WebSockets will be as follows:
wss://stream.binance.com:9443//ws/<symbol>@trade
Here you need to replace the symbol value with the ticker, e.g., “btcusdt.”
Let’s see an example.
Binance WebSockets Streaming Prices
We also need to define the functions for the websocket client.
With the socket set and the functions created, let’s run this thing forever… or at least until we escape it.

Here is the output of the above script:
This is great, but it’s not easy to see. Let’s convert this to a dataframe.

Binance WebSockets Candlesticks (Kline)
Most technical analysts use candlesticks to trade. Let’s create 1-minute bars with the kline stream.
We’ll add the OHLCV values to a list, and on close we’ll add it to a dataframe.

Common Errors and Issues Accessing Binance API
Server Time Synchronization Error
You might get a server time error while accessing Binance server time. For instance, executing the following script on a Windows machine returned an error for me:

You can solve this error by going to Windows -> Setting-> Time & Language -> Date & Time -> ‘Sync Now’, as shown in the following screenshot:
Invalid API Key Error
Another common error you will likely encounter is the Invalid API-Key error. For instance, executing the following script using the Binance Spot Test Network returns an invalid key error:
This error usually occurs when you access Binance sapi/wapi endpoints via the Spot Test Network, as the Spot Test Network does not support these endpoints.

To see if a method calls a sapi/wapi endpoint, click the method name from the python-binance API; you will see the underlying REST API call. You can see from the REST API call if the method calls a sapi/wapi endpoint.
You can access these endpoints only through a live Binance trading account.
Binance Alternatives
Following are some alternatives to Binance:
Frequently Asked Questions
Is Python-Binance API Safe?
Synk.io security scan of the python-Binance API reveals one vulnerability or license issue with the python-binance API. The overall health score of the library is 68/100. The library is generally considered secure as users do not report any security breaches.
Can I Share My Binance API Key?
Binance recommends that you never share your API key or secret with anyone.
Does Binance Provide Private Keys?
Binance is a centralized exchange and doesn’t provide its users with a private key.
What Clients Are Available for Binance API?
Apart from Python, Binance clients are available in the Java, PHP, Node, .NET and Go programming languages.
How to Delete My Binance API Key
To delete a Binance API key, go to your dashboard, click your profile icon from the top-right corner and click “API Management”. A list of your API Keys will appear. Click the “Delete” button for the API Key you want to delete.
The Bottom Line
With the largest daily trading volume, Binance is the world’s leading cryptocurrency exchange allowing you to buy and sell the most commonly traded cryptocurrencies. Binance’s secure cold wallet ensures the security and safety of your crypto data. In addition to an easy-to-use GUI interface, Binance offers a rich REST API.
In this article, you saw some options to connect to the Binance API via the Python programming language. The information in this tutorial can help you develop cryptocurrency software and automate your Binance trading tasks using a trading bot. Moreover, machine learning and data science researchers can leverage the python-binance API for financial data research.
Introduction
![]()
APIs, or application programming interfaces, have become an essential tool for developers looking to access data on cryptocurrency markets. These APIs allow developers to retrieve real-time data on the prices, trading volumes, and other market movements of various cryptocurrencies. This data can then be used to build a variety of applications, such as trading bots, portfolio trackers, and market analysis tools.
In this article, we will take a closer look at Binance API. I will show you how to access list of available crypto pairs in Binance exchange and also download historical Klines data.
What is Binance
Binance is a cryptocurrency exchange platform that allows users to trade various cryptocurrencies such as Bitcoin, Ethereum, and Litecoin. It was founded in 2017 and is based in Malta. Binance is one of the largest cryptocurrency exchanges in the world in terms of trading volume.
What are Cryptocurrencies
Cryptocurrency is a digital or virtual currency that uses cryptography for security. It operates independently of a central bank or government. Cryptocurrencies use decentralized systems, typically a blockchain, to record transactions and manage the issuance of new units. Some examples of cryptocurrencies include Bitcoin, Ethereum, Litecoin, and Ripple. These currencies can be traded on cryptocurrency exchanges and can also be used to purchase goods and services. Cryptocurrencies are still considered a relatively new and highly volatile asset class and their long-term value and usage is yet to be determined.
Generate API key and Secret Key from Binance
API keys are used to identify the calling party and to track and control the usage of an API. They are typically a string of characters that are passed in an API request to identify the calling party. API keys are used to provide secure and restricted access to an API. They allow the API provider to track usage and bill customers, as well as limit the number of requests a user can make in a given time period.
API keys also allows the provider to monitor the usage of the API, and to take action if an application is making an excessive number of requests or if the usage pattern appears to be malicious. Additionally, API keys can be used to authenticate the identity of the calling party and to ensure that only authorized parties are able to access the API. This helps to protect the API and its users from unauthorized access and abuse.
To create new API and Secret Key you just need to login to your Binance account (or create new if you don’t have one), click on your account icon and head to API Management. Here you can create new API and generate keys. Make sure to copy both API Key and Secret Key.
Python code
And here is actual code. I have commented most of the lines to make it easier to understand.
Binance Python API – A Step-by-Step Guide
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.
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.
Why should I use the Binance API?
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.
Commissions are very competitive and you may be hard-pressed to find another exchange with lower fees.
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.
The most important part, when Binance got hacked in 2019, and more than $40 million was stolen, Binance covered the users that were impacted.
Why shouldn’t I use the Binance API?
While security is a big plus point for Binance when it comes to exchanges, there are better alternatives, depending on your needs.
If your primary interest is trading Bitcoin, you might be better off trading Bitcoin futures with a regulated broker like Interactive Brokers for example.
The benefit of a regulated broker is that they have insurance schemes in place to protect the consumer.
If trading futures is not your thing, there are several regulated brokers that offer CFD trading on cryptocurrencies which can be a good alternative.
It should be noted that these options don’t have nearly as extensive of an offering as Binance. And in most cases, the trading fees are significantly higher.
Another challenge with API trading at Binance is that API changes occur often.
API changes are generally a good thing. It means the exchange is trying to update and improve their infrastructure (most of the time).
However, this involves keeping a close eye on Binance’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.
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.
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.
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.
What are the alternatives to using the Binance API?
Coinmarketcap has more than 300 exchanges listed in its database, and many of them offer an API. So there isn’t a shortage of alternatives.
Some of the names that stand out from their list as well-established exchanges include Coinbase, Kraken, Bitfinex, Bitstamp, and Bittrex.
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.
» Before you run your strategies, you need data to design and backtest them. Quandl provides (mostly) free data that can be useful.
(Yes, Quandl has crypto data such as this and this)
Are there any Python libraries available for the Binance API?
There are several third-party libraries available, the most popular is python-binance.
There is an interesting story on how this library came to be the most popular Python library for Binance.
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).
At the time of the contest, BNB was trading below $2 but it surged to a high $691 in the first half of 2021!
There were several good submissions for the Python category but python-binance ultimately won.
This was a clever approach to ensure the best developers worked hard to create a good library.
Another popular library is CCXT. This library supports over a hundred different exchanges and is available in many different programming languages.
A third and perhaps lesser known option is Binance Connector which appears like it could be an official library as it is hosted under Binance’s Github page. There is also a recommendation and link to it in the Binance API documentation.
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.
The advantage to Python Binance is that a lot of people use it so it’s easy to get support and help from other users.
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’t a lot of documentation or usage examples available for it.
How do I get started with the Binance API?
Sign up with Binance
The first step is to create an account with Binance. You only need to enter your email and create a password – https://accounts.binance.com/en/register
Optionally, if you’re interested in using a Referral ID, you can use ZCYOCDMQ to receive a 10% discount off your trading fees.
That’s my Referral ID, thanks for supporting me! – Jignesh
You will be asked if you want to enable two-factor authentication for additional security. We highly recommend that you do. If you’ve never used it before, you will need to install Google Authenticator.
There are tutorials on getting started on things like your first deposit and much more on Binance Academy.
Obtaining an API key
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.
Next, you will be asked to create a label for the API key. If you plan to create multiple keys, it’s a good idea to use a descriptive name here so that you can easily distinguish it later on.
If you have two-factor authentication enabled, you will be asked to authenticate once again at this point.
Binance will send you an email to confirm the API key creation. Click on the confirmation link from your confirmation email to proceed.
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.
In such a scenario, you will need to delete your API key and start over again by creating a new one.
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.
Before moving forward, there are a few settings here that we need to take a look at.
The Read Only option is selected by default, and you likely won’t be able to uncheck it.
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 Only, but you can still perform other operations with this option checked.
There is also an option to Enable Trading, Enable Withdrawals, and Enable Future.
If you’re still testing out the API, it might be a good idea to leave these unchecked. If you’re ready to start trading, then check off the Enable Trading box and the Enable Future box if you plan to trade futures.
For some people, the Enable Future box won’t be shown here. That means the account is not set up for trading futures.
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.
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 Derivatives option in the top menu bar.
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.
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.
If you intend on running your script from a virtual private server such as AWS, this shouldn’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.
There are third-party solutions, such as noip.com that provide a way around not having a static IP.
Installing the python-binance library
The easiest way to install the python-binance library is to use pip. From the command line, simply type:
Securing your API keys
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’t run at the risk of revealing your credentials.
This can be done via the command prompt. Here is the syntax for Windows users.
You can verify that the keys are saved right from the command prompt by launching Python. Here is an example:
And this is how you can store environment variables on a Mac or in a Linux environment using the terminal.
We can later retrieve these values from within our Python trading script by using the os library.
Does Binance offer a demo account?
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.
Start by going to the Binance Spot Test Network website, you can find it here – https://testnet.binance.vision/
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.
Once you’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.
Choose the option to generate a HMAC key. In the next step, enter in descriptive name for your key.
After clicking generate, you will be taken to a screen that displays your key. If you leave this screen, you won’t be able to access they secret key again, and will have to start over.
Once you’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.
At the time of writing, the python-binance library, which we’ve used in all the examples, does not support the Test Network. However, we will discuss a workaround in the next step.
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.
How do I retrieve my account balance using the Binance API?
Now that we’ve installed the library and obtained API keys, it’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.
We start with our imports. We will need the Client class from the python-binance library as well as the os library to retrieve the API keys that we stored as environment variables.
Next, we store our API key and secret to local variables.
And finally, we initialize our client and pass through the API key and secret. We are all set to start accessing the API at t his point.
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:
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.
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.
This might be a bit too much information. If we are only interested in our BTC balance, we can use another endpoint.
If you’re after the balance details of another asset, simply switch out BTC with the asset you are after.
Account balances for futures accounts are separate from the main balance and therefore require a different endpoint.
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.
If you’re not familiar with margin trading, you can check out the Binance guide: What is Margin Trading for more details and the Binance Margin Trading Guide for setup instructions.
How can I retrieve the latest price for Bitcoin?
There are several methods to get the latest price for Bitcoin. The simplest one involves using the get_symbol_ticker function.
You can pass through any ticker here as opposed to BTCUSDT if you’re after another asset.
The code above will print out a dictionary that contains the symbol and the price. Here is an example output –
We can access just the price as follows.
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.
Using the Binance WebSocket for the latest Bitcoin price
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.
We need to import the ThreadedSocketManager to use this function, along with the sleep function from the time module.
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.
Then, we will create a function that will tell the socket manager what to do when it receives new data.
For now, we will just print the last closing price to the screen.
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.
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.
A latter example involving the websocket expands on the error checking part.
You may have noticed that Binance doesn’t use full variable names. IE the close price comes over the websocket in a variable called ‘c’ rather than ‘close’. Binance probably did this to keep the overall size of the message minimal in an attempt to boost communication speed.
If you’re ever trying to program a new websocket connection and are unsure what the variables stand for, check out the Binance API documentation. They have a detailed explanation of what each component of the websocket message is used for.
The next step is to initialize the socket manager. When we do that, the library will create a new thread which we’ve started in the code snippet above.
We will call the start_symbol_ticker_socket which has similar output to the get_symbol_ticker function of the API that we discussed earlier.
We need to pass through a symbol, which in this case is BTCUSDT. We also specify it to call our custom btc_trade_history function every time a new message comes in.
If you’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 Trade History box that is on the Binance webpage under the spot trading section.
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.
Binance has several websocket streams and we can easily add more.
The code snippet above subscribes to the ticker price for ETHUSDT. We kept the callback as btc_trade_history. That means when a new message arrives for ETHUSDT, it will get handled by the same btc_trade_history function we created.
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.
When you’re done with the WebSocket, use the following syntax to properly terminate it:
The WebSocket can deliver various data. To get a full view of what is available, type the following in your Python terminal.
This will list all the different methods available as well as give some information about the returned data.
Here is an example for the start_symbol_ticker_socket:
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.
This is another way to figure out that msg[‘b’] returns the best bid, besides checking the documentation.
How can I get Bitcoin’s historical price data in CSV format?
We will request historical Bitcoin price data from the Binance API and then outline four options to save that data to a CSV file.
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.
In the code snippet above, we’ve called the ._get_earliest_valid_timestamp function and passed in BTCUSDT as our symbol and 1d as our timeframe. The output is saved to a variable.
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’ve used our timestamp variable for that.
Lastly, this function by default calls the last 500 points of data. The maximum is 1000 so we’ve increased the limit to the maximum.
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.
In an effort to be ‘kind’ to the API, there is a sleep function built-in after every third call. So this could take a while if you’re looking for say 1-minute data from the very start.
Binance began operations over the summer of 2017, so that will likely be the earliest price point available.
Here is a definition of the data returned as per the Binance API documentation.
Now that we have our date, let’s go through four different options to save it to a file.
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 import json .
The second method uses csv writer to save the list as a CSV file. Make sure to import csv .
The third option doesn’t use any library. We’ve created an f string which is a native function of Python 3 and above.
There is a bit more flexibility here. We’ve taken advantage of it and only saved the first five columns: date, open, high, low, close.
Alternatively, you can also delete the additional columns, if you don’t need them, like this:
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.
We’ve passed through our data into a DataFrame and defined the columns. Since we’ve deleted some unwanted columns, there are only five that need to be defined.
This is what our DataFrame looks like at this point –
The date column has been set as an index which makes it a time-series indexed DataFrame. This way, it’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.
Lastly, we can export the DataFrame as a CSV file.
UPDATE August 30, 2021: Binance has launched a new website that hosts historical market data for both the spot and futures markets.
The website can be accessed by clicking on the following URL – Binance Data Collection
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.
At this point, you can pick the type of data you’re after. The common data types are:
- aggTrades – Tick data aggregated into 10 second blocks
- klines – Also known as candles or bars. This data has the OHLC format (Open, High, Low, Close)
- Trades – A record of all the trades that took place. Also known as tick data
The data is in ZIP format. Once unzipped, it will be in CSV format.
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.
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.
Further, the python-binance library implements delays in certain market data requests (like tick data) to ensure you don’t accidentally receive an API ban by overloading the API.
Should I trade futures or spot? What is the difference?
In the futures market, you can enter a contract to buy a cryptocurrency at a later date. This means you don’t take actual ownership if you enter in a trade to.
In fact, most futures traders never take ownership. Trading futures is mostly for speculative purposes, even though it was designed for other reasons.
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.
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.
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.
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.
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.
Here are a few reasons you may not want to trade futures:
- You plan to trade many different crypto’s, possibly against each other – the current futures offering from Binance is currently limited to popular USDT pairs.
- You want to own crypto and maybe store it in an offline wallet.
The Binance API uses a different endpoint for futures trading. But if you’re using the python-binance library, these endpoints are already configured in the library.
Further, the futures functions within the library have been appropriately labeled to distinguish them from the spot markets.
As an example, if you’re trading spot, you would use the following function to access your open orders:
If you’re trading futures, you would use:
How to access technical indicators such as the 20 SMA?
There are several libraries available that ease the process of calculating technical indicators.
We’ve already discussed how you can export a DataFrame as a CSV file. There’s a lot more you can do with Pandas and calculating a moving average is one of them.
Here’s an example:
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.
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.
As you can see, a new column has been created with the 20 moving average.
Let’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.
We can use the same mean() function and just run it on the last 20 rows of the DataFrame like this:
There is a lot more Pandas can do. We can easily grab the highest price Bitcoin traded this year as follows –
But Pandas isn’t able to calculate other technical indicators such as RSI, or MACD. The Binance API does not provide this info either.
TA-LIB has been a popular library for some time. We recently got a chance to test out a new library – bta-lib.
This library was created by the author of Backtrader. He discusses on his blog that TA-LIB has several indicators that were improperly implemented.
Further, TA-LIB wasn’t designed for Python. There is a wrapper available but there is much less overhead going with a solution designed for Python.
Bta-lib can be installed using PIP as follows.
Let’s try calculating the same moving average with the library as a comparison –
We now have a separate DataFrame that contains the values for the moving average. It looks like this:
Note that bta-lib will return an object to our sma variable. To access the DataFrame that is contained within it, simply type .df after the variable name.
By default, the library uses the 30 period moving average.
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.
Let’s create a few more indicators. Here is how we can calculate the RSI using the bta-lib library –
Once again, an object containing a df has been returned. We can access the very last value like this.
In a live environment, you might only need the very last value.
Here is how we can calculate the MACD for Bitcoin in bta-lib.
Finally, we will join our RSI and MACD values to our original Bitcoin price DataFrame
And now we have all our calculations easily accessible from one DataFrame –
How to fire an order for Ethereum using the Binance API?
The library we are using has a function that allows us to create test orders. Here is an example:
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.
If we change the type in the above code to ‘MARKET’ for example, it will throw an exception. The reason being is that a timeInForce and price parameters are not used for market orders. Instead, a market order would look like this:
Once your satisfied the syntax is correct, simply swap out the create_test_order function for the create_order function .
Note: If you’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.
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.
In addition to the client and the custom exceptions, we have imported binance.enums, which we will discuss shortly.
Here is the order code block.
An order confirmation will be sent back from the exchange and stored in our buy_limit variable. This is what it looks like:
It is in a dictionary format. Note that it contains an orderId. We can use this id to cancel the limit order like this –
Once again, we receive confirmation. We can print out the cancel variable to view it.
The create_order function is the main method to place an order. We can pass through several parameters here.
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:
Here are some of the helper functions you might want to use:
- order_limit_buy()
- order_limit_sell()
- order_market_buy()
- order_market_sell()
- order_oco_buy()
- order_ocosell()
The last two are considered advanced order types. OCO stands for One Cancels the Other.
A good example of this is when you’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.
Some of the order types require string constants such as ‘MARKET‘ or ‘BUY‘. Another broker might use ‘MKT‘ instead and so there isn’t always a logical answer as to what you should use.
You can look these up in the documentation if needed. Alternatively, the library has hard coded strings into variables that you can use.
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.
Here is an example of an order without using the built-in variables:
And here is the same thing using the built-in variables.
If you plan to go this route, you will need the enums import discussed earlier.
A full list of all the hard coded strings can be found here .
How to implement a stop loss or take profit using the Binance API?
The method to place stop losses or take profits differs with cryptocurrencies compared to other markets such as stocks or Forex.
The reason being, with stocks, you have a base currency. This is often in USD. Once you buy a stock, you are in a ‘trade’. At some point, you will want to sell that stock and return to your base USD currency.
With crypto, there really isn’t a concept of a base currency. When you conduct a trade, you are swapping one currency for another. The system doesn’t view it as a ‘trade’ that you eventually want to get out of.
For this reason, Binance does not allow you to natively attach a stop loss and a take profit to your main order.
But we can still implement one manually.
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.
Going back to our ETH order, here is how we can implement a stop loss and take profit.
Note that we are passing in both a stopPrice and a stopLimitPrice. Once the stopPrice level gets hit, a limit order will be placed using the stopLimitPrice. In most cases, the prices will be the same for both of these parameters.
While most assets accept stop-loss limit order, not all of them do. Before placing your order, it’s a good idea to check if it is supported.
You can use the exchange info endpoint for this.
Here is the response –
Under orderTypes, it shows that a stop-loss limit is indeed accepted for this asset.
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.
How to use Binance Coin (BNB) for discounted trading commissions?
Commissions add up quickly, but fortunately, there is a discount scheme.
The image above shows the fee schedule and discounts for trading the spot market. There are discounts for futures trading too.
You can either qualify for a discount depending on your trading volume or the quantity of Binance coin you own.
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.
If you’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.
Keep in mind, if you’re using BNB to pay for trading fees, your balance will reduce over time.
The function below ensures there is a minimum amount of BNB in your account and tops it up if there isn’t.
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.
As an example, we can call the above function like this –
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.
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.
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 –
This is where you can enable and disable the option to pay for trading fees with BNB.
How to execute a trade on ETH when BTC hits a certain price?
In the next example, we will place a buy order in Ethereum when Bitcoin crosses above the $10,000 price point.
We will use the Binance WebSocket to track the price of Bitcoin.
The code above looks very similar to the prior example where we showed how to use the WebSocket.
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.
However, since we need to use a try/except block for our order entry, it’s best not to as this could interfere with error checking that takes place on the back end, in the library.
We will start the WebSocket and direct it to the btc_pairs_trade function we just created.
Before getting started, a quick check to make sure we have data.
The above infinite loop will break as soon as soon as the WebSocket populates our price dictionary with a new value.
On to the main trade logic.
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.
After a buy order is sent, we break out of the loop and our script completes.
Don’t forget to terminate the WebSocket properly
How to execute an ETH trade when BTC moves 5% in the last 5 minutes?
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.
So if Bitcoin rallies more than 5% we buy Ethereum. If it declines by more than 5%, we will sell Ethereum.
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.
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.
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.
The callback function contains the code to populate the DataFrame from WebSocket data.
We are using the .loc function to append data into the DataFrame via the last index value. We use the length of the DataFrame to determine the index value.
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.
Now that we have our callback function created, we will start the WebSocket.
Once again, we will do a quick check to make sure data is streaming.
Before starting the main trade logic, we will put the script to sleep for five minutes since we need at least that much data.
In our main loop, we first grab our DataFrame from the dictionary file and assign it to the variable df. This step is not necessary but makes the code easier to read for our example.
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.
With the start_time value, we can filter our DataFrame down to contain only the last five minutes of data.
From there, we can use max() and min() functions from Pandas to find the highest and lowest price.
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.
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.
If the last price is 5% lower than the max price in our DataFrame, then we do the opposite.
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.
Once again, if our order gets filled, we will break out of our main loop and properly terminate the WebSocket.
This strategy, however, might be one that could be run indefinitely. If you don’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.
Otherwise, new orders will be sent on every tick until the 5% divergence gap closes.
Final Thoughts
Our overall view of Binance is that it is a great exchange. It’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.
If you plan on using the Binance API, we highly recommend joining their Telegram groups. They have one group for API announcements which will keep you up to date on any planned or unplanned outages.
They also have another group for general API discussions. This group is moderated and the admins are usually good at answering any API specific questions.
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.
Check out our article on the Interactive Brokers API 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.
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.
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.
If you’ve never used AWS before, they offer a free server for one year for new customers. The promotion is for a server on the ‘micro’ tier which is more than sufficient to run a basic Python script.
All the code examples used here are available for download on GitHub. 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!
Работа с API Binance: описание, код и примеры
Биржа binance, как и многие другие биржи, предоставляет API — программный интерфейс для автоматизации торговли. В этой статье рассмотрены методы и приведены примеры кода для работы с ними.
Официальное описание API (на английском) — здесь. Бот для Binance — здесь. Как получить API ключи — тут.
Вводная информация
В отличии от многих других бирж, Binance лимитирует не только количество запросов к API, но и «вес» запросов. Причем, это не какие-то фиксированные единицы, но целый комплекс (как они заявляют, англ). Например, если вы постоянно запрашиваете свечи но не торгуете, то ваш вес накапливается и вас могут забанить. И вообще они суровые — если вы постоянно перебиваете лучшую цену на минимальную ставку, или создаете/отменяете ордера но не покупаете и продаете и т.п. то вас настигнут санкции. Так что будьте аккуратны при тестировании ботов. Впрочем, пока я тестировал, ничего плохого не случилось, хотя я порой и жестил.
Если биржа захочет вам намекнуть, что пора бы снизить пыл, она вернет 429 ответ сервера. Если вы будете игнорировать этот ответ и ломиться в закрытую дверь, то вас забанят по IP на срок от 2 минут до 3 дней.
Подключение к API биржи идет через https://api.binance.com, для авторизованных запросов нужно отправлять ключ в заголовке X-MBX-APIKEY, и подписывать тело запроса SHA256.
Что бы вы не заморачивались с этим, я написал код, который позволяет все указанные запросы выполнять. Для его работы нужно установить Python версии 3.6+ с официального сайта, потом в командной строке выполнить pip install requests. Создайте папку (для удобства), создайте новый файл binance_api.py, и вставьте туда этот код:
Для тестирования методов, создайте в этой же папке второй файл, например, binance_test.py, туда вставьте вот такой код (подставьте свои API ключи):
После этого код можно запускать. К примеру, если вы только установили Python и не знаете, что делать, найдите редактор Idle (он устанавливается вместе с питоном), в нем File -> Open, откройте файл binance_test.py и нажмите F5. Код, представленный выше, вернет информацию по вашему аккаунту — подробности ниже.
Еще немного общей информации: практически во всех подписанных запросах необходимо указывать параметр timestamp — это текущее unix-время в милиосекундах. Но, так как некоторые сети бывают перегружены, то ваш запрос может заблудиться и придти позже. Поэтому биржа предоставляет вам временное окно (по умолчанию 5000 милисекунд). Если у вас запросы не успевают придти в это окно, вы можете его расширить с помощью параметра recvWindow. Но, думаю, это мало кому понадобится.
Публичные запросы
Проверка связи — /api/v1/ping
Метод для проверки работы API.
Возвращает пустой словарь
Ссылка для просмотра в браузере https://api.binance.com/api/v1/ping.
Вес — 1
Код для проверки:
Получение времени биржи — /api/v1/time
Ссылка для просмотра в браузере https://api.binance.com/api/v1/time
Вес — 1
Возвращает словарь с текущим временем:
Код для проверки:
Настройки и лимиты биржи — /api/v1/exchangeInfo
Ссылка для просмотра в браузере https://api.binance.com/api/v1/exchangeInfo
Вес — 1
Возвращает структуру данных:
Ключ rateLimits ведет на массив с лимитами — сколько запросов в секунду/минуту/день можно делать.
Ключ symbols содержит настройки для каждой пары — рассмотрим одну, ETHBTC
symbol — непосредственно пара
status — TRADING -разрешена торговля
baseAsset — базовая валюта
baseAssetPrecision — требуемое количество символов базовой валюты после запятой при создании ордера (для цены и количества)
quoteAsset — квотируемая валюта
quotePrecision — требуемое количество символов квотируемой валюты после запятой при создании ордера (для цены и количества)
«orderTypes»: [
«LIMIT»,
«LIMIT_MAKER»,
«MARKET»,
«STOP_LOSS_LIMIT»,
«TAKE_PROFIT_LIMIT»
] — допустимые виды ордеров по паре
icebergAllowed — разрешено ли создание айсбергов (ордеров с невидимой частью)
filters — ограничение ордеров
PRICE_FILTER — ограничение цены создаваемого ордера. Цена ордера должна быть в диапазоне min_price и max_price, и шаг торговли должен быть кратен tickSize. Да да, тут нельзя ставить ордера с произвольной ценой.
LOT_SIZE — ограничение объема создаваемого ордера. Объем должен быть в диапазоне minQty и maxQty, и быть кратен stepSize.
MIN_NOTIONAL — итоговая сумма ордера (объем*цена) должна быть выше minNotional.
Код для проверки:
Открытые ордера на бирже — /api/v1/depth
Метод позволяет получить книгу ордеров.
Принимает параметры:
Обязательные:
symbol — пара
Необязательные:
limit — кол-во возвращаемых записей от 5 до 1000 (по умолчанию 100). Допустимые значения: 5, 10, 20, 50, 100, 500, 1000. Еще можно указать 0, но он может вернуть большое кол-во данных.
Вес зависит от параметра limit. При лимите от 5 до 100 вес будет равен 1. Для параметра 500 вес составит 5. Для параметра 1000 вес будет 10.
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/depth?symbol=ETHBTC
Возвращает значения:
bids — это списки цен/объемов на покупку, asks — на продажу.
Пример кода:
Последние (чужие) сделки — /api/v1/trades
Принимает параметры:
Обязательные:
symbol — пара
Необязательные:
limit — кол-во возвращаемых записей (максимум 500, по умолчанию 500).
Вес — 1
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/trades?symbol=ETHBTC
Пример ответа:
id — id сделки
price — цена
qty — количество
time — время сделки
isBuyerMaker — была ли покупка по указанной покупателем цене,
isBestMatch — была ли встречная сделка
Пример кода:
Сжатая история сделок — /api/v1/aggTrades
Метод позволяет получить суммарную историю сделок. Сделки, выполненные в одно время по одному ордеру и по одной цене будут представлены одной строкой с объединенным количеством.
Вес — 1
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/aggTrades?symbol=ETHBTC
Принимает параметры:
Обязательные:
symbol — пара
Необязательные:
fromID — показывать начиная со сделки № (включительно)
startTime — начиная с какого времени (включительно)
endTime — заканчивая каким временем (включительно)
limit — Кол-во записей (максимум 500, по умолчанию 500)
Возвращает данные:
Данные по свечам – /api/v1/klines
Вес – 1
Ссылка для просмотра в браузере https://api.binance.com/api/v1/klines?symbol=LTCBTC&interval=5m
Параметры:
Обязательные:
symbol – пара
interval – период свечи
Допустимые интервалы:
• 1m // 1 минута
• 3m // 3 минуты
• 5m // 5 минут
• 15m // 15 минут
• 30m // 30 минут
• 1h // 1 час
• 2h // 2 часа
• 4h // 4 часа
• 6h // 6 часов
• 8h // 8 часов
• 12h // 12 часов
• 1d // 1 день
• 3d // 3 дня
• 1w // 1 неделя
• 1M // 1 месяц
Необязательные:
limit – кол-во свечей (максимум 500, по умолчанию 500)
startTime – время начала построения
endTime – окончание периода
Если не указаны параметры startTime и endTime, то возвращаются самые последние свечи.
Пример ответа:
Статистика за 24 часа — /api/v1/ticker/24hr
Вес – 1, если указана пара, иначе вес равен (количеству всех торгуемых пар)/2.
Ссылка для просмотра в браузере: https://api.binance.com/api/v1/ticker/24hr?symbol=BNBBTC
Параметры:
Необязательные:
symbol – пара
Если symbol не указан, возвращаются данные по всем парам. В этом случае, считается, что вы сделали столько запросов к бирже, сколько вернулось пар.
Пример ответа:
Если пар несколько, то такие словари вкладываются в массив, вот так:
Последняя цена по паре (или парам) — /api/v3/ticker/price
Вес — 1
Параметры:
Необязательные:
symbol – пара
Если параметр symbol не указан, то возвращаются цены по всем парам.
Ссылка для просмотра в браузере: https://api.binance.com/api/v3/ticker/price?symbol=BNBBTC
Пример ответа:
Или (если не указан параметр)
Лучшие цены покупки/продажи — /api/v3/ticker/bookTicker
Вес 1
Параметры:
Необязательные:
symbol – пара
Если параметр symbol не указан, возвращаются данные по всем парам.
Ссылка для просмотра в браузере: https://api.binance.com/api/v3/ticker/bookTicker?symbol=BNBBTC
Пример ответа:
Или (если не указан параметр):
Авторизованные запросы:
Создание ордера — /api/v3/order
Вес – 1
Метод: POST
Параметры:
Обязательные:
symbol – пара
side – тип ордера (BUY либо SELL)
type – тип ордера (LIMIT, MARKET, STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, LIMIT_MAKER)
quantity – количество к покупке
timestamp – текущее время в миллисекундах (в коде, выложенном здесь, проставляется автоматически, указывать не надо.
Необязательные:
timeInForce – (GTC, IOC, FOK). По умолчанию GTC. Расшифрую.
GTC (Good Till Cancelled) – ордер будет висеть до тех пор, пока его не отменят.
IOC (Immediate Or Cancel) – Будет куплено то количество, которое можно купить немедленно. Все, что не удалось купить, будет отменено.
FOK (Fill-Or-Kill) – Либо будет куплено все указанное количество немедленно, либо не будет куплено вообще ничего, ордер отменится.
price – цена
newClientOrderId – Идентификатор ордера, который вы сами придумаете (строка). Если не указан, генерится автоматически.
stopPrice – стоп-цена, можно указывать если тип ордера STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, или TAKE_PROFIT_LIMIT.
icebergQty – кол-во для ордера-айсберга, можно указывать, если тип ордера LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT
recvWindow – кол-во миллисекунд, которое прибавляется к timestamp и формирует окно действия запроса (см. выше). По умолчанию 5000.
newOrderRespType –какую информацию возвращать, если удалось создать ордер. Допустимые значения ACK, RESULT, или FULL, по умолчанию RESULT. Подробности ниже.
В зависимости от типа ордера, некоторые поля становятся обязательными:
Ордера типа LIMIT_MAKER – это ордера типа обычного LIMIT, но они отклонятся, если ордер при выставлении может выполниться по рынку. Другими словами, вы никогда не будете тейкером, ордер либо выставится выше/ниже рынка, либо не выставится вовсе.
Ордера типа STOP_LOSS и TAKE_PROFIT исполнятся по рынку (ордер типа MARKET), как только будет достигнута цена stopPrice.
Любые ордера LIMIT или LIMIT_MAKER могут формировать ордер-айсберг, установив параметр icebergQty.
Если установлен параметр icebergQty, то параметр timeInForce ОБЯЗАТЕЛЬНО должен иметь значение GTC.
Для того, что бы выставлять цены, противоположные текущим для ордеров типов MARKET и LIMIT:
Цена выше рыночной: STOP_LOSS BUY, TAKE_PROFIT SELL
Цена ниже рыночной: STOP_LOSS SELL, TAKE_PROFIT BUY
При создании ордера вернется ответ, в зависимости от параметра newOrderRespType: